hablas-ai 2.2.13 → 2.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +195 -184
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,198 +1,209 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],
|
|
4
|
-
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n
|
|
2
|
+
"use strict";var Ic=Object.create;var qn=Object.defineProperty;var Pc=Object.getOwnPropertyDescriptor;var Mc=Object.getOwnPropertyNames;var jc=Object.getPrototypeOf,Lc=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Dc=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Mc(e))!Lc.call(t,n)&&n!==r&&qn(t,n,{get:()=>e[n],enumerable:!(s=Pc(e,n))||s.enumerable});return t};var k=(t,e,r)=>(r=t!=null?Ic(jc(t)):{},Dc(e||!t||!t.__esModule?qn(r,"default",{value:t,enumerable:!0}):r,t));var kt=I(zr=>{var zt=class extends Error{constructor(e,r,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Vr=class extends zt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};zr.CommanderError=zt;zr.InvalidArgumentError=Vr});var Kt=I(Gr=>{var{InvalidArgumentError:Fc}=kt(),Kr=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new Fc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Nc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Gr.Argument=Kr;Gr.humanReadableArgName=Nc});var Yr=I(Bn=>{var{humanReadableArgName:Uc}=Kt(),Jr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&r.push(s),this.sortSubcommands&&r.sort((n,i)=>n.name().localeCompare(i.name())),r}compareOptions(e,r){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?r.push(s):s.long&&!i?r.push(e.createOption(s.long,s.description)):s.short&&!n&&r.push(e.createOption(s.short,s.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(s=>Uc(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((s,n)=>Math.max(s,r.subcommandTerm(n).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((s,n)=>Math.max(s,r.argumentTerm(n).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,r){let s=r.padWidth(e,r),n=r.helpWidth||80,i=2,o=2;function a(u,g){if(g){let m=`${u.padEnd(s+o)}${g}`;return r.wrap(m,n-i,s+o)}return u}function l(u){return u.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],f=r.commandDescription(e);f.length>0&&(c=c.concat([r.wrap(f,n,0),""]));let d=r.visibleArguments(e).map(u=>a(r.argumentTerm(u),r.argumentDescription(u)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let h=r.visibleOptions(e).map(u=>a(r.optionTerm(u),r.optionDescription(u)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let u=r.visibleGlobalOptions(e).map(g=>a(r.optionTerm(g),r.optionDescription(g)));u.length>0&&(c=c.concat(["Global Options:",l(u),""]))}let p=r.visibleCommands(e).map(u=>a(r.subcommandTerm(u),r.subcommandDescription(u)));return p.length>0&&(c=c.concat(["Commands:",l(p),""])),c.join(`
|
|
4
|
+
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,s,n=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-s;if(a<n)return e;let l=e.slice(0,s),c=e.slice(s).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${a-1}}([${
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
10
|
-
(Did you mean one of ${
|
|
11
|
-
(Did you mean ${
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Kc(e,r)}argument(e,r,n
|
|
13
|
-
Expecting one of '${
|
|
14
|
-
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=
|
|
6
|
+
`),f=" ".repeat(s),h="\\s\u200B",p=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),u=c.match(p)||[];return l+u.map((g,m)=>g===`
|
|
8
|
+
`?"":(m>0?f:"")+g.trimEnd()).join(`
|
|
9
|
+
`)}};Bn.Help=Jr});var es=I(Zr=>{var{InvalidArgumentError:qc}=kt(),Xr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Hc(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new qc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Bc(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Qr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,r){let s=r.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return r.negate===(i===e)}};function Bc(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Hc(t){let e,r,s=t.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),r=s.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}Zr.Option=Xr;Zr.DualOptions=Qr});var Wn=I(Hn=>{function Wc(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let s=0;s<=t.length;s++)r[s]=[s];for(let s=0;s<=e.length;s++)r[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=t.length;n++){let i=1;t[n-1]===e[s-1]?i=0:i=1,r[n][s]=Math.min(r[n-1][s]+1,r[n][s-1]+1,r[n-1][s-1]+i),n>1&&s>1&&t[n-1]===e[s-2]&&t[n-2]===e[s-1]&&(r[n][s]=Math.min(r[n][s],r[n-2][s-2]+1))}return r[t.length][e.length]}function Vc(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Wc(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),r&&(s=s.map(o=>`--${o}`)),s.length>1?`
|
|
10
|
+
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
11
|
+
(Did you mean ${s[0]}?)`:""}Hn.suggestSimilar=Vc});var Jn=I(Gn=>{var zc=require("node:events").EventEmitter,ts=require("node:child_process"),ve=require("node:path"),rs=require("node:fs"),V=require("node:process"),{Argument:Kc,humanReadableArgName:Gc}=Kt(),{CommanderError:ss}=kt(),{Help:Jc}=Yr(),{Option:Vn,DualOptions:Yc}=es(),{suggestSimilar:zn}=Wn(),ns=class t extends zc{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>V.stdout.write(r),writeErr:r=>V.stderr.write(r),getOutHelpWidth:()=>V.stdout.isTTY?V.stdout.columns:void 0,getErrHelpWidth:()=>V.stderr.isTTY?V.stderr.columns:void 0,outputError:(r,s)=>s(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,s){let n=r,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),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),n?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Jc,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Kc(e,r)}argument(e,r,s,n){let i=this.createArgument(e,r);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,n]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,s){this._exitCallback&&this._exitCallback(new ss(e,r,s)),V.exit(e)}action(e){let r=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Vn(e,r)}_callParseArg(e,r,s,n){try{return e.parseArg(r,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let s=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 '${s}'
|
|
14
|
+
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=n=>[n.name()].concat(n.aliases()),s=r(e).find(n=>this._findCommand(n));if(s){let n=r(this._findCommand(s)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);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(s,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,r,s,n,i){if(typeof r=="object"&&r instanceof Vn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,s);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,c)=>{let f=a.exec(l);return f?f[0]:c},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,r,s,n){return this._optionEx({},e,r,s,n)}requiredOption(e,r,s,n){return this._optionEx({mandatory:!0},e,r,s,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,s){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(r=s.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){V.versions?.electron&&(r.from="electron");let n=V.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(r.from="eval")}e===void 0&&(e=V.argv),this.rawArgs=e.slice();let s;switch(r.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":V.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,r){let s=this._prepareUserArgs(e,r);return this._parseCommand([],s),this}async parseAsync(e,r){let s=this._prepareUserArgs(e,r);return await this._parseCommand([],s),this}_executeSubCommand(e,r){r=r.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,d){let h=ve.resolve(f,d);if(rs.existsSync(h))return h;if(n.includes(ve.extname(d)))return;let p=n.find(u=>rs.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=rs.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=ve.resolve(ve.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let d=ve.basename(this._scriptPath,ve.extname(this._scriptPath));d!==this._name&&(f=i(a,`${d}-${e._name}`))}o=f||o}s=n.includes(ve.extname(o));let l;V.platform!=="win32"?s?(r.unshift(o),r=Kn(V.execArgv).concat(r),l=ts.spawn(V.argv[0],r,{stdio:"inherit"})):l=ts.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Kn(V.execArgv).concat(r),l=ts.spawn(V.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{V.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 ss(f,"commander.executeSubCommandAsync","(close)")):V.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(
|
|
17
|
+
- ${d}`;throw new Error(h)}else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)V.exit(1);else{let d=new ss(1,"commander.executeSubCommandAsync","(error)");d.nestedError=f,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,s){let n=this._findCommand(e);n||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,r.concat(s));else return n._parseCommand(r,s)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),r[n]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),r==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,r,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,r))}),n}_parseCommand(e,r){let s=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),r=s.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],s=[],n=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){n===s&&n.push(l),n.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)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&s.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){n.push(l),i.length>0&&n.push(...i);break}n.push(l)}return{operands:r,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let s=0;s<r;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let
|
|
22
|
-
Expecting one of '${
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(
|
|
24
|
-
causes have become circular...`;let
|
|
25
|
-
caused by: `+ti(n,e)):r},Qc=t=>ti(t,new Set),ri=(t,e,r)=>{if(!kt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=nn(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+ri(s,e,i)}else return n},Zc=t=>ri(t,new Set);ni.exports={isErrorLike:kt,getErrorCause:nn,stackWithCauses:Qc,messageWithCauses:Zc}});var on=I((Vy,ii)=>{"use strict";var eu=Symbol("circular-ref-tag"),zt=Symbol("pino-raw-err-ref"),si=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[zt]},set:function(t){this[zt]=t}}});Object.defineProperty(si,zt,{writable:!0,value:{}});ii.exports={pinoErrProto:si,pinoErrorSymbols:{seen:eu,rawSymbol:zt}}});var li=I((Ky,ai)=>{"use strict";ai.exports=ln;var{messageWithCauses:tu,stackWithCauses:ru,isErrorLike:oi}=sn(),{pinoErrProto:nu,pinoErrorSymbols:su}=on(),{seen:an}=su,{toString:iu}=Object.prototype;function ln(t){if(!oi(t))return t;t[an]=void 0;let e=Object.create(nu);e.type=iu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=tu(t),e.stack=ru(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>ln(r)));for(let r in t)if(e[r]===void 0){let n=t[r];oi(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,an)&&(e[r]=ln(n)):e[r]=n}return delete t[an],e.raw=t,e}});var ui=I((zy,ci)=>{"use strict";ci.exports=Jt;var{isErrorLike:cn}=sn(),{pinoErrProto:ou,pinoErrorSymbols:au}=on(),{seen:Gt}=au,{toString:lu}=Object.prototype;function Jt(t){if(!cn(t))return t;t[Gt]=void 0;let e=Object.create(ou);e.type=lu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Jt(r))),cn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Gt)&&(e.cause=Jt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];cn(n)?Object.prototype.hasOwnProperty.call(n,Gt)||(e[r]=Jt(n)):e[r]=n}return delete t[Gt],e.raw=t,e}});var mi=I((Gy,pi)=>{"use strict";pi.exports={mapHttpRequest:cu,reqSerializer:di};var un=Symbol("pino-raw-req-ref"),fi=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[un]},set:function(t){this[un]=t}}});Object.defineProperty(fi,un,{writable:!0,value:{}});function di(t){let e=t.info||t.socket,r=Object.create(fi);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function cu(t){return{req:di(t)}}});var wi=I((Jy,yi)=>{"use strict";yi.exports={mapHttpResponse:uu,resSerializer:gi};var fn=Symbol("pino-raw-res-ref"),hi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[fn]},set:function(t){this[fn]=t}}});Object.defineProperty(hi,fn,{writable:!0,value:{}});function gi(t){let e=Object.create(hi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function uu(t){return{res:gi(t)}}});var pn=I((Yy,bi)=>{"use strict";var dn=li(),fu=ui(),Yt=mi(),Xt=wi();bi.exports={err:dn,errWithCause:fu,mapHttpRequest:Yt.mapHttpRequest,mapHttpResponse:Xt.mapHttpResponse,req:Yt.reqSerializer,res:Xt.resSerializer,wrapErrorSerializer:function(e){return e===dn?e:function(n){return e(dn(n))}},wrapRequestSerializer:function(e){return e===Yt.reqSerializer?e:function(n){return e(Yt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Xt.resSerializer?e:function(n){return e(Xt.resSerializer(n))}}}});var mn=I((Xy,xi)=>{"use strict";function du(t,e){return e}xi.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=du;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var Ti=I((Qy,$i)=>{"use strict";function hn(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=hn(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=hn(t[r]));return e}return t}function vi(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function Si(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function _i(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var Qt=Symbol("PATH_NOT_FOUND");function pu(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Qt;r=r[n]}return r}function mu(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function hu(t,e,r,n=!1){for(let s of e){let i=vi(s);if(i.includes("*"))ki(t,i,r,s,n);else if(n)_i(t,i);else{let o=pu(t,i);if(o===Qt)continue;let a=typeof r=="function"?r(o,i):r;Si(t,i,a)}}}function ki(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else gu(t,e,r,i,n,s)}function gu(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let m=0;m<u.length;m++)l[d]=m.toString(),c(u[m],d+1);else if(typeof u=="object"&&u!==null)for(let m in u)l[d]=m,c(u[m],d+1)}else if(d<o.length){let m=o[d];u&&typeof u=="object"&&u!==null&&m in u&&(l[d]=m,c(u[m],d+1))}else if(a.includes("*"))ki(u,a,typeof r=="function"?(p,f)=>{let g=[...l.slice(0,d),...f];return r(p,g)}:r,s,i);else if(i)_i(u,a);else{let m=typeof r=="function"?r(mu(u,a),[...l.slice(0,d),...a]):r;Si(u,a,m)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let m=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[m],l[d]=m}u!=null&&c(u,o.length)}}function yu(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=vi(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function wu(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let c=l.toString();s.has(c)||s.has("*")?a[l]=r(n[l],s.get(c)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function bu(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function xu(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)bu(e)}function vu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;xu(e);let o=yu(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=wu(l,o),u=l,d=r;return typeof r=="function"&&(d=r),hu(c,e,d,i),n===!1?(c.restore=function(){return hn(u)},c):typeof n=="function"?n(c):JSON.stringify(c)}}$i.exports=vu});var it=I((Zy,Ci)=>{"use strict";var Su=Symbol("pino.setLevel"),_u=Symbol("pino.getLevel"),ku=Symbol("pino.levelVal"),$u=Symbol("pino.levelComp"),Tu=Symbol("pino.useLevelLabels"),Cu=Symbol("pino.useOnlyCustomLevels"),Eu=Symbol("pino.mixin"),Au=Symbol("pino.lsCache"),Ou=Symbol("pino.chindings"),Ru=Symbol("pino.asJson"),Iu=Symbol("pino.write"),Mu=Symbol("pino.redactFmt"),ju=Symbol("pino.time"),Pu=Symbol("pino.timeSliceIndex"),Lu=Symbol("pino.stream"),Du=Symbol("pino.stringify"),Fu=Symbol("pino.stringifySafe"),Nu=Symbol("pino.stringifiers"),Uu=Symbol("pino.end"),qu=Symbol("pino.formatOpts"),Bu=Symbol("pino.messageKey"),Hu=Symbol("pino.errorKey"),Wu=Symbol("pino.nestedKey"),Vu=Symbol("pino.nestedKeyStr"),Ku=Symbol("pino.mixinMergeStrategy"),zu=Symbol("pino.msgPrefix"),Gu=Symbol("pino.wildcardFirst"),Ju=Symbol.for("pino.serializers"),Yu=Symbol.for("pino.formatters"),Xu=Symbol.for("pino.hooks"),Qu=Symbol.for("pino.metadata");Ci.exports={setLevelSym:Su,getLevelSym:_u,levelValSym:ku,levelCompSym:$u,useLevelLabelsSym:Tu,mixinSym:Eu,lsCacheSym:Au,chindingsSym:Ou,asJsonSym:Ru,writeSym:Iu,serializersSym:Ju,redactFmtSym:Mu,timeSym:ju,timeSliceIndexSym:Pu,streamSym:Lu,stringifySym:Du,stringifySafeSym:Fu,stringifiersSym:Nu,endSym:Uu,formatOptsSym:qu,messageKeySym:Bu,errorKeySym:Hu,nestedKeySym:Wu,wildcardFirstSym:Gu,needsMetadataGsym:Qu,useOnlyCustomLevelsSym:Cu,formattersSym:Yu,hooksSym:Xu,nestedKeyStrSym:Vu,mixinMergeStrategySym:Ku,msgPrefixSym:zu}});var yn=I((ew,Ri)=>{"use strict";var Ei=Ti(),{redactFmtSym:Zu,wildcardFirstSym:Zt}=it(),gn=/[^.[\]]+|\[([^[\]]*?)\]/g,Ai="[Redacted]",Oi=!1;function ef(t,e){let{paths:r,censor:n,remove:s}=tf(t),i=r.reduce((l,c)=>{gn.lastIndex=0;let u=gn.exec(c),d=gn.exec(c),m=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(m==="*"&&(m=Zt),d===null)return l[m]=null,l;if(l[m]===null)return l;let{index:p}=d,f=`${c.substr(p,c.length-1)}`;return l[m]=l[m]||[],m!==Zt&&l[m].length===0&&l[m].push(...l[Zt]||[]),m===Zt&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(f)}),l[m].push(f),l},{}),o={[Zu]:Ei({paths:r,censor:n,serialize:e,strict:Oi,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=u=>a(u,[c]);else{let u=typeof n=="function"?(d,m)=>n(d,[c,...m]):n;l[c]=Ei({paths:i[c],censor:u,serialize:e,strict:Oi,remove:s})}return l},o)}function tf(t){if(Array.isArray(t))return t={paths:t,censor:Ai},t;let{paths:e,censor:r=Ai,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}Ri.exports=ef});var ji=I((tw,Mi)=>{"use strict";var rf=()=>"",nf=()=>`,"time":${Date.now()}`,sf=()=>`,"time":${Math.round(Date.now()/1e3)}`,of=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,af=1000000n,Ii=1000000000n,lf=BigInt(Date.now())*af,cf=process.hrtime.bigint(),uf=()=>{let t=process.hrtime.bigint()-cf,e=lf+t,r=e/Ii,n=e%Ii,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Mi.exports={nullTime:rf,epochTime:nf,unixTime:sf,isoTime:of,isoTimeNano:uf}});var Li=I((rw,Pi)=>{"use strict";function ff(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Pi.exports=df;function df(t,e,r){var n=r&&r.stringify||ff,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",u=1-s,d=-1,m=t&&t.length||0,p=0;p<m;){if(t.charCodeAt(p)===37&&p+1<m){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(c+=t.slice(d,p));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=p+2,p++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=p+2,p++;break}c+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<m&&(c+=t.slice(d)),c)}});var bn=I((nw,wn)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));wn.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};wn.exports=t}});var Wi=I((sw,Hi)=>{"use strict";var N=require("fs"),pf=require("events"),mf=require("util").inherits,Di=require("path"),vn=bn(),hf=require("assert"),er=100,tr=Buffer.allocUnsafe(0),gf=16*1024,Fi="buffer",Ni="utf8",[yf,wf]=(process.versions.node||"0.0").split(".").map(Number),bf=yf>=22&&wf>=7;function Ui(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&N.mkdirSync(Di.dirname(t),{recursive:!0});let i=N.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?N.mkdir(Di.dirname(t),{recursive:!0},i=>{if(i)return r(i);N.open(t,n,s,r)}):N.open(t,n,s,r)}function me(t){if(!(this instanceof me))return new me(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:m,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||gf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,g;if(m===Fi)this._writingBuf=tr,this.write=Sf,this.flush=kf,this.flushSync=Tf,this._actualWrite=Ef,f=()=>N.writeSync(this.fd,this._writingBuf),g=()=>N.write(this.fd,this._writingBuf,this.release);else if(m===void 0||m===Ni)this._writingBuf="",this.write=vf,this.flush=_f,this.flushSync=$f,this._actualWrite=Cf,f=()=>Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?N.write(this.fd,this._writingBuf,this.release):N.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ni}" and "${Fi}", but passed ${m}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ui(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(h,b)=>{if(h){if((h.code==="EAGAIN"||h.code==="EBUSY")&&this.retryEAGAIN(h,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{vn(er),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(g,er);else this._writing=!1,this.emit("error",h);return}this.emit("write",b);let w=xn(this._writingBuf,this._len,b);if(this._len=w.len,this._writingBuf=w.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let S=f(),E=xn(this._writingBuf,this._len,S);this._len=E.len,this._writingBuf=E.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&N.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,rr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(xf,this)):this.emit("drain"))},this.on("newListener",function(h){h==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function xn(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function xf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}mf(me,pf);function qi(t,e){return t.length===0?tr:t.length===1?t[0]:Buffer.concat(t,e)}function vf(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Sf(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Bi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{N.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function _f(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Bi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function kf(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Bi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}me.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&N.close(e,r=>{if(r)return this.emit("error",r)})}),Ui(this.file,this)};me.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():rr(this)))};function $f(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?N.writeSync(this.fd,t):N.writeSync(this.fd,t,"utf8"),r=xn(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;vn(er)}}try{N.fsyncSync(this.fd)}catch{}}function Tf(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=tr);let t=tr;for(;this._bufs.length||t.length;){t.length<=0&&(t=qi(this._bufs[0],this._lens[0]));try{let e=N.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;vn(er)}}}me.prototype.destroy=function(){this.destroyed||rr(this)};function Cf(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?N.writeSync(this.fd,this._writingBuf):N.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else N.write(this.fd,this._writingBuf,t)}function Ef(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:qi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=N.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else bf&&(this._writingBuf=Buffer.from(this._writingBuf)),N.write(this.fd,this._writingBuf,t)}function rr(t){if(t.fd===-1){t.once("ready",rr.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],hf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{N.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?N.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}me.SonicBoom=me;me.default=me;Hi.exports=me});var Sn=I((iw,Ji)=>{"use strict";var he={exit:[],beforeExit:[]},Vi={exit:Rf,beforeExit:If},ot;function Af(){ot===void 0&&(ot=new FinalizationRegistry(Mf))}function Of(t){he[t].length>0||process.on(t,Vi[t])}function Ki(t){he[t].length>0||(process.removeListener(t,Vi[t]),he.exit.length===0&&he.beforeExit.length===0&&(ot=void 0))}function Rf(){zi("exit")}function If(){zi("beforeExit")}function zi(t){for(let e of he[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}he[t]=[]}function Mf(t){for(let e of["exit","beforeExit"]){let r=he[e].indexOf(t);he[e].splice(r,r+1),Ki(e)}}function Gi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Of(t);let n=new WeakRef(e);n.fn=r,Af(),ot.register(e,n),he[t].push(n)}function jf(t,e){Gi("exit",t,e)}function Pf(t,e){Gi("beforeExit",t,e)}function Lf(t){if(ot!==void 0){ot.unregister(t);for(let e of["exit","beforeExit"])he[e]=he[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ki(e)}}Ji.exports={register:jf,registerBeforeExit:Pf,unregister:Lf}});var Yi=I((ow,Df)=>{Df.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Qi=I((aw,Xi)=>{"use strict";function Ff(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Nf(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Xi.exports={wait:Ff,waitDiff:Nf}});var eo=I((lw,Zi)=>{"use strict";Zi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var po=I((cw,fo)=>{"use strict";var{version:Uf}=Yi(),{EventEmitter:qf}=require("events"),{Worker:Bf}=require("worker_threads"),{join:Hf}=require("path"),{pathToFileURL:Wf}=require("url"),{wait:Vf}=Qi(),{WRITE_INDEX:Se,READ_INDEX:He,SEQ_INDEX:_n}=eo(),Kf=require("buffer"),zf=require("assert"),v=Symbol("kImpl"),Gf=Kf.constants.MAX_STRING_LENGTH;function to(){}function Cn(t,e){Atomics.add(t[v].state,_n,1),e(),Atomics.add(t[v].state,_n,1),Atomics.notify(t[v].state,_n)}function ro(t){Cn(t,()=>{Atomics.store(t[v].state,He,0),Atomics.store(t[v].state,Se,0)})}var $t=class{constructor(e){this._value=e}deref(){return this._value}},nr=class{register(){}unregister(){}},Jf=process.env.NODE_V8_COVERAGE?nr:global.FinalizationRegistry||nr,Yf=process.env.NODE_V8_COVERAGE?$t:global.WeakRef||$t,no=new Jf(t=>{t.exited||t.terminate()});function Xf(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Hf(__dirname,"lib","worker.js"),o=new Bf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Wf(r).href,dataBuf:t[v].dataBuf,stateBuf:t[v].stateBuf,workerData:{$context:{threadStreamVersion:Uf},...n}}});return o.stream=new $t(t),o.on("message",Qf),o.on("exit",oo),no.register(t,o),o}function so(t){zf(!t[v].sync),t[v].needDrain&&(t[v].needDrain=!1,t.emit("drain"))}function io(t){for(;;){let e=Atomics.load(t[v].state,Se),r=t[v].data.length-e;if(r>0){if(t[v].bufLen===0){t[v].flushing=!1,t[v].ending?En(t):t[v].needDrain&&process.nextTick(so,t);return}co(t,r,to);continue}if(r===0){if(e===0&&t[v].bufLen===0)return;sr(t,()=>{t.destroyed||(ro(t),io(t))});return}ae(t,new Error("overwritten"));return}}function Qf(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new Yf(e),sr(e,()=>{e[v].ready=!0,e.emit("ready")});break;case"ERROR":ae(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){ae(e,new Error("this should not happen: "+t.code));break}let r=e[v].flushCallbacks.get(t.id);r&&(e[v].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ae(e,new Error("this should not happen: "+t.code))}}function oo(t){let e=this.stream.deref();e!==void 0&&(no.unregister(e),e.worker.exited=!0,e.worker.off("exit",oo),ae(e,t!==0?new Error("the worker thread exited"):null))}var $n=class extends qf{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[v]={},this[v].stateBuf=new SharedArrayBuffer(128),this[v].state=new Int32Array(this[v].stateBuf),this[v].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[v].data=Buffer.from(this[v].dataBuf),this[v].sync=e.sync||!1,this[v].ending=!1,this[v].ended=!1,this[v].needDrain=!1,this[v].destroyed=!1,this[v].flushing=!1,this[v].ready=!1,this[v].finished=!1,this[v].errored=null,this[v].closed=!1,this[v].buf=[],this[v].bufHead=0,this[v].bufLen=0,this[v].flushCallbacks=new Map,this[v].nextFlushId=0,this.worker=Xf(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[v].destroyed)return Tn(this,new Error("the worker has exited")),!1;if(this[v].ending)return Tn(this,new Error("the worker is ending")),!1;if(this[v].flushing&&this[v].bufLen+r.length>=Gf)try{kn(this),this[v].flushing=!0}catch(n){return ae(this,n),!1}if(this[v].buf.push(r),this[v].bufLen+=r.length,this[v].sync)try{return kn(this),!0}catch(n){return ae(this,n),!1}return this[v].flushing||(this[v].flushing=!0,setImmediate(io,this)),this[v].needDrain=this[v].data.length-this[v].bufLen-Atomics.load(this[v].state,Se)<=0,!this[v].needDrain}end(){this[v].destroyed||(this[v].ending=!0,En(this))}flush(e){e=typeof e=="function"?e:to,ao(this,r=>{if(r){process.nextTick(e,r);return}lo(this,e)})}flushSync(){this[v].destroyed||(kn(this),uo(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[v].ready}get destroyed(){return this[v].destroyed}get closed(){return this[v].closed}get writable(){return!this[v].destroyed&&!this[v].ending}get writableEnded(){return this[v].ending}get writableFinished(){return this[v].finished}get writableNeedDrain(){return this[v].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[v].errored}};function ao(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].sync&&(t[v].flushing||t[v].bufLen>0)){setImmediate(ao,t,e);return}sr(t,e)}function sr(t,e){let r=Atomics.load(t[v].state,Se);Vf(t[v].state,He,r,1/0,(n,s)=>{if(n){ae(t,n),e(n);return}if(s!=="ok"){sr(t,e);return}e()})}function lo(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].ready){let n=()=>{i(),lo(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[v].nextFlushId;t[v].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[v].flushCallbacks.delete(r),ae(t,n),process.nextTick(e,n)}}function Zf(t,e){let r=t[v].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function Tn(t,e){setImmediate(()=>{t.emit("error",e)})}function ae(t,e){t[v].destroyed||(t[v].destroyed=!0,Zf(t,e),e&&(t[v].errored=e,Tn(t,e)),t.worker.exited?setImmediate(()=>{t[v].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[v].closed=!0,t.emit("close")}))}function co(t,e,r){let s=Atomics.load(t[v].state,Se),i=e;for(;i>0&&t[v].bufLen!==0;){let o=t[v].bufHead,a=t[v].buf[o];if(a.length<=i){a.copy(t[v].data,s),s+=a.length,i-=a.length,t[v].bufLen-=a.length,t[v].bufHead=o+1,t[v].bufHead===t[v].buf.length?(t[v].buf.length=0,t[v].bufHead=0):t[v].bufHead>=1024&&t[v].bufHead*2>=t[v].buf.length&&(t[v].buf.splice(0,t[v].bufHead),t[v].bufHead=0);continue}a.copy(t[v].data,s,0,i),t[v].buf[o]=a.subarray(i),t[v].bufLen-=i,s+=i,i=0}return Cn(t,()=>{Atomics.store(t[v].state,Se,s)}),r(),!0}function En(t){if(!(t[v].ended||!t[v].ending||t[v].flushing)){t[v].ended=!0;try{t.flushSync();let e=Atomics.load(t[v].state,He);Cn(t,()=>{Atomics.store(t[v].state,Se,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[v].state,He,e,1e3),e=Atomics.load(t[v].state,He),e===-2){ae(t,new Error("end() failed"));return}if(++r===10){ae(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[v].finished=!0,t.emit("finish")})}catch(e){ae(t,e)}}}function kn(t){let e=()=>{t[v].ending?En(t):t[v].needDrain&&process.nextTick(so,t)};for(t[v].flushing=!1;t[v].bufLen!==0;){let r=Atomics.load(t[v].state,Se),n=t[v].data.length-r;if(n===0){uo(t),ro(t);continue}else if(n<0)throw new Error("overwritten");co(t,n,e)}}function uo(t){if(t[v].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[v].state,Se),r=0;for(;;){let n=Atomics.load(t[v].state,He);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[v].state,He,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}fo.exports=$n});var Rn=I((uw,go)=>{"use strict";var{createRequire:ed}=require("module"),{existsSync:td}=require("node:fs"),rd=mn(),{join:An,isAbsolute:ho,sep:nd}=require("node:path"),{fileURLToPath:sd}=require("node:url"),id=bn(),On=Sn(),od=po();function ad(t){On.register(t,dd),On.registerBeforeExit(t,pd),t.on("close",function(){On.unregister(t)})}function ld(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function cd(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&mo(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(mo(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function mo(t){let e=ud(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=sd(r)}catch{return!1}return ho(r)&&!td(r)}function ud(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function fd(t,e,r,n,s){if(!r.execArgv&&ld()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=cd(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new od({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&ad(i)}function a(){i.closed||(i.flushSync(),id(100),i.end())}return i}function dd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function pd(t){t.flushSync()}function md(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=rd(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||An(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:p(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(g=>({...g,level:f.level,target:p(g.target)})))):e&&(d=u["pino-worker"]||An(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:p(f.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let m=r||e?"pino.transport":d;return fd(p(d),l,i,a,m);function p(f){if(f=u[f]||f,ho(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return An(__dirname,"..","file.js");let g;for(let h of c)try{let b=h==="node:repl"?process.cwd()+nd:h;g=ed(b).resolve(f);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${f}"`);return g}}go.exports=md});var ar=I((fw,Ao)=>{"use strict";var hd=require("node:diagnostics_channel"),yo=Li(),{mapHttpRequest:gd,mapHttpResponse:yd}=pn(),Mn=Wi(),wo=Sn(),{lsCacheSym:wd,chindingsSym:_o,writeSym:bo,serializersSym:ko,formatOptsSym:xo,endSym:bd,stringifiersSym:$o,stringifySym:To,stringifySafeSym:jn,wildcardFirstSym:Co,nestedKeySym:xd,formattersSym:Eo,messageKeySym:vd,errorKeySym:Sd,nestedKeyStrSym:_d,msgPrefixSym:ir}=it(),{isMainThread:kd}=require("worker_threads"),$d=Rn(),[Td]=process.versions.node.split(".").map(t=>Number(t)),vo=hd.tracingChannel("pino_asJson"),In=Td>=25?t=>JSON.stringify(t):Ed;function at(){}function Cd(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=gd(n):typeof n.setHeader=="function"&&(n=yd(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[bo](n,yo(i,o,this[xo]),t)}else{let i=n===void 0?s.shift():n;typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[bo](null,yo(i,s,this[xo]),t)}}}function Ed(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function Ad(t,e,r,n){if(vo.hasSubscribers===!1)return So.call(this,t,e,r,n);let s={instance:this,arguments};return vo.traceSync(So,s,this,t,e,r,n)}function So(t,e,r,n){let s=this[To],i=this[jn],o=this[$o],a=this[bd],l=this[_o],c=this[ko],u=this[Eo],d=this[vd],m=this[Sd],p=this[wd][r]+n;p=p+l;let f;u.log&&(t=u.log(t));let g=o[Co],h="";for(let w in t)if(f=t[w],Object.prototype.hasOwnProperty.call(t,w)&&f!==void 0){c[w]?f=c[w](f):w===m&&c.err&&(f=c.err(f));let x=o[w]||g;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":x&&(f=x(f));break;case"string":f=(x||In)(f);break;default:f=(x||s)(f,i)}if(f===void 0)continue;let S=In(w);h+=","+S+":"+f}let b="";if(e!==void 0){f=c[d]?c[d](e):e;let w=o[d]||g;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":w&&(f=w(f)),b=',"'+d+'":'+f;break;case"string":f=(w||In)(f),b=',"'+d+'":'+f;break;default:f=(w||s)(f,i),b=',"'+d+'":'+f}}return this[xd]&&h?p+this[_d]+h.slice(1)+"}"+b+a:p+h+b+a}function Od(t,e){let r,n=t[_o],s=t[To],i=t[jn],o=t[$o],a=o[Co],l=t[ko],c=t[Eo].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Rd(t){return t.write!==t.constructor.prototype.write}function or(t){let e=new Mn(t);return e.on("error",r),!t.sync&&kd&&(wo.register(e,Id),e.on("close",function(){wo.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=at,e.end=at,e.flushSync=at,e.destroy=at;return}e.removeListener("error",r),e.emit("error",n)}}function Id(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Md(t){return function(r,n,s={},i){if(typeof s=="string")i=or({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=or({dest:i})}else if(s instanceof Mn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof Mn||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=$d({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=at),i||(Rd(process.stdout)?i=process.stdout:i=or({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function jd(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[jn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Pd(t,e,r){return{level:t,bindings:e,log:r}}function Ld(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Ao.exports={noop:at,buildSafeSonicBoom:or,asChindings:Od,asJson:Ad,genLog:Cd,createArgsNormalizer:Md,stringify:jd,buildFormatters:Pd,normalizeDestFileDescriptor:Ld}});var lr=I((dw,Oo)=>{var Dd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Fd={ASC:"ASC",DESC:"DESC"};Oo.exports={DEFAULT_LEVELS:Dd,SORTING_ORDER:Fd}});var Dn=I((pw,jo)=>{"use strict";var{lsCacheSym:Nd,levelValSym:Pn,useOnlyCustomLevelsSym:Ud,streamSym:qd,formattersSym:Bd,hooksSym:Hd,levelCompSym:Ro}=it(),{noop:Wd,genLog:We}=ar(),{DEFAULT_LEVELS:be,SORTING_ORDER:Io}=lr(),Mo={fatal:t=>{let e=We(be.fatal,t);return function(...r){let n=this[qd];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>We(be.error,t),warn:t=>We(be.warn,t),info:t=>We(be.info,t),debug:t=>We(be.debug,t),trace:t=>We(be.trace,t)},Ln=Object.keys(be).reduce((t,e)=>(t[be[e]]=e,t),{}),Vd=Object.keys(Ln).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Kd(t){let e=t[Bd].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Nd]=n,t}function zd(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Gd(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[Pn],s=this[Pn]=r[t],i=this[Ud],o=this[Ro],a=this[Hd].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Wd;continue}this[l]=zd(l,i)?Mo[l](a):We(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Jd(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Yd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Ro](r,this[Pn])}function Xd(t,e,r){return t===Io.DESC?e<=r:e>=r}function Qd(t){return typeof t=="string"?Xd.bind(null,t):t}function Zd(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Ln,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:be,t);return{labels:n,values:s}}function ep(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Ln).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:be,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function tp(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function rp(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Io).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}jo.exports={initialLsCache:Vd,genLsCache:Kd,levelMethods:Mo,getLevel:Jd,setLevel:Gd,isLevelEnabled:Yd,mappings:Zd,assertNoLevelCollisions:tp,assertDefaultLevelFound:ep,genLevelComparison:Qd,assertLevelComparison:rp}});var Fn=I((mw,Po)=>{"use strict";Po.exports={version:"10.3.1"}});var Ho=I((gw,Bo)=>{"use strict";var{EventEmitter:np}=require("node:events"),{lsCacheSym:sp,levelValSym:ip,setLevelSym:Un,getLevelSym:Lo,chindingsSym:ur,mixinSym:op,asJsonSym:Fo,writeSym:ap,mixinMergeStrategySym:lp,timeSym:cp,timeSliceIndexSym:up,streamSym:No,serializersSym:Ve,formattersSym:Tt,errorKeySym:fp,messageKeySym:dp,useOnlyCustomLevelsSym:pp,needsMetadataGsym:mp,redactFmtSym:hp,stringifySym:gp,formatOptsSym:yp,stringifiersSym:wp,msgPrefixSym:qn,hooksSym:bp}=it(),{getLevel:xp,setLevel:vp,isLevelEnabled:Sp,mappings:_p,initialLsCache:kp,genLsCache:$p,assertNoLevelCollisions:Tp}=Dn(),{asChindings:Bn,asJson:Cp,buildFormatters:Nn,stringify:Do,noop:Uo}=ar(),{version:Ep}=Fn(),Ap=yn(),Op=class{},qo={constructor:Op,child:Rp,bindings:Ip,setBindings:Mp,flush:Lp,isLevelEnabled:Sp,version:Ep,get level(){return this[Lo]()},set level(t){this[Un](t)},get levelVal(){return this[ip]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[qn]},get[Symbol.toStringTag](){return"Pino"},[sp]:kp,[ap]:Pp,[Fo]:Cp,[Lo]:xp,[Un]:vp};Object.setPrototypeOf(qo,np.prototype);Bo.exports=function(){return Object.create(qo)};var cr=t=>t;function Rp(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Ve],n=this[Tt],s=Object.create(this);if(e==null)return s[Tt].bindings!==cr&&(s[Tt]=Nn(n.level,cr,n.log)),s[ur]=Bn(s,t),this.onChild!==Uo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ve]=Object.create(null);for(let c in r)s[Ve][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[Ve][c]=r[c]}for(let c in e.serializers)s[Ve][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[Ve][c]=e.serializers[c]}}else s[Ve]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[Tt]=Nn(a||n.level,l||cr,c||n.log)}else s[Tt]=Nn(n.level,cr,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Tp(this.levels,e.customLevels),s.levels=_p(e.customLevels,s[pp]),$p(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Ap(s.redact,Do),l={stringify:a[hp]};s[gp]=Do,s[wp]=a,s[yp]=l}if(typeof e.msgPrefix=="string"&&(s[qn]=(this[qn]||"")+e.msgPrefix),s[ur]=Bn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Un](a)}return this.onChild(s),s}function Ip(){let e=`{${this[ur].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Mp(t){let e=Bn(this,t);this[ur]=e}function jp(t,e){return Object.assign(e,t)}function Pp(t,e,r){let n=this[cp](),s=this[op],i=this[fp],o=this[dp],a=this[lp]||jp,l,c=this[bp].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Fo](l,e,r,n),d=this[No];d[mp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[up]),d.lastLogger=this),d.write(c?c(u):u)}function Lp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[No];typeof e.flush=="function"?e.flush(t||Uo):t&&t()}});var zo=I((Kn,Ko)=>{"use strict";var{hasOwnProperty:Ct}=Object.prototype,ze=Vn();ze.configure=Vn;ze.stringify=ze;ze.default=ze;Kn.stringify=ze;Kn.configure=Vn;Ko.exports=ze;var Dp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ie(t){return t.length<5e3&&!Dp.test(t)?`"${t}"`:JSON.stringify(t)}function Hn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var Fp=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Wn(t){return Fp.call(t)!==void 0&&t.length!==0}function Wo(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Np(t){if(Ct.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Up(t){let e;if(Ct.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function qp(t,e){let r;if(Ct.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Vo(t,e){let r;if(Ct.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ke(t){return t===1?"1 item":`${t} items`}function Bp(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Hp(t){if(Ct.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Vn(t){t={...t};let e=Hp(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Np(t),n=qp(t,"bigint"),s=Up(t),i=typeof s=="function"?s:void 0,o=Vo(t,"maximumDepth"),a=Vo(t,"maximumBreadth");function l(p,f,g,h,b,w){let x=f[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=h.call(f,p,x),typeof x){case"string":return Ie(x);case"object":{if(x===null)return"null";if(g.indexOf(x)!==-1)return r;let S="",E=",",_=w;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(x),b!==""&&(w+=b,S+=`
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${
|
|
20
|
+
`),this.outputHelp({error:!0}));let s=r||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in V.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,V.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Yc(this.options),r=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&r(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!r(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let s=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},n=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=zn(e,n)}let s=`error: unknown option '${e}'${r}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,s=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),r=zn(e,n)}let s=`error: unknown command '${e}'${r}`;this.error(s,{code:"commander.unknownCommand"})}version(e,r,s){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",s=s||"output the version number";let n=this.createOption(r,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(s=>Gc(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ve.basename(e,ve.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},s;return r.error?s=n=>this._outputConfiguration.writeErr(n):s=n=>this._outputConfiguration.writeOut(n),r.write=e.write||s,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let n=this.helpInformation(s);if(r&&(n=r(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=V.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${s.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(n=>r.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Kn(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],s=i[3],n=i[4]),r&&n!=="0"?`${r}=${s}:${parseInt(n)+1}`:e})}Gn.Command=ns});var Zn=I(ie=>{var{Argument:Yn}=Kt(),{Command:is}=Jn(),{CommanderError:Xc,InvalidArgumentError:Xn}=kt(),{Help:Qc}=Yr(),{Option:Qn}=es();ie.program=new is;ie.createCommand=t=>new is(t);ie.createOption=(t,e)=>new Qn(t,e);ie.createArgument=(t,e)=>new Yn(t,e);ie.Command=is;ie.Option=Qn;ie.Argument=Yn;ie.Help=Qc;ie.CommanderError=Xc;ie.InvalidArgumentError=Xn;ie.InvalidOptionArgumentError=Xn});var ls=I((Ny,oi)=>{"use strict";var $t=t=>t&&typeof t.message=="string",as=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return $t(r)?r:void 0}else return $t(e)?e:void 0},ni=(t,e)=>{if(!$t(t))return"";let r=t.stack||"";if(e.has(t))return r+`
|
|
24
|
+
causes have become circular...`;let s=as(t);return s?(e.add(t),r+`
|
|
25
|
+
caused by: `+ni(s,e)):r},Zc=t=>ni(t,new Set),ii=(t,e,r)=>{if(!$t(t))return"";let s=r?"":t.message||"";if(e.has(t))return s+": ...";let n=as(t);if(n){e.add(t);let i=typeof t.cause=="function";return s+(i?"":": ")+ii(n,e,i)}else return s},eu=t=>ii(t,new Set);oi.exports={isErrorLike:$t,getErrorCause:as,stackWithCauses:Zc,messageWithCauses:eu}});var cs=I((Uy,li)=>{"use strict";var tu=Symbol("circular-ref-tag"),Gt=Symbol("pino-raw-err-ref"),ai=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[Gt]},set:function(t){this[Gt]=t}}});Object.defineProperty(ai,Gt,{writable:!0,value:{}});li.exports={pinoErrProto:ai,pinoErrorSymbols:{seen:tu,rawSymbol:Gt}}});var fi=I((qy,ui)=>{"use strict";ui.exports=fs;var{messageWithCauses:ru,stackWithCauses:su,isErrorLike:ci}=ls(),{pinoErrProto:nu,pinoErrorSymbols:iu}=cs(),{seen:us}=iu,{toString:ou}=Object.prototype;function fs(t){if(!ci(t))return t;t[us]=void 0;let e=Object.create(nu);e.type=ou.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=ru(t),e.stack=su(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>fs(r)));for(let r in t)if(e[r]===void 0){let s=t[r];ci(s)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(s,us)&&(e[r]=fs(s)):e[r]=s}return delete t[us],e.raw=t,e}});var pi=I((By,di)=>{"use strict";di.exports=Yt;var{isErrorLike:ds}=ls(),{pinoErrProto:au,pinoErrorSymbols:lu}=cs(),{seen:Jt}=lu,{toString:cu}=Object.prototype;function Yt(t){if(!ds(t))return t;t[Jt]=void 0;let e=Object.create(au);e.type=cu.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=>Yt(r))),ds(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Jt)&&(e.cause=Yt(t.cause));for(let r in t)if(e[r]===void 0){let s=t[r];ds(s)?Object.prototype.hasOwnProperty.call(s,Jt)||(e[r]=Yt(s)):e[r]=s}return delete t[Jt],e.raw=t,e}});var yi=I((Hy,gi)=>{"use strict";gi.exports={mapHttpRequest:uu,reqSerializer:mi};var ps=Symbol("pino-raw-req-ref"),hi=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[ps]},set:function(t){this[ps]=t}}});Object.defineProperty(hi,ps,{writable:!0,value:{}});function mi(t){let e=t.info||t.socket,r=Object.create(hi);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 s=t.path;r.url=typeof s=="string"?s: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 uu(t){return{req:mi(t)}}});var Si=I((Wy,xi)=>{"use strict";xi.exports={mapHttpResponse:fu,resSerializer:bi};var hs=Symbol("pino-raw-res-ref"),wi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[hs]},set:function(t){this[hs]=t}}});Object.defineProperty(wi,hs,{writable:!0,value:{}});function bi(t){let e=Object.create(wi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function fu(t){return{res:bi(t)}}});var gs=I((Vy,vi)=>{"use strict";var ms=fi(),du=pi(),Xt=yi(),Qt=Si();vi.exports={err:ms,errWithCause:du,mapHttpRequest:Xt.mapHttpRequest,mapHttpResponse:Qt.mapHttpResponse,req:Xt.reqSerializer,res:Qt.resSerializer,wrapErrorSerializer:function(e){return e===ms?e:function(s){return e(ms(s))}},wrapRequestSerializer:function(e){return e===Xt.reqSerializer?e:function(s){return e(Xt.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Qt.resSerializer?e:function(s){return e(Qt.resSerializer(s))}}}});var ys=I((zy,_i)=>{"use strict";function pu(t,e){return e}_i.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=pu;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let s=r.slice(2),n=[];for(let i of s)i&&n.push(i.getFileName());return n}});var Ai=I((Ky,Ei)=>{"use strict";function ws(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]=ws(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]=ws(t[r]));return e}return t}function ki(t){let e=[],r="",s=!1,n=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!s&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),s=!0):a==="]"&&s?(e.push(r),r="",s=!1,n=!1):(a==='"'||a==="'")&&s?n?a===i?(n=!1,i=""):r+=a:(n=!0,i=a):r+=a}return r&&e.push(r),e}function $i(t,e,r){let s=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=r;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=r)}else typeof s=="object"&&s!==null&&n in s&&Object.prototype.hasOwnProperty.call(s,n)&&(s[n]=r);return!0}function Ti(t,e){let r=t;for(let n=0;n<e.length-1;n++){let i=e[n];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let n=0;n<r.length;n++)r[n]=void 0;else if(typeof r=="object"&&r!==null)for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&delete r[n]}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&delete r[s];return!0}var Zt=Symbol("PATH_NOT_FOUND");function hu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null||!(s in r))return Zt;r=r[s]}return r}function mu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null)return;r=r[s]}return r}function gu(t,e,r,s=!1){for(let n of e){let i=ki(n);if(i.includes("*"))Ci(t,i,r,n,s);else if(s)Ti(t,i);else{let o=hu(t,i);if(o===Zt)continue;let a=typeof r=="function"?r(o,i):r;$i(t,i,a)}}}function Ci(t,e,r,s,n=!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(n)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(n){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 yu(t,e,r,i,s,n)}function yu(t,e,r,s,n,i=!1){let o=e.slice(0,s),a=e.slice(s+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("*"))Ci(f,a,typeof r=="function"?(p,u)=>{let g=[...l.slice(0,d),...u];return r(p,g)}:r,n,i);else if(i)Ti(f,a);else{let h=typeof r=="function"?r(mu(f,a),[...l.slice(0,d),...a]):r;$i(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 wu(t){if(t.length===0)return null;let e=new Map;for(let r of t){let s=ki(r),n=e;for(let i=0;i<s.length;i++){let o=s[i];n.has(o)||n.set(o,new Map),n=n.get(o)}}return e}function bu(t,e){if(!e)return t;function r(s,n,i=0){if(!n||n.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let c=l.toString();n.has(c)||n.has("*")?a[l]=r(s[l],n.get(c)||n.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(n.has(a)||n.has("*")?o[a]=r(s[a],n.get(a)||n.get("*")):o[a]=s[a]);return o}return r(t,e)}function xu(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,s="";for(let n=0;n<t.length;n++){let i=t[n];if((i==='"'||i==="'")&&e>0)r?i===s&&(r=!1,s=""):(r=!0,s=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 Su(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)xu(e)}function vu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:s=JSON.stringify,strict:n=!0,remove:i=!1}=t;Su(e);let o=wu(e);return function(l){if(n&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let c=bu(l,o),f=l,d=r;return typeof r=="function"&&(d=r),gu(c,e,d,i),s===!1?(c.restore=function(){return ws(f)},c):typeof s=="function"?s(c):JSON.stringify(c)}}Ei.exports=vu});var nt=I((Gy,Oi)=>{"use strict";var _u=Symbol("pino.setLevel"),ku=Symbol("pino.getLevel"),$u=Symbol("pino.levelVal"),Tu=Symbol("pino.levelComp"),Cu=Symbol("pino.useLevelLabels"),Eu=Symbol("pino.useOnlyCustomLevels"),Au=Symbol("pino.mixin"),Ou=Symbol("pino.lsCache"),Ru=Symbol("pino.chindings"),Iu=Symbol("pino.asJson"),Pu=Symbol("pino.write"),Mu=Symbol("pino.redactFmt"),ju=Symbol("pino.time"),Lu=Symbol("pino.timeSliceIndex"),Du=Symbol("pino.stream"),Fu=Symbol("pino.stringify"),Nu=Symbol("pino.stringifySafe"),Uu=Symbol("pino.stringifiers"),qu=Symbol("pino.end"),Bu=Symbol("pino.formatOpts"),Hu=Symbol("pino.messageKey"),Wu=Symbol("pino.errorKey"),Vu=Symbol("pino.nestedKey"),zu=Symbol("pino.nestedKeyStr"),Ku=Symbol("pino.mixinMergeStrategy"),Gu=Symbol("pino.msgPrefix"),Ju=Symbol("pino.wildcardFirst"),Yu=Symbol.for("pino.serializers"),Xu=Symbol.for("pino.formatters"),Qu=Symbol.for("pino.hooks"),Zu=Symbol.for("pino.metadata");Oi.exports={setLevelSym:_u,getLevelSym:ku,levelValSym:$u,levelCompSym:Tu,useLevelLabelsSym:Cu,mixinSym:Au,lsCacheSym:Ou,chindingsSym:Ru,asJsonSym:Iu,writeSym:Pu,serializersSym:Yu,redactFmtSym:Mu,timeSym:ju,timeSliceIndexSym:Lu,streamSym:Du,stringifySym:Fu,stringifySafeSym:Nu,stringifiersSym:Uu,endSym:qu,formatOptsSym:Bu,messageKeySym:Hu,errorKeySym:Wu,nestedKeySym:Vu,wildcardFirstSym:Ju,needsMetadataGsym:Zu,useOnlyCustomLevelsSym:Eu,formattersSym:Xu,hooksSym:Qu,nestedKeyStrSym:zu,mixinMergeStrategySym:Ku,msgPrefixSym:Gu}});var xs=I((Jy,Mi)=>{"use strict";var Ri=Ai(),{redactFmtSym:ef,wildcardFirstSym:er}=nt(),bs=/[^.[\]]+|\[([^[\]]*?)\]/g,Ii="[Redacted]",Pi=!1;function tf(t,e){let{paths:r,censor:s,remove:n}=rf(t),i=r.reduce((l,c)=>{bs.lastIndex=0;let f=bs.exec(c),d=bs.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=er),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!==er&&l[h].length===0&&l[h].push(...l[er]||[]),h===er&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(u)}),l[h].push(u),l},{}),o={[ef]:Ri({paths:r,censor:s,serialize:e,strict:Pi,remove:n})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof s=="function"?(d,h)=>s(d,[c,...h]):s;l[c]=Ri({paths:i[c],censor:f,serialize:e,strict:Pi,remove:n})}return l},o)}function rf(t){if(Array.isArray(t))return t={paths:t,censor:Ii},t;let{paths:e,censor:r=Ii,remove:s}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(r=void 0),{paths:e,censor:r,remove:s}}Mi.exports=tf});var Di=I((Yy,Li)=>{"use strict";var sf=()=>"",nf=()=>`,"time":${Date.now()}`,of=()=>`,"time":${Math.round(Date.now()/1e3)}`,af=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,lf=1000000n,ji=1000000000n,cf=BigInt(Date.now())*lf,uf=process.hrtime.bigint(),ff=()=>{let t=process.hrtime.bigint()-uf,e=cf+t,r=e/ji,s=e%ji,n=Number(r*1000n+s/1000000n),i=new Date(n),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}.${s.toString().padStart(9,"0")}Z"`};Li.exports={nullTime:sf,epochTime:nf,unixTime:of,isoTime:af,isoTimeNano:ff}});var Ni=I((Xy,Fi)=>{"use strict";function df(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Fi.exports=pf;function pf(t,e,r){var s=r&&r.stringify||df,n=1;if(typeof t=="object"&&t!==null){var i=e.length+n;if(i===1)return t;var o=new Array(i);o[0]=s(t);for(var a=1;a<i;a++)o[a]=s(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-n,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+=s(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 vs=I((Qy,Ss)=>{"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));Ss.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 s=Date.now()+Number(e);for(;s>Date.now(););};Ss.exports=t}});var Ki=I((Zy,zi)=>{"use strict";var q=require("fs"),hf=require("events"),mf=require("util").inherits,Ui=require("path"),ks=vs(),gf=require("assert"),tr=100,rr=Buffer.allocUnsafe(0),yf=16*1024,qi="buffer",Bi="utf8",[wf,bf]=(process.versions.node||"0.0").split(".").map(Number),xf=wf>=22&&bf>=7;function Hi(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 s=e.append?"a":"w",n=e.mode;if(e.sync)try{e.mkdir&&q.mkdirSync(Ui.dirname(t),{recursive:!0});let i=q.openSync(t,s,n);r(null,i)}catch(i){throw r(i),i}else e.mkdir?q.mkdir(Ui.dirname(t),{recursive:!0},i=>{if(i)return r(i);q.open(t,s,n,r)}):q.open(t,s,n,r)}function he(t){if(!(this instanceof he))return new he(t);let{fd:e,dest:r,minLength:s,maxLength:n,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(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=n||0,this.maxWrite=i||yf,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,g;if(h===qi)this._writingBuf=rr,this.write=_f,this.flush=$f,this.flushSync=Cf,this._actualWrite=Af,u=()=>q.writeSync(this.fd,this._writingBuf),g=()=>q.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Bi)this._writingBuf="",this.write=vf,this.flush=kf,this.flushSync=Tf,this._actualWrite=Ef,u=()=>Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?q.write(this.fd,this._writingBuf,this.release):q.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Bi}" and "${qi}", 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=(m,x)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{ks(tr),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(g,tr);else this._writing=!1,this.emit("error",m);return}this.emit("write",x);let b=_s(this._writingBuf,this._len,x);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let v=u(),_=_s(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&q.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,sr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Sf,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function _s(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 Sf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}mf(he,hf);function Wi(t,e){return t.length===0?rr:t.length===1?t[0]:Buffer.concat(t,e)}function vf(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,s=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(t):s[s.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function _f(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||s[s.length-1]+t.length>this.maxWrite?(r.push([t]),s.push(t.length)):(r[r.length-1].push(t),s[s.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Vi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{q.fsync(this.fd,s=>{this._flushPending=!1,t(s)})}catch(s){t(s)}this.off("error",r)},r=s=>{this._flushPending=!1,t(s),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function kf(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Vi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function $f(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Vi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}he.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&&q.close(e,r=>{if(r)return this.emit("error",r)})}),Hi(this.file,this)};he.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():sr(this)))};function Tf(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?q.writeSync(this.fd,t):q.writeSync(this.fd,t,"utf8"),r=_s(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;ks(tr)}}try{q.fsyncSync(this.fd)}catch{}}function Cf(){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=rr);let t=rr;for(;this._bufs.length||t.length;){t.length<=0&&(t=Wi(this._bufs[0],this._lens[0]));try{let e=q.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;ks(tr)}}}he.prototype.destroy=function(){this.destroyed||sr(this)};function Ef(){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)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else q.write(this.fd,this._writingBuf,t)}function Af(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Wi(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=q.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else xf&&(this._writingBuf=Buffer.from(this._writingBuf)),q.write(this.fd,this._writingBuf,t)}function sr(t){if(t.fd===-1){t.once("ready",sr.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],gf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{q.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?q.close(t.fd,r):r()}function r(s){if(s){t.emit("error",s);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}he.SonicBoom=he;he.default=he;zi.exports=he});var $s=I((ew,Qi)=>{"use strict";var me={exit:[],beforeExit:[]},Gi={exit:If,beforeExit:Pf},it;function Of(){it===void 0&&(it=new FinalizationRegistry(Mf))}function Rf(t){me[t].length>0||process.on(t,Gi[t])}function Ji(t){me[t].length>0||(process.removeListener(t,Gi[t]),me.exit.length===0&&me.beforeExit.length===0&&(it=void 0))}function If(){Yi("exit")}function Pf(){Yi("beforeExit")}function Yi(t){for(let e of me[t]){let r=e.deref(),s=e.fn;r!==void 0&&s(r,t)}me[t]=[]}function Mf(t){for(let e of["exit","beforeExit"]){let r=me[e].indexOf(t);me[e].splice(r,r+1),Ji(e)}}function Xi(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Rf(t);let s=new WeakRef(e);s.fn=r,Of(),it.register(e,s),me[t].push(s)}function jf(t,e){Xi("exit",t,e)}function Lf(t,e){Xi("beforeExit",t,e)}function Df(t){if(it!==void 0){it.unregister(t);for(let e of["exit","beforeExit"])me[e]=me[e].filter(r=>{let s=r.deref();return s&&s!==t}),Ji(e)}}Qi.exports={register:jf,registerBeforeExit:Lf,unregister:Df}});var Zi=I((tw,Ff)=>{Ff.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 to=I((rw,eo)=>{"use strict";function Nf(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(t,e);if(a===r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(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 Uf(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(t,e)!==r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(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"){n(null,"ok");return}o()}):setImmediate(o)};o()}eo.exports={wait:Nf,waitDiff:Uf}});var so=I((sw,ro)=>{"use strict";ro.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var go=I((nw,mo)=>{"use strict";var{version:qf}=Zi(),{EventEmitter:Bf}=require("events"),{Worker:Hf}=require("worker_threads"),{join:Wf}=require("path"),{pathToFileURL:Vf}=require("url"),{wait:zf}=to(),{WRITE_INDEX:_e,READ_INDEX:Be,SEQ_INDEX:Ts}=so(),Kf=require("buffer"),Gf=require("assert"),S=Symbol("kImpl"),Jf=Kf.constants.MAX_STRING_LENGTH;function no(){}function Os(t,e){Atomics.add(t[S].state,Ts,1),e(),Atomics.add(t[S].state,Ts,1),Atomics.notify(t[S].state,Ts)}function io(t){Os(t,()=>{Atomics.store(t[S].state,Be,0),Atomics.store(t[S].state,_e,0)})}var Tt=class{constructor(e){this._value=e}deref(){return this._value}},nr=class{register(){}unregister(){}},Yf=process.env.NODE_V8_COVERAGE?nr:global.FinalizationRegistry||nr,Xf=process.env.NODE_V8_COVERAGE?Tt:global.WeakRef||Tt,oo=new Yf(t=>{t.exited||t.terminate()});function Qf(t,e){let{filename:r,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Wf(__dirname,"lib","worker.js"),o=new Hf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Vf(r).href,dataBuf:t[S].dataBuf,stateBuf:t[S].stateBuf,workerData:{$context:{threadStreamVersion:qf},...s}}});return o.stream=new Tt(t),o.on("message",Zf),o.on("exit",co),oo.register(t,o),o}function ao(t){Gf(!t[S].sync),t[S].needDrain&&(t[S].needDrain=!1,t.emit("drain"))}function lo(t){for(;;){let e=Atomics.load(t[S].state,_e),r=t[S].data.length-e;if(r>0){if(t[S].bufLen===0){t[S].flushing=!1,t[S].ending?Rs(t):t[S].needDrain&&process.nextTick(ao,t);return}po(t,r,no);continue}if(r===0){if(e===0&&t[S].bufLen===0)return;ir(t,()=>{t.destroyed||(io(t),lo(t))});return}ae(t,new Error("overwritten"));return}}function Zf(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 Xf(e),ir(e,()=>{e[S].ready=!0,e.emit("ready")});break;case"ERROR":ae(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){ae(e,new Error("this should not happen: "+t.code));break}let r=e[S].flushCallbacks.get(t.id);r&&(e[S].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ae(e,new Error("this should not happen: "+t.code))}}function co(t){let e=this.stream.deref();e!==void 0&&(oo.unregister(e),e.worker.exited=!0,e.worker.off("exit",co),ae(e,t!==0?new Error("the worker thread exited"):null))}var Es=class extends Bf{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[S]={},this[S].stateBuf=new SharedArrayBuffer(128),this[S].state=new Int32Array(this[S].stateBuf),this[S].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[S].data=Buffer.from(this[S].dataBuf),this[S].sync=e.sync||!1,this[S].ending=!1,this[S].ended=!1,this[S].needDrain=!1,this[S].destroyed=!1,this[S].flushing=!1,this[S].ready=!1,this[S].finished=!1,this[S].errored=null,this[S].closed=!1,this[S].buf=[],this[S].bufHead=0,this[S].bufLen=0,this[S].flushCallbacks=new Map,this[S].nextFlushId=0,this.worker=Qf(this,e),this.on("message",(r,s)=>{this.worker.postMessage(r,s)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[S].destroyed)return As(this,new Error("the worker has exited")),!1;if(this[S].ending)return As(this,new Error("the worker is ending")),!1;if(this[S].flushing&&this[S].bufLen+r.length>=Jf)try{Cs(this),this[S].flushing=!0}catch(s){return ae(this,s),!1}if(this[S].buf.push(r),this[S].bufLen+=r.length,this[S].sync)try{return Cs(this),!0}catch(s){return ae(this,s),!1}return this[S].flushing||(this[S].flushing=!0,setImmediate(lo,this)),this[S].needDrain=this[S].data.length-this[S].bufLen-Atomics.load(this[S].state,_e)<=0,!this[S].needDrain}end(){this[S].destroyed||(this[S].ending=!0,Rs(this))}flush(e){e=typeof e=="function"?e:no,uo(this,r=>{if(r){process.nextTick(e,r);return}fo(this,e)})}flushSync(){this[S].destroyed||(Cs(this),ho(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[S].ready}get destroyed(){return this[S].destroyed}get closed(){return this[S].closed}get writable(){return!this[S].destroyed&&!this[S].ending}get writableEnded(){return this[S].ending}get writableFinished(){return this[S].finished}get writableNeedDrain(){return this[S].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[S].errored}};function uo(t,e){if(t[S].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[S].sync&&(t[S].flushing||t[S].bufLen>0)){setImmediate(uo,t,e);return}ir(t,e)}function ir(t,e){let r=Atomics.load(t[S].state,_e);zf(t[S].state,Be,r,1/0,(s,n)=>{if(s){ae(t,s),e(s);return}if(n!=="ok"){ir(t,e);return}e()})}function fo(t,e){if(t[S].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[S].ready){let s=()=>{i(),fo(t,e)},n=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",s),t.off("close",n)};t.once("ready",s),t.once("close",n);return}let r=++t[S].nextFlushId;t[S].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(s){t[S].flushCallbacks.delete(r),ae(t,s),process.nextTick(e,s)}}function ed(t,e){let r=t[S].flushCallbacks;if(r.size===0)return;let s=e||new Error("the worker has exited");for(let n of r.values())process.nextTick(n,s);r.clear()}function As(t,e){setImmediate(()=>{t.emit("error",e)})}function ae(t,e){t[S].destroyed||(t[S].destroyed=!0,ed(t,e),e&&(t[S].errored=e,As(t,e)),t.worker.exited?setImmediate(()=>{t[S].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[S].closed=!0,t.emit("close")}))}function po(t,e,r){let n=Atomics.load(t[S].state,_e),i=e;for(;i>0&&t[S].bufLen!==0;){let o=t[S].bufHead,a=t[S].buf[o];if(a.length<=i){a.copy(t[S].data,n),n+=a.length,i-=a.length,t[S].bufLen-=a.length,t[S].bufHead=o+1,t[S].bufHead===t[S].buf.length?(t[S].buf.length=0,t[S].bufHead=0):t[S].bufHead>=1024&&t[S].bufHead*2>=t[S].buf.length&&(t[S].buf.splice(0,t[S].bufHead),t[S].bufHead=0);continue}a.copy(t[S].data,n,0,i),t[S].buf[o]=a.subarray(i),t[S].bufLen-=i,n+=i,i=0}return Os(t,()=>{Atomics.store(t[S].state,_e,n)}),r(),!0}function Rs(t){if(!(t[S].ended||!t[S].ending||t[S].flushing)){t[S].ended=!0;try{t.flushSync();let e=Atomics.load(t[S].state,Be);Os(t,()=>{Atomics.store(t[S].state,_e,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[S].state,Be,e,1e3),e=Atomics.load(t[S].state,Be),e===-2){ae(t,new Error("end() failed"));return}if(++r===10){ae(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[S].finished=!0,t.emit("finish")})}catch(e){ae(t,e)}}}function Cs(t){let e=()=>{t[S].ending?Rs(t):t[S].needDrain&&process.nextTick(ao,t)};for(t[S].flushing=!1;t[S].bufLen!==0;){let r=Atomics.load(t[S].state,_e),s=t[S].data.length-r;if(s===0){ho(t),io(t);continue}else if(s<0)throw new Error("overwritten");po(t,s,e)}}function ho(t){if(t[S].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[S].state,_e),r=0;for(;;){let s=Atomics.load(t[S].state,Be);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(t[S].state,Be,s,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}mo.exports=Es});var Ms=I((iw,bo)=>{"use strict";var{createRequire:td}=require("module"),{existsSync:rd}=require("node:fs"),sd=ys(),{join:Is,isAbsolute:wo,sep:nd}=require("node:path"),{fileURLToPath:id}=require("node:url"),od=vs(),Ps=$s(),ad=go();function ld(t){Ps.register(t,pd),Ps.registerBeforeExit(t,hd),t.on("close",function(){Ps.unregister(t)})}function cd(){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 ud(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],s=!1;for(let n=0;n<e.length;n++){let i=e[n];if(i==="--require"||i==="-r"||i==="--import"){let o=e[n+1];if(o&&yo(o)){s=!0,n++;continue}r.push(i),o&&(r.push(o),n++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(yo(o)){s=!0;continue}}r.push(i)}return s?r.join(" "):t}function yo(t){let e=fd(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=id(r)}catch{return!1}return wo(r)&&!rd(r)}function fd(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function dd(t,e,r,s,n){if(!r.execArgv&&cd()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=ud(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:n};let i=new ad({filename:t,workerData:e,workerOpts:r,sync:s});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&&ld(i)}function a(){i.closed||(i.flushSync(),od(100),i.end())}return i}function pd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function hd(t){t.flushSync()}function md(t){let{pipeline:e,targets:r,levels:s,dedupe:n,worker:i={},caller:o=sd(),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"]||Is(__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(g=>({...g,level:u.level,target:p(g.target)})))):e&&(d=f["pino-worker"]||Is(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),s&&(l.levels=s),n&&(l.dedupe=n),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return dd(p(d),l,i,a,h);function p(u){if(u=f[u]||u,wo(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return Is(__dirname,"..","file.js");let g;for(let m of c)try{let x=m==="node:repl"?process.cwd()+nd:m;g=td(x).resolve(u);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${u}"`);return g}}bo.exports=md});var lr=I((ow,Io)=>{"use strict";var gd=require("node:diagnostics_channel"),xo=Ni(),{mapHttpRequest:yd,mapHttpResponse:wd}=gs(),Ls=Ki(),So=$s(),{lsCacheSym:bd,chindingsSym:To,writeSym:vo,serializersSym:Co,formatOptsSym:_o,endSym:xd,stringifiersSym:Eo,stringifySym:Ao,stringifySafeSym:Ds,wildcardFirstSym:Oo,nestedKeySym:Sd,formattersSym:Ro,messageKeySym:vd,errorKeySym:_d,nestedKeyStrSym:kd,msgPrefixSym:or}=nt(),{isMainThread:$d}=require("worker_threads"),Td=Ms(),[Cd]=process.versions.node.split(".").map(t=>Number(t)),ko=gd.tracingChannel("pino_asJson"),js=Cd>=25?t=>JSON.stringify(t):Ad;function ot(){}function Ed(t,e){if(!e)return r;return function(...n){e.call(this,n,r,t)};function r(s,...n){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=yd(s):typeof s.setHeader=="function"&&(s=wd(s)));let o;i===null&&n.length===0?o=[null]:(i=n.shift(),o=n),typeof this[or]=="string"&&i!==void 0&&i!==null&&(i=this[or]+i),this[vo](s,xo(i,o,this[_o]),t)}else{let i=s===void 0?n.shift():s;typeof this[or]=="string"&&i!==void 0&&i!==null&&(i=this[or]+i),this[vo](null,xo(i,n,this[_o]),t)}}}function Ad(t){let e="",r=0,s=!1,n=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&n>=32;o++)n=t.charCodeAt(o),(n===34||n===92)&&(e+=t.slice(r,o)+"\\",r=o,s=!0);return s?e+=t.slice(r):e=t,n<32?JSON.stringify(t):'"'+e+'"'}function Od(t,e,r,s){if(ko.hasSubscribers===!1)return $o.call(this,t,e,r,s);let n={instance:this,arguments};return ko.traceSync($o,n,this,t,e,r,s)}function $o(t,e,r,s){let n=this[Ao],i=this[Ds],o=this[Eo],a=this[xd],l=this[To],c=this[Co],f=this[Ro],d=this[vd],h=this[_d],p=this[bd][r]+s;p=p+l;let u;f.log&&(t=f.log(t));let g=o[Oo],m="";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 w=o[b]||g;switch(typeof u){case"undefined":case"function":continue;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":w&&(u=w(u));break;case"string":u=(w||js)(u);break;default:u=(w||n)(u,i)}if(u===void 0)continue;let v=js(b);m+=","+v+":"+u}let x="";if(e!==void 0){u=c[d]?c[d](e):e;let b=o[d]||g;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||js)(u),x=',"'+d+'":'+u;break;default:u=(b||n)(u,i),x=',"'+d+'":'+u}}return this[Sd]&&m?p+this[kd]+m.slice(1)+"}"+x+a:p+m+x+a}function Rd(t,e){let r,s=t[To],n=t[Ao],i=t[Ds],o=t[Eo],a=o[Oo],l=t[Co],c=t[Ro].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||n)(r,i),r===void 0)continue;s+=',"'+f+'":'+r}return s}function Id(t){return t.write!==t.constructor.prototype.write}function ar(t){let e=new Ls(t);return e.on("error",r),!t.sync&&$d&&(So.register(e,Pd),e.on("close",function(){So.unregister(e)})),e;function r(s){if(s.code==="EPIPE"){e.write=ot,e.end=ot,e.flushSync=ot,e.destroy=ot;return}e.removeListener("error",r),e.emit("error",s)}}function Pd(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Md(t){return function(r,s,n={},i){if(typeof n=="string")i=ar({dest:n}),n={};else if(typeof i=="string"){if(n&&n.transport)throw Error("only one of option.transport or stream can be specified");i=ar({dest:i})}else if(n instanceof Ls||n.writable||n._writableState)i=n,n={};else if(n.transport){if(n.transport instanceof Ls||n.transport.writable||n.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(n.transport.targets&&n.transport.targets.length&&n.formatters&&typeof n.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;n.customLevels&&(l=n.useOnlyCustomLevels?n.customLevels:Object.assign({},n.levels,n.customLevels)),i=Td({caller:s,...n.transport,levels:l})}if(n=Object.assign({},t,n),n.serializers=Object.assign({},t.serializers,n.serializers),n.formatters=Object.assign({},t.formatters,n.formatters),n.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}=n;return o===!1&&(n.level="silent"),a||(n.onChild=ot),i||(Id(process.stdout)?i=process.stdout:i=ar({fd:process.stdout.fd||1})),{opts:n,stream:i}}}function jd(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Ds])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Ld(t,e,r){return{level:t,bindings:e,log:r}}function Dd(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Io.exports={noop:ot,buildSafeSonicBoom:ar,asChindings:Rd,asJson:Od,genLog:Ed,createArgsNormalizer:Md,stringify:jd,buildFormatters:Ld,normalizeDestFileDescriptor:Dd}});var cr=I((aw,Po)=>{var Fd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Nd={ASC:"ASC",DESC:"DESC"};Po.exports={DEFAULT_LEVELS:Fd,SORTING_ORDER:Nd}});var Us=I((lw,Do)=>{"use strict";var{lsCacheSym:Ud,levelValSym:Fs,useOnlyCustomLevelsSym:qd,streamSym:Bd,formattersSym:Hd,hooksSym:Wd,levelCompSym:Mo}=nt(),{noop:Vd,genLog:He}=lr(),{DEFAULT_LEVELS:xe,SORTING_ORDER:jo}=cr(),Lo={fatal:t=>{let e=He(xe.fatal,t);return function(...r){let s=this[Bd];if(e.call(this,...r),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:t=>He(xe.error,t),warn:t=>He(xe.warn,t),info:t=>He(xe.info,t),debug:t=>He(xe.debug,t),trace:t=>He(xe.trace,t)},Ns=Object.keys(xe).reduce((t,e)=>(t[xe[e]]=e,t),{}),zd=Object.keys(Ns).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Kd(t){let e=t[Hd].level,{labels:r}=t.levels,s={};for(let n in r){let i=e(r[n],Number(n));s[n]=JSON.stringify(i).slice(0,-1)}return t[Ud]=s,t}function Gd(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 Jd(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 s=this[Fs],n=this[Fs]=r[t],i=this[qd],o=this[Mo],a=this[Wd].logMethod;for(let l in r){if(o(r[l],n)===!1){this[l]=Vd;continue}this[l]=Gd(l,i)?Lo[l](a):He(r[l],a)}this.emit("level-change",t,n,e[s],s,this)}function Yd(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Xd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Mo](r,this[Fs])}function Qd(t,e,r){return t===jo.DESC?e<=r:e>=r}function Zd(t){return typeof t=="string"?Qd.bind(null,t):t}function ep(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Ns,r),n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:xe,t);return{labels:s,values:n}}function tp(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Ns).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:xe,e);if(!(t in s))throw Error(`default level:${t} must be included in custom levels`)}function rp(t,e){let{labels:r,values:s}=t;for(let n in e){if(n in s)throw Error("levels cannot be overridden");if(e[n]in r)throw Error("pre-existing level values cannot be used for new levels")}}function sp(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(jo).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Do.exports={initialLsCache:zd,genLsCache:Kd,levelMethods:Lo,getLevel:Yd,setLevel:Jd,isLevelEnabled:Xd,mappings:ep,assertNoLevelCollisions:rp,assertDefaultLevelFound:tp,genLevelComparison:Zd,assertLevelComparison:sp}});var qs=I((cw,Fo)=>{"use strict";Fo.exports={version:"10.3.1"}});var zo=I((fw,Vo)=>{"use strict";var{EventEmitter:np}=require("node:events"),{lsCacheSym:ip,levelValSym:op,setLevelSym:Hs,getLevelSym:No,chindingsSym:fr,mixinSym:ap,asJsonSym:qo,writeSym:lp,mixinMergeStrategySym:cp,timeSym:up,timeSliceIndexSym:fp,streamSym:Bo,serializersSym:We,formattersSym:Ct,errorKeySym:dp,messageKeySym:pp,useOnlyCustomLevelsSym:hp,needsMetadataGsym:mp,redactFmtSym:gp,stringifySym:yp,formatOptsSym:wp,stringifiersSym:bp,msgPrefixSym:Ws,hooksSym:xp}=nt(),{getLevel:Sp,setLevel:vp,isLevelEnabled:_p,mappings:kp,initialLsCache:$p,genLsCache:Tp,assertNoLevelCollisions:Cp}=Us(),{asChindings:Vs,asJson:Ep,buildFormatters:Bs,stringify:Uo,noop:Ho}=lr(),{version:Ap}=qs(),Op=xs(),Rp=class{},Wo={constructor:Rp,child:Ip,bindings:Pp,setBindings:Mp,flush:Dp,isLevelEnabled:_p,version:Ap,get level(){return this[No]()},set level(t){this[Hs](t)},get levelVal(){return this[op]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[Ws]},get[Symbol.toStringTag](){return"Pino"},[ip]:$p,[lp]:Lp,[qo]:Ep,[No]:Sp,[Hs]:vp};Object.setPrototypeOf(Wo,np.prototype);Vo.exports=function(){return Object.create(Wo)};var ur=t=>t;function Ip(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[We],s=this[Ct],n=Object.create(this);if(e==null)return n[Ct].bindings!==ur&&(n[Ct]=Bs(s.level,ur,s.log)),n[fr]=Vs(n,t),this.onChild!==Ho&&this.onChild(n),n;if(e.hasOwnProperty("serializers")===!0){n[We]=Object.create(null);for(let c in r)n[We][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];n[We][c]=r[c]}for(let c in e.serializers)n[We][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];n[We][c]=e.serializers[c]}}else n[We]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;n[Ct]=Bs(a||s.level,l||ur,c||s.log)}else n[Ct]=Bs(s.level,ur,s.log);if(e.hasOwnProperty("customLevels")===!0&&(Cp(this.levels,e.customLevels),n.levels=kp(e.customLevels,n[hp]),Tp(n)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){n.redact=e.redact;let a=Op(n.redact,Uo),l={stringify:a[gp]};n[yp]=Uo,n[bp]=a,n[wp]=l}if(typeof e.msgPrefix=="string"&&(n[Ws]=(this[Ws]||"")+e.msgPrefix),n[fr]=Vs(n,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;n[Hs](a)}return this.onChild(n),n}function Pp(){let e=`{${this[fr].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Mp(t){let e=Vs(this,t);this[fr]=e}function jp(t,e){return Object.assign(e,t)}function Lp(t,e,r){let s=this[up](),n=this[ap],i=this[dp],o=this[pp],a=this[cp]||jp,l,c=this[xp].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)),n&&(l=a(l,n(l,r,this)));let f=this[qo](l,e,r,s),d=this[Bo];d[mp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=s.slice(this[fp]),d.lastLogger=this),d.write(c?c(f):f)}function Dp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Bo];typeof e.flush=="function"?e.flush(t||Ho):t&&t()}});var Yo=I((Js,Jo)=>{"use strict";var{hasOwnProperty:Et}=Object.prototype,ze=Gs();ze.configure=Gs;ze.stringify=ze;ze.default=ze;Js.stringify=ze;Js.configure=Gs;Jo.exports=ze;var Fp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ie(t){return t.length<5e3&&!Fp.test(t)?`"${t}"`:JSON.stringify(t)}function zs(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let s=t[r],n=r;for(;n!==0&&t[n-1]>s;)t[n]=t[n-1],n--;t[n]=s}return t}var Np=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Ks(t){return Np.call(t)!==void 0&&t.length!==0}function Ko(t,e,r){t.length<r&&(r=t.length);let s=e===","?"":" ",n=`"0":${s}${t[0]}`;for(let i=1;i<r;i++)n+=`${e}"${i}":${s}${t[i]}`;return n}function Up(t){if(Et.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 qp(t){let e;if(Et.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 Bp(t,e){let r;if(Et.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 Go(t,e){let r;if(Et.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 Ve(t){return t===1?"1 item":`${t} items`}function Hp(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Wp(t){if(Et.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 s=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(s+=` (${r.toString()})`),new Error(s)}}}function Gs(t){t={...t};let e=Wp(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Up(t),s=Bp(t,"bigint"),n=qp(t),i=typeof n=="function"?n:void 0,o=Go(t,"maximumDepth"),a=Go(t,"maximumBreadth");function l(p,u,g,m,x,b){let w=u[p];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(p)),w=m.call(u,p,w),typeof w){case"string":return Ie(w);case"object":{if(w===null)return"null";if(g.indexOf(w)!==-1)return r;let v="",_=",",C=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(w),x!==""&&(b+=x,v+=`
|
|
26
|
+
${b}`,_=`,
|
|
27
|
+
${b}`);let D=Math.min(w.length,a),W=0;for(;W<D-1;W++){let ee=l(String(W),w,g,m,x,b);v+=ee!==void 0?ee:"null",v+=_}let J=l(String(W),w,g,m,x,b);if(v+=J!==void 0?J:"null",w.length-1>a){let ee=w.length-a-1;v+=`${_}"... ${Ve(ee)} not stringified"`}return x!==""&&(v+=`
|
|
28
|
+
${C}`),g.pop(),`[${v}]`}let E=Object.keys(w),A=E.length;if(A===0)return"{}";if(o<g.length+1)return'"[Object]"';let T="",P="";x!==""&&(b+=x,_=`,
|
|
29
|
+
${b}`,T=" ");let N=Math.min(A,a);n&&!Ks(w)&&(E=zs(E,i)),g.push(w);for(let D=0;D<N;D++){let W=E[D],J=l(W,w,g,m,x,b);J!==void 0&&(v+=`${P}${Ie(W)}:${T}${J}`,P=_)}if(A>a){let D=A-a;v+=`${P}"...":${T}"${Ve(D)} not stringified"`,P=_}return x!==""&&P.length>1&&(v=`
|
|
30
|
+
${b}${v}
|
|
31
|
+
${C}`),g.pop(),`{${v}}`}case"number":return isFinite(w)?String(w):e?e(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(w);default:return e?e(w):void 0}}function c(p,u,g,m,x,b){switch(typeof u=="object"&&u!==null&&typeof u.toJSON=="function"&&(u=u.toJSON(p)),typeof u){case"string":return Ie(u);case"object":{if(u===null)return"null";if(g.indexOf(u)!==-1)return r;let w=b,v="",_=",";if(Array.isArray(u)){if(u.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(u),x!==""&&(b+=x,v+=`
|
|
32
|
+
${b}`,_=`,
|
|
33
|
+
${b}`);let A=Math.min(u.length,a),T=0;for(;T<A-1;T++){let N=c(String(T),u[T],g,m,x,b);v+=N!==void 0?N:"null",v+=_}let P=c(String(T),u[T],g,m,x,b);if(v+=P!==void 0?P:"null",u.length-1>a){let N=u.length-a-1;v+=`${_}"... ${Ve(N)} not stringified"`}return x!==""&&(v+=`
|
|
34
|
+
${w}`),g.pop(),`[${v}]`}g.push(u);let C="";x!==""&&(b+=x,_=`,
|
|
35
|
+
${b}`,C=" ");let E="";for(let A of m){let T=c(A,u[A],g,m,x,b);T!==void 0&&(v+=`${E}${Ie(A)}:${C}${T}`,E=_)}return x!==""&&E.length>1&&(v=`
|
|
36
|
+
${b}${v}
|
|
37
|
+
${w}`),g.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(s)return String(u);default:return e?e(u):void 0}}function f(p,u,g,m,x){switch(typeof u){case"string":return Ie(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,g,m,x);if(u===null)return"null"}if(g.indexOf(u)!==-1)return r;let b=x;if(Array.isArray(u)){if(u.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(u),x+=m;let T=`
|
|
38
|
+
${x}`,P=`,
|
|
39
|
+
${x}`,N=Math.min(u.length,a),D=0;for(;D<N-1;D++){let J=f(String(D),u[D],g,m,x);T+=J!==void 0?J:"null",T+=P}let W=f(String(D),u[D],g,m,x);if(T+=W!==void 0?W:"null",u.length-1>a){let J=u.length-a-1;T+=`${P}"... ${Ve(J)} not stringified"`}return T+=`
|
|
40
|
+
${b}`,g.pop(),`[${T}]`}let w=Object.keys(u),v=w.length;if(v===0)return"{}";if(o<g.length+1)return'"[Object]"';x+=m;let _=`,
|
|
41
|
+
${x}`,C="",E="",A=Math.min(v,a);Ks(u)&&(C+=Ko(u,_,a),w=w.slice(u.length),A-=u.length,E=_),n&&(w=zs(w,i)),g.push(u);for(let T=0;T<A;T++){let P=w[T],N=f(P,u[P],g,m,x);N!==void 0&&(C+=`${E}${Ie(P)}: ${N}`,E=_)}if(v>a){let T=v-a;C+=`${E}"...": "${Ve(T)} not stringified"`,E=_}return E!==""&&(C=`
|
|
42
|
+
${x}${C}
|
|
43
|
+
${b}`),g.pop(),`{${C}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(u);default:return e?e(u):void 0}}function d(p,u,g){switch(typeof u){case"string":return Ie(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,g);if(u===null)return"null"}if(g.indexOf(u)!==-1)return r;let m="",x=u.length!==void 0;if(x&&Array.isArray(u)){if(u.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(u);let C=Math.min(u.length,a),E=0;for(;E<C-1;E++){let T=d(String(E),u[E],g);m+=T!==void 0?T:"null",m+=","}let A=d(String(E),u[E],g);if(m+=A!==void 0?A:"null",u.length-1>a){let T=u.length-a-1;m+=`,"... ${Ve(T)} not stringified"`}return g.pop(),`[${m}]`}let b=Object.keys(u),w=b.length;if(w===0)return"{}";if(o<g.length+1)return'"[Object]"';let v="",_=Math.min(w,a);x&&Ks(u)&&(m+=Ko(u,",",a),b=b.slice(u.length),_-=u.length,v=","),n&&(b=zs(b,i)),g.push(u);for(let C=0;C<_;C++){let E=b[C],A=d(E,u[E],g);A!==void 0&&(m+=`${v}${Ie(E)}:${A}`,v=",")}if(w>a){let C=w-a;m+=`${v}"...":"${Ve(C)} not stringified"`}return g.pop(),`{${m}}`}case"number":return isFinite(u)?String(u):e?e(u):"null";case"boolean":return u===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(u);default:return e?e(u):void 0}}function h(p,u,g){if(arguments.length>1){let m="";if(typeof g=="number"?m=" ".repeat(Math.min(g,10)):typeof g=="string"&&(m=g.slice(0,10)),u!=null){if(typeof u=="function")return l("",{"":p},[],u,m,"");if(Array.isArray(u))return c("",p,[],Hp(u),m,"")}if(m.length!==0)return f("",p,[],m,"")}return d("",p,[])}return h}});var ea=I((dw,Zo)=>{"use strict";var Ys=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Qo}=cr(),Vp=Qo.info;function zp(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Qo);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let s={write:n,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:f,[Ys]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,s):a.call(s,t),t=null,s;function n(d){let h,p=this.lastLevel,{streams:u}=this,g=0,m;for(let x=Kp(u.length,e.dedupe);Jp(x,u.length,e.dedupe);x=Gp(x,e.dedupe))if(h=u[x],h.level<=p){if(g!==0&&g!==h.level)break;if(m=h.stream,m[Ys]){let{lastTime:b,lastMsg:w,lastObj:v,lastLogger:_}=this;m.lastLevel=p,m.lastTime=b,m.lastMsg=w,m.lastObj=v,m.lastLogger=_}m.write(d),e.dedupe&&(g=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 s;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:g}=this,m;typeof d.levelVal=="number"?m=d.levelVal:typeof d.level=="string"?m=g[d.level]:typeof d.level=="number"?m=d.level:m=Vp;let x={stream:p,level:m,levelVal:void 0,id:++s.lastId};return u.unshift(x),u.sort(Xo),this.minLevel=u[0].level,s}function l(d){let{streams:h}=this,p=h.findIndex(u=>u.id===d);return p>=0&&(h.splice(p,1),h.sort(Xo),this.minLevel=h.length>0?h[0].level:-1),s}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:n,add:a,remove:l,minLevel:d,streams:h,clone:f,emit:i,flushSync:o,[Ys]:!0}}}function Xo(t,e){return t.level-e.level}function Kp(t,e){return e?t-1:0}function Gp(t,e){return e?t-1:t+1}function Jp(t,e,r){return r?t>=0:t<e}Zo.exports=zp});var ha=I((pw,le)=>{"use strict";var Yp=require("node:os"),la=gs(),Xp=ys(),Qp=xs(),ca=Di(),Zp=zo(),ua=nt(),{configure:eh}=Yo(),{assertDefaultLevelFound:th,mappings:fa,genLsCache:rh,genLevelComparison:sh,assertLevelComparison:nh}=Us(),{DEFAULT_LEVELS:da,SORTING_ORDER:ih}=cr(),{createArgsNormalizer:oh,asChindings:ah,buildSafeSonicBoom:ta,buildFormatters:lh,stringify:Xs,normalizeDestFileDescriptor:ra,noop:ch}=lr(),{version:uh}=qs(),{chindingsSym:sa,redactFmtSym:fh,serializersSym:na,timeSym:dh,timeSliceIndexSym:ph,streamSym:hh,stringifySym:ia,stringifySafeSym:Qs,stringifiersSym:oa,setLevelSym:mh,endSym:gh,formatOptsSym:yh,messageKeySym:wh,errorKeySym:bh,nestedKeySym:xh,mixinSym:Sh,levelCompSym:vh,useOnlyCustomLevelsSym:_h,formattersSym:aa,hooksSym:kh,nestedKeyStrSym:$h,mixinMergeStrategySym:Th,msgPrefixSym:Ch}=ua,{epochTime:pa,nullTime:Eh}=ca,{pid:Ah}=process,Oh=Yp.hostname(),Rh=la.err,Ih={level:"info",levelComparison:ih.ASC,levels:da,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Ah,hostname:Oh},serializers:Object.assign(Object.create(null),{err:Rh}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:pa,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Ph=oh(Ih),Mh=Object.assign(Object.create(null),la);function Zs(...t){let e={},{opts:r,stream:s}=Ph(e,Xp(),...t);r.level&&typeof r.level=="string"&&da[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:n,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:f,base:d,name:h,level:p,customLevels:u,levelComparison:g,mixin:m,mixinMergeStrategy:x,useOnlyCustomLevels:b,formatters:w,hooks:v,depthLimit:_,edgeLimit:C,onChild:E,msgPrefix:A}=r,T=eh({maximumDepth:_,maximumBreadth:C}),P=lh(w.level,w.bindings,w.log),N=Xs.bind({[Qs]:T}),D=n?Qp(n,N):{},W=n?{stringify:D[fh]}:{stringify:N},J="}"+(i?`\r
|
|
44
44
|
`:`
|
|
45
|
-
`),ee=
|
|
46
|
-
`);o=c.pop()||"";for(let
|
|
47
|
-
`);a=
|
|
48
|
-
`));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var
|
|
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 r=0;r<t.hunks.length;r++){var
|
|
45
|
+
`),ee=ah.bind(null,{[sa]:"",[na]:o,[oa]:D,[ia]:Xs,[Qs]:T,[aa]:P}),ne="";d!==null&&(h===void 0?ne=ee(d):ne=ee(Object.assign({},d,{name:h})));let j=a instanceof Function?a:a?pa:Eh,F=j().indexOf(":")+1;if(b&&!u)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(m&&typeof m!="function")throw Error(`Unknown mixin type "${typeof m}" - expected "function"`);if(A&&typeof A!="string")throw Error(`Unknown msgPrefix type "${typeof A}" - expected "string"`);th(p,u,b);let Vt=fa(u,b);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Vt,messageKey:l,errorKey:c}}),nh(g);let Un=sh(g);return Object.assign(e,{levels:Vt,[vh]:Un,[_h]:b,[hh]:s,[dh]:j,[ph]:F,[ia]:Xs,[Qs]:T,[oa]:D,[gh]:J,[yh]:W,[wh]:l,[bh]:c,[xh]:f,[$h]:f?`,${JSON.stringify(f)}:{`:"",[na]:o,[Sh]:m,[Th]:x,[sa]:ne,[aa]:P,[kh]:v,silent:ch,onChild:E,[Ch]:A}),Object.setPrototypeOf(e,Zp()),rh(e),e[mh](p),e}le.exports=Zs;le.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=ra(t.dest||process.stdout.fd),ta(t)):ta({dest:ra(t),minLength:0});le.exports.transport=Ms();le.exports.multistream=ea();le.exports.levels=fa();le.exports.stdSerializers=Mh;le.exports.stdTimeFunctions=Object.assign({},ca);le.exports.symbols=ua;le.exports.version=uh;le.exports.default=Zs;le.exports.pino=Zs});var ei=k(Zn(),1),{program:_y,createCommand:ky,createArgument:$y,createOption:Ty,CommanderError:Cy,InvalidArgumentError:Ey,InvalidOptionArgumentError:Ay,Command:ti,Argument:Oy,Option:Ry,Help:Iy}=ei.default;var pe=k(require("fs")),qe=k(require("path")),ri=k(require("os"));var et={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0},vision:{enabled:!0,primaryModel:"moonshotai/kimi-k2.6",fallbackModel:"meta/llama-3.2-90b-vision-instruct",maxImageBytes:1048576}},oe={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var tt=qe.join(ri.homedir(),".hablas"),os=qe.join(tt,"config.json");function rt(t={}){let e={};if(pe.existsSync(os))try{e=JSON.parse(pe.readFileSync(os,"utf-8"))}catch{}let r={...et,...e,tools:{...et.tools,...e.tools||{},runCommand:{...et.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...et.workspace,...e.workspace||{}},vision:{...et.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(r.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(r.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(r.vision.enabled=!1),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=qe.resolve(t.project)),t.provider){let s=t.provider;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function st(t){pe.existsSync(tt)||pe.mkdirSync(tt,{recursive:!0}),pe.writeFileSync(os,JSON.stringify(t,null,2),"utf-8")}function si(){let t=[tt,qe.join(tt,"logs"),qe.join(tt,"backup")];for(let e of t)pe.existsSync(e)||pe.mkdirSync(e,{recursive:!0})}var en=k(ha()),tn=k(require("path")),ma=k(require("os")),dr=k(require("fs"));function rn(t){let e=tn.join(ma.homedir(),".hablas","logs");dr.existsSync(e)||dr.mkdirSync(e,{recursive:!0});let r=tn.join(e,`session-${Date.now()}.log`);return(0,en.default)({level:"info"},en.default.destination({dest:r,sync:!1}))}var pr=k(require("fs")),At=k(require("path"));function ga(){let t=[At.resolve(__dirname,"..","package.json"),At.resolve(__dirname,"..","..","package.json"),At.resolve(process.cwd(),"package.json"),At.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(pr.existsSync(e)){let r=JSON.parse(pr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var St=k(require("fs")),Br=k(require("path")),gc=k(require("os"));var hr=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(s=>s.name):[]}catch{return[]}}async chatWithTools(e,r,s){let n={model:this.model,messages:e,stream:!1};r.length>0&&(n.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let n=s.body?.getReader();if(!n)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await n.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 ya=12e4,jh=6e4,mr=3,wa=1e3,Lh=20;function ba(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(s=>s?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((s,n)=>({id:`call_${n}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Dh(t){return t.map(e=>({type:"function",function:e.function}))}function Fh(t){return t.filter(e=>e?.function?.name).map(e=>{let r={};try{r=JSON.parse(e.function?.arguments||"{}")}catch{r={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:r}}})}function xa(t){return new Promise(e=>setTimeout(e,t))}function Sa(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var Ot=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,s,n=0;for(;r&&n<Lh;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;s&&o.set("after",s),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(jh)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(f=>f.id||f.name||f).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let f=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...f),c.has_more&&f.length>0?(s=f[f.length-1],n++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(f=>f.name||f.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,s){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ba(e)};r.length>0&&(i.tools=Dh(r),i.tool_choice="auto");let o=null;for(let a=0;a<=mr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),ya),f={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let d=await fetch(n,f);if(clearTimeout(c),!d.ok){let g=await d.text().catch(()=>"");if(!Sa(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${g}`),a<mr){let m=wa*Math.pow(2,a);await xa(m);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?Fh(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"&&s?.aborted)throw d;if(Sa(d)&&(o=d,a<mr)){let h=wa*Math.pow(2,a);await xa(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=mr)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:ba(e),stream:!0}),signal:r||AbortSignal.timeout(ya)});if(!n.ok)throw new Error(`API error: ${n.status} ${n.statusText}`);let i=n.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 at(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:oe.apiUrl};return new Ot(e)}return t.provider==="custom"&&t.apiUrl?new Ot(t):new hr(t)}function Ke(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var B=k(require("fs/promises")),dn=k(require("fs")),Pe=k(require("path"));function ke(){}ke.prototype={diff:function(e,r){var s,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.callback;typeof n=="function"&&(i=n,n={}),this.options=n;var o=this;function a(v){return i?(setTimeout(function(){i(void 0,v)},0),!0):v}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,f=1,d=l+c;n.maxEditLength&&(d=Math.min(d,n.maxEditLength));var h=(s=n.timeout)!==null&&s!==void 0?s:1/0,p=Date.now()+h,u=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(u[0],r,e,0);if(u[0].oldPos+1>=c&&g+1>=l)return a([{value:this.join(r),count:r.length}]);var m=-1/0,x=1/0;function b(){for(var v=Math.max(m,-f);v<=Math.min(x,f);v+=2){var _=void 0,C=u[v-1],E=u[v+1];C&&(u[v-1]=void 0);var A=!1;if(E){var T=E.oldPos-v;A=E&&0<=T&&T<l}var P=C&&C.oldPos+1<c;if(!A&&!P){u[v]=void 0;continue}if(!P||A&&C.oldPos+1<E.oldPos?_=o.addToPath(E,!0,void 0,0):_=o.addToPath(C,void 0,!0,1),g=o.extractCommon(_,r,e,v),_.oldPos+1>=c&&g+1>=l)return a(Nh(o,_.lastComponent,r,e,o.useLongestToken));u[v]=_,_.oldPos+1>=c&&(x=Math.min(x,v-1)),g+1>=l&&(m=Math.max(m,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 w=b();if(w)return w}},addToPath:function(e,r,s,n){var i=e.lastComponent;return i&&i.added===r&&i.removed===s?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:s,previousComponent:i}}},extractCommon:function(e,r,s,n){for(var i=r.length,o=s.length,a=e.oldPos,l=a-n,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],s[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],s=0;s<e.length;s++)e[s]&&r.push(e[s]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Nh(t,e,r,s,n){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(s.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&&n){var h=r.slice(c,c+d.count);h=h.map(function(g,m){var x=s[f+m];return x.length>g.length?x:g}),d.value=t.join(h)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(f+=d.count)}}var u=i[l-1];return l>1&&typeof u.value=="string"&&(u.added||u.removed)&&t.equals("",u.value)&&(i[l-2].value+=u.value,i.pop()),i}var Ew=new ke;var va=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,_a=/\S/,ka=new ke;ka.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!_a.test(t)&&!_a.test(e)};ka.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&va.test(e[r])&&va.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var ln=new ke;ln.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
48
|
+
`));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var s=0;s<r.length;s++){var n=r[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=n:(this.options.ignoreWhitespace&&(n=n.trim()),e.push(n))}return e};function Uh(t,e,r){return ln.diff(t,e,r)}var qh=new ke;qh.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Bh=new ke;Bh.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function gr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?gr=function(e){return typeof e}:gr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gr(t)}function sn(t){return Hh(t)||Wh(t)||Vh(t)||zh()}function Hh(t){if(Array.isArray(t))return nn(t)}function Wh(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Vh(t,e){if(t){if(typeof t=="string")return nn(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return nn(t,e)}}function nn(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,s=new Array(e);r<e;r++)s[r]=t[r];return s}function zh(){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 Kh=Object.prototype.toString,Rt=new ke;Rt.useLongestToken=!0;Rt.tokenize=ln.tokenize;Rt.castInput=function(t){var e=this.options,r=e.undefinedReplacement,s=e.stringifyReplacer,n=s===void 0?function(i,o){return typeof o>"u"?r:o}:s;return typeof t=="string"?t:JSON.stringify(on(t,null,null,n),n," ")};Rt.equals=function(t,e){return ke.prototype.equals.call(Rt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function on(t,e,r,s,n){e=e||[],r=r||[],s&&(t=s(n,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(Kh.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),i=0;i<t.length;i+=1)o[i]=on(t[i],e,r,s,n);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),gr(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=on(t[l],e,r,s,l);e.pop(),r.pop()}else o=t;return o}var an=new ke;an.tokenize=function(t){return t.slice()};an.join=an.removeEmpty=function(t){return t};function Gh(t,e,r,s,n,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Uh(r,s,o);if(!a)return;a.push({value:"",lines:[]});function l(x){return x.map(function(b){return" "+b})}for(var c=[],f=0,d=0,h=[],p=1,u=1,g=function(b){var w=a[b],v=w.lines||w.value.replace(/\n$/,"").split(`
|
|
50
|
+
`);if(w.lines=v,w.added||w.removed){var _;if(!f){var C=a[b-1];f=p,d=u,C&&(h=o.context>0?l(C.lines.slice(-o.context)):[],f-=h.length,d-=h.length)}(_=h).push.apply(_,sn(v.map(function(J){return(w.added?"+":"-")+J}))),w.added?u+=v.length:p+=v.length}else{if(f)if(v.length<=o.context*2&&b<a.length-2){var E;(E=h).push.apply(E,sn(l(v)))}else{var A,T=Math.min(v.length,o.context);(A=h).push.apply(A,sn(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 N=/\n$/.test(r),D=/\n$/.test(s),W=v.length==0&&h.length>P.oldLines;!N&&W&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!W||!D)&&h.push("\")}c.push(P),f=0,d=0,h=[]}p+=v.length,u+=v.length}},m=0;m<a.length;m++)g(m);return{oldFileName:t,newFileName:e,oldHeader:n,newHeader:i,hunks:c}}function $a(t){if(Array.isArray(t))return t.map($a).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 r=0;r<t.hunks.length;r++){var s=t.hunks[r];s.oldLines===0&&(s.oldStart-=1),s.newLines===0&&(s.newStart-=1),e.push("@@ -"+s.oldStart+","+s.oldLines+" +"+s.newStart+","+s.newLines+" @@"),e.push.apply(e,s.lines)}return e.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`}function
|
|
54
|
-
`),
|
|
55
|
-
... [Partial read. Total lines: ${
|
|
56
|
-
${
|
|
57
|
-
`)}${A}`}}catch(
|
|
58
|
-
|
|
59
|
-
`)
|
|
60
|
-
`),T=[
|
|
61
|
-
`)
|
|
62
|
-
|
|
63
|
-
`)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`),
|
|
53
|
+
`}function Jh(t,e,r,s,n,i,o){return $a(Gh(t,e,r,s,n,i,o))}function Ta(t,e,r,s,n,i){return Jh(t,t,e,r,s,n,i)}function cn(t,e,r){return Ta(t,e,r,"original","modified")}var Se=k(require("fs/promises")),un=k(require("fs")),lt=k(require("path")),Ea=k(require("os")),It=lt.join(Ea.homedir(),".hablas","backup"),Ca=10;async function Ge(t){try{if(!un.existsSync(t))return;un.existsSync(It)||await Se.mkdir(It,{recursive:!0});let e=await Se.readFile(t,"utf-8"),r=lt.basename(t),s=Date.now(),n=`${r}.${s}.bak`,i=lt.join(It,n);await Se.writeFile(i,e,"utf-8");let a=(await Se.readdir(It)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Ca)for(let l of a.slice(Ca))await Se.unlink(lt.join(It,l))}catch{}}function Aa(t){let e=p=>Pe.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),m=(await B.readFile(u,"utf-8")).split(`
|
|
54
|
+
`),x=m.length,b=p.start_line?Math.max(1,p.start_line):1,w=p.end_line?Math.min(x,p.end_line):x,v=m.slice(b-1,w),_=String(w).length,C=v.map((T,P)=>`${String(b+P).padStart(_," ")} | ${T}`),E=`[${p.path} \u2014 lines ${b}-${w} of ${x}]`,A=w<x?`
|
|
55
|
+
... [Partial read. Total lines: ${x}.]`:"";return{success:!0,output:`${E}
|
|
56
|
+
${C.join(`
|
|
57
|
+
`)}${A}`}}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 dn.existsSync(u)&&await Ge(u),await B.mkdir(Pe.dirname(u),{recursive:!0}),await B.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),g=await B.readFile(u,"utf-8"),m=p.old_content,x=p.new_content,b=fn(g,m),w=m;if(b===0){let A=D=>D.replace(/\r\n/g,`
|
|
58
|
+
`).split(`
|
|
59
|
+
`).map(W=>W.trimEnd()).join(`
|
|
60
|
+
`),T=A(g),P=A(m),N=fn(T,P);N===1&&(w=P,b=N)}if(b===0)return{success:!1,output:"",error:`[edit_file]: old_content not found in file. Check for whitespace/newline differences. File preview: "${g.slice(0,200).replace(/\n/g,"\u21B5")}\u2026"`};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations. Provide more surrounding context to make it unique.`};await Ge(u);let C=(w!==m?(A=>A.replace(/\r\n/g,`
|
|
61
|
+
`).split(`
|
|
62
|
+
`).map(T=>T.trimEnd()).join(`
|
|
63
|
+
`))(g):g).replace(w,x);await B.writeFile(u,C,"utf-8");let E=cn(p.path,g,C);return{success:!0,output:`Edited: ${p.path}
|
|
64
|
+
${E}`}}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),g=await B.readFile(u,"utf-8"),m=g.split(`
|
|
65
|
+
`),x=m.length,b=p.start_line,w=p.end_line;if(b<1||b>x)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${x} lines)`};if(w<b||w>x)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${b}, total=${x})`};await Ge(u);let v=m.slice(0,b-1),_=m.slice(w),C=p.new_content.split(`
|
|
66
|
+
`),E=[...v,...C,..._].join(`
|
|
67
|
+
`);await B.writeFile(u,E,"utf-8");let A=cn(p.path,g,E),T=w-b+1,P=C.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${P})
|
|
68
|
+
${A}`}}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),g=await B.readFile(u,"utf-8"),m=p.search,x=p.replace,b=p.is_regex;await Ge(u);let w,v;if(b){let _=new RegExp(m,"g");v=(g.match(_)||[]).length,w=g.replace(_,x)}else v=fn(g,m),w=g.split(m).join(x);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await B.writeFile(u,w,"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 B.mkdir(Pe.dirname(u),{recursive:!0}),dn.existsSync(u)&&await Ge(u),await B.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 Ge(u),await B.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),g=e(p.to);return await B.mkdir(Pe.dirname(g),{recursive:!0}),await B.rename(u,g),{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 B.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||"."),g=p.depth||3;return{success:!0,output:await Oa(u,"",g,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),g=await B.stat(u);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Xh(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
|
|
69
|
+
`)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function fn(t,e){let r=0,s=0;for(;;){let n=t.indexOf(e,s);if(n===-1)break;r++,s=n+e.length}return r}var Yh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Oa(t,e,r,s){if(s>=r)return"";let i=(await B.readdir(t,{withFileTypes:!0})).filter(a=>!Yh.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}
|
|
70
|
+
`,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await Oa(Pe.join(t,l.name),h,r,s+1)}}return o}function Xh(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"),yr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let s=`bg_${this.nextId++}`,n=r?.timeout||this.config.defaultTimeout,i=(0,Ra.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:s,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+=`
|
|
71
|
+
Error: ${a.message}`}),n>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
|
|
72
|
+
Process timed out after ${n}ms`)},n),this.processes.set(s,o),s}readOutput(e,r){let s=this.processes.get(e);if(!s)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let n=r?.type||"both",i="";return(n==="stdout"||n==="both")&&(i+=s.stdout),(n==="stderr"||n==="both")&&(i&&(i+=`
|
|
73
|
+
`),i+=s.stderr),r?.lastLines&&(i=i.split(`
|
|
68
74
|
`).slice(-r.lastLines).join(`
|
|
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,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
`),
|
|
75
|
-
|
|
76
|
-
`);for(let
|
|
77
|
-
`);for(let o
|
|
78
|
-
`)
|
|
79
|
-
`);n.line
|
|
80
|
-
`)
|
|
75
|
+
`)),{success:!0,output:i,status:s.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,s]of this.processes){let n=Date.now()-s.startTime,i=this.formatUptime(n);e.push({id:r,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);return s<60?`${s}m ${r%60}s`:`${Math.floor(s/60)}h ${s%60}m`}};var Qh=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],pn=null;function wr(t){return pn||(pn=new yr({workingDir:t})),pn}function Pa(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let s=r.command,n=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Qh,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(n){let l=wr(t).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
|
|
76
|
+
PID: ${wr(t).getProcess(l)?.pid}
|
|
77
|
+
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Ia.exec)(s,{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=>{let u=(g,m)=>g.length>8e3?g.slice(0,8e3)+`
|
|
78
|
+
... [${m} truncated \u2014 ${g.length} chars total]`:g;l(h===0?{success:!0,output:u(f,"stdout")||"(no output)"}:{success:!1,output:u(f,"stdout"),error:u(d||`Exit code: ${h}`,"stderr")})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}function Ma(t){return{name:"bash_output",description:"Read output from a background shell process started with run_command(run_in_background=true).",safety:"safe",parameters:{process_id:{type:"string",description:"ID of the background process (e.g., bg_1)",required:!0},last_lines:{type:"number",description:"Number of last lines to return (default: all)",required:!1},type:{type:"string",description:"Output type: stdout, stderr, or both (default: both)",required:!1}},execute:async e=>{let r=e.process_id,s=e.last_lines,n=e.type||"both",o=wr(t).readOutput(r,{lastLines:s,type:n});return o.success?{success:!0,output:`[${r}] (${o.status})
|
|
79
|
+
${o.output}`}:{success:!1,output:"",error:o.error||"Failed to read output"}}}}function ja(t){return{name:"kill_shell",description:"Kill a running background shell process.",safety:"dangerous",parameters:{process_id:{type:"string",description:"ID of the background process to kill",required:!0}},execute:async e=>{let r=e.process_id;return wr(t).kill(r)?{success:!0,output:`Process ${r} killed successfully.`}:{success:!1,output:"",error:`Process ${r} not found or already stopped.`}}}}var br=k(require("fs/promises")),Me=k(require("path")),Zh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),em=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function La(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,s=Me.resolve(t,e.path||"."),n=[];if(await Da(s,r,n,t),n.length===0)return{success:!0,output:`No matches found for: "${r}"`};let i=n.slice(0,50).join(`
|
|
80
|
+
`),o=n.length>50?`
|
|
81
|
+
... and ${n.length-50} more matches`:"";return{success:!0,output:i+o}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function Da(t,e,r,s){let n=await br.readdir(t,{withFileTypes:!0});for(let i of n){if(Zh.has(i.name)||i.name.startsWith("."))continue;let o=Me.join(t,i.name);if(i.isDirectory())await Da(o,e,r,s);else if(em.has(Me.extname(i.name)))try{let l=(await br.readFile(o,"utf-8")).split(`
|
|
82
|
+
`),c=Me.relative(s,o);for(let f=0;f<l.length;f++)new RegExp(e,"i").test(l[f])&&r.push(`${c}:${f+1}: ${l[f].trim()}`)}catch{}}}var hn=require("child_process"),ce=k(require("fs")),je=k(require("path"));function tm(t){let e=[],r=je.join(t,"tsconfig.json");if(!ce.existsSync(r))return e;try{(0,hn.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let n=s,o=(n.stdout||n.message||"").split(`
|
|
83
|
+
`);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 rm(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>ce.existsSync(je.join(t,s))))return e;try{(0,hn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:je.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(`
|
|
84
|
+
`);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 sm(t,e,r){let s;try{s=ce.readFileSync(t,"utf-8")}catch{return}let n=je.relative(e,t),i=s.split(`
|
|
85
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:n,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:n,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:n,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:n,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function nm(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function s(n,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=ce.readdirSync(n)}catch{return}for(let l of a){if(o.includes(l))continue;let c=je.join(n,l),f;try{f=ce.statSync(c)}catch{continue}f.isDirectory()?s(c,i+1):r.some(d=>l.endsWith(d))&&sm(c,t,e)}}return s(t),e.slice(0,20)}function im(t){let e=[];e.push(...tm(t)),e.push(...rm(t)),e.push(...nm(t));let r={error:0,warning:1,info:2};return e.sort((s,n)=>r[s.severity]-r[n.severity]),e}function Fa(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,s=t.filter(i=>i.severity==="warning").length,n=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${s} warnings, ${n} 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(`
|
|
86
|
+
`)}function om(t,e){let r=[];for(let s of t)if(s.source==="pattern"&&s.message.includes("console.log")){let n=je.join(e,s.file);try{let o=ce.readFileSync(n,"utf-8").split(`
|
|
87
|
+
`);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],ce.writeFileSync(n,o.join(`
|
|
88
|
+
`),"utf-8"),r.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function Na(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,s=e.fix==="true"||e.fix===!0;try{let n=im(r);if(s&&n.length>0){let o=om(n,r).filter(l=>l.fixed).length;return{success:!0,output:`${Fa(n)}
|
|
81
89
|
|
|
82
|
-
Auto-fixed: ${o}/${
|
|
90
|
+
Auto-fixed: ${o}/${n.length} issues`}}return{success:!0,output:Fa(n)}}catch(n){return{success:!1,output:"",error:`Bug detection failed: ${n instanceof Error?n.message:String(n)}`}}}}}var Ua=2*1024*1024,qa=15e3,Ba=32e3,am="HablasBot/2.0 (+https://hablas.dev)";function lm(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
91
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
84
92
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
85
|
-
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n
|
|
86
|
-
${"#".repeat(parseInt(
|
|
87
|
-
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n
|
|
93
|
+
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,s,n)=>`
|
|
94
|
+
${"#".repeat(parseInt(s))} ${n.replace(/<[^>]+>/g,"").trim()}
|
|
95
|
+
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,s,n)=>{let i=n.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${s})`:s}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,s)=>"\n```\n"+s.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(r,s)=>String.fromCharCode(parseInt(s))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
88
96
|
|
|
89
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
97
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function cm(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function um(t,e){let r=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,n,i=new Set;for(;(n=s.exec(t))!==null;){let o=n[1].trim(),a=n[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function Ha(t){let e=new AbortController,r=setTimeout(()=>e.abort(),qa);try{let s=await fetch(t,{signal:e.signal,headers:{"User-Agent":am,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!s.ok)return{html:"",finalUrl:s.url||t,status:s.status};let n=s.headers.get("content-type")||"";if(!n.includes("text/")&&!n.includes("application/xhtml")&&!n.includes("application/json"))return{html:`[Binary content: ${n}]`,finalUrl:s.url||t,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||t,status:s.status};let o=[],a=0;for(;a<Ua;){let{done:f,value:d}=await i.read();if(f)break;o.push(d),a+=d.length}if(a>=Ua)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(f=>l.decode(f,{stream:!0})).join("")+l.decode(),finalUrl:s.url||t,status:s.status}}catch(s){clearTimeout(r);let n=s instanceof Error?s:new Error(String(s));throw n.name==="AbortError"?new Error(`Timeout after ${qa/1e3}s`):n}}function Wa(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:s,status:n}=await Ha(e);if(!r||n>=400)return{success:!1,output:"",error:`HTTP ${n} \u2014 could not fetch ${e}`};let i=cm(r),o=lm(r);return o.length>Ba&&(o=o.slice(0,Ba)+`
|
|
90
98
|
|
|
91
|
-
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${
|
|
92
|
-
`)}}catch(r){let
|
|
99
|
+
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
100
|
+
`)}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:n,status:i}=await Ha(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=um(s,n);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
|
|
93
101
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
94
102
|
|
|
95
|
-
${a}`}}catch(
|
|
96
|
-
`)}}catch(
|
|
103
|
+
${a}`}}catch(s){let n=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${n}`}}}}]}var fm=3600*1e3,ct=new Map;function dm(t){let e=ct.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>fm?(ct.delete(t.toLowerCase().trim()),null):e.results:null}function pm(t,e){if(ct.size>200){let r=ct.keys().next().value;r!==void 0&&ct.delete(r)}ct.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function hm(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let s=new URLSearchParams({q:t,count:String(Math.min(e,10))}),n=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return n.ok?((await n.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 mm(t,e){try{let r=new URLSearchParams({q:t}),s=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let n=await s.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(n))!==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(n))!==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 mn(t,e=5){let r=dm(t);if(r)return r.slice(0,e);let s=[{name:"brave",fn:()=>hm(t,e)},{name:"duckduckgo",fn:()=>mm(t,e)}];for(let n of s)try{let i=await n.fn();if(i&&i.length>0)return pm(t,i),i}catch{}return[]}function Va(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let s=await mn(e.trim(),r);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let n=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];n.push(`[${i+1}] ${o.title}`),n.push(` ${o.url}`),o.snippet&&n.push(` ${o.snippet}`),n.push("")}return{success:!0,output:n.join(`
|
|
104
|
+
`)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var $e=k(require("fs")),Ya=k(require("path")),za=50*1024*1024,Ka=4e4;function Ga(t){let e=t.toString("latin1"),r={},s=[],n=0,i=e.match(/\/Type\s*\/Page\b/g);n=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=Je(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Je(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Je(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=Je(c[1]));let f=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=f.exec(e))!==null;){let p=d[1],u=Ja(p);u.trim()&&s.push(u);try{let g=require("zlib"),m=Buffer.from(p,"latin1"),x=g.inflateSync(m).toString("latin1"),b=Ja(x);b.trim()&&!s.includes(b)&&s.push(b)}catch{}}return{text:s.join(`
|
|
97
105
|
`).replace(/\r\n/g,`
|
|
98
106
|
`).replace(/\n{3,}/g,`
|
|
99
107
|
|
|
100
|
-
`).trim(),pages:
|
|
101
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function
|
|
102
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function
|
|
108
|
+
`).trim(),pages:n,metadata:r}}function Ja(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,s;for(;(s=r.exec(t))!==null;)e.push(Je(s[1]));let n=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=n.exec(t))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(f=>Je(f.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(t))!==null;)e.push(Je(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
|
|
109
|
+
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Je(t){return t.replace(/\\n/g,`
|
|
110
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Xa(t){let e=r=>Ya.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let s=e(r.path);if(!$e.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let n=$e.statSync(s);if(n.size>za)return{success:!1,output:"",error:`File too large: ${(n.size/1024/1024).toFixed(1)}MB (max: ${za/1024/1024}MB)`};try{let i=$e.readFileSync(s),{text:o,pages:a,metadata:l}=Ga(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
|
|
103
111
|
|
|
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>
|
|
112
|
+
[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>Ka&&(c=c.slice(0,Ka)+`
|
|
105
113
|
|
|
106
|
-
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(
|
|
114
|
+
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(n.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
107
115
|
`)}
|
|
108
|
-
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let
|
|
109
|
-
`)}}catch(
|
|
110
|
-
Errors/Warnings:`:"Errors:"),i.push(
|
|
111
|
-
`),error:
|
|
116
|
+
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let s=e(r.path);if(!$e.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let n=$e.statSync(s),i=$e.readFileSync(s),{pages:o,metadata:a}=Ga(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(n.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: ${n.mtime.toISOString()}`].filter(Boolean).join(`
|
|
117
|
+
`)}}catch(n){return{success:!1,output:"",error:`Failed to read PDF metadata: ${n instanceof Error?n.message:String(n)}`}}}}]}var el=require("child_process"),xr=k(require("fs")),tl=k(require("os")),rl=k(require("path")),sl=1e4,Qa=16e3;function ut(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 Za={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>ut("tsx")?`tsx "${t}"`:ut("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=>ut("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>ut("python3")||ut("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>ut("bash")}};async function gm(t,e,r=sl){let s=Za[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Za).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.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 n=tl.tmpdir(),i=rl.join(n,`hablas_exec_${Date.now()}${s.extension}`);try{xr.writeFileSync(i,t,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let c=(0,el.exec)(o,{timeout:r,maxBuffer:5242880,cwd:n,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,Qa),stderr:d.slice(0,Qa/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{xr.unlinkSync(i)}catch{}}}function ym(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 nl(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||ym(e),s=Math.min(Math.max(1e3,t.timeout||sl),3e4),n=await gm(e,r,s),i=[];return i.push(`Language: ${n.language} | Exit: ${n.exitCode} | Duration: ${n.duration}ms`),i.push(""),n.stdout&&(i.push("Output:"),i.push(n.stdout)),n.stderr&&(i.push(n.stdout?`
|
|
118
|
+
Errors/Warnings:`:"Errors:"),i.push(n.stderr)),!n.stdout&&!n.stderr&&i.push("(no output)"),{success:n.success,output:i.join(`
|
|
119
|
+
`),error:n.success?void 0:n.stderr||`Exit code: ${n.exitCode}`}}}]}var kr=k(require("fs")),ge=k(require("path"));var wm=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org","live.staticflickr.com","flickr.com","images.rawpixel.com","rawpixel.com"],bm=[/images\.unsplash\.com/i,/images\.pexels\.com/i,/cdn\.pixabay\.com\/photo/i,/upload\.wikimedia\.org\/wikipedia\/commons/i,/live\.staticflickr\.com/i,/images\.rawpixel\.com/i];function gn(t){let e=String(t||"").toLowerCase().trim();return!e||e==="generic"?"generic":e==="hero"||e.includes("wallpaper")||e.includes("background")||e.includes("banner")?"hero":e==="product"||e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":e==="icon"||e.includes("icon")||e.includes("logo")?"icon":e==="avatar"||e.includes("avatar")||e.includes("profile")||e.includes("portrait")?"avatar":e==="banner"?"banner":"generic"}var xm=new Set(["image","images","photo","photos","picture","pictures","free","download","asset","assets","website","site","stock","hd","4k","8k","for","with","and","the","a","an","of","in","on","at","to","from","is","are","high","quality","beautiful","nice","new","best","top"]);function Sr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!xm.has(e))}function vr(t,e){let r=[...new Set(Sr(t))].slice(0,6);return r.length>0?r.join(" "):t.trim().slice(0,60)}function Pt(t){try{let e=new URL(t).hostname.toLowerCase();return wm.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function Sm(t){return bm.some(e=>e.test(t))}function _r(t,e,r,s,n=[]){let i=Pt(t),o=[],a=[],l=0;if(i&&(l+=20,o.push("trusted-host")),Sm(t)&&(l+=15,o.push("cdn-direct")),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=8,o.push("image-ext")),(/\/photos?\/[^/?#]+/i.test(t)||/\/images?\/[^/?#]+/i.test(t))&&(l+=6,o.push("photo-page")),n.length>0){let f=Sr([e,r,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),d=new Set(f),h=n.filter(p=>d.has(p));h.length>0&&(l+=h.length*10,o.push("query-match:"+h.slice(0,3).join(",")))}let c=[e,r,t].join(" ").toLowerCase();return(s==="hero"||s==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(c)&&(l+=5,o.push("kind-hero")),(s==="product"||s==="thumbnail")&&/product|closeup|detail|item|buy/i.test(c)&&(l+=5,o.push("kind-product")),(s==="icon"||s==="avatar")&&/icon|avatar|logo|portrait|profile/i.test(c)&&(l+=5,o.push("kind-icon")),/javascript|\.woff|\.eot|\.ttf|\.css/i.test(t)&&(l-=30,a.push("non-image-resource")),{score:l,positives:o,negatives:a,trusted:i}}function il(t,e){let r=vr(t,e),s=encodeURIComponent(r);return r?[{source:"unsplash",url:`https://unsplash.com/s/photos/${s}`},{source:"pexels",url:`https://www.pexels.com/search/${s}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${s}/`}]:[]}function ol(t,e){let r=vr(t,e);return[`${r} site:unsplash.com/photos`,`${r} site:pexels.com/photo`,`${r} site:pixabay.com/photos`,`${r} site:commons.wikimedia.org/wiki/File`]}function vm(t,e){try{let r=t.split(",")[0].trim().split(/\s+/)[0],s=new URL(r,e);return/^https?:$/i.test(s.protocol)?s.href:null}catch{return null}}function ft(t,e){let r=new Set,s=[];function n(i){let o=vm(i,e);o&&!r.has(o)&&(r.add(o),s.push(o))}for(let i of t.matchAll(/<meta[^>]+(?:property|name)=["'](?:og:image(?::secure_url)?|twitter:image(?::src)?)["'][^>]+content=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["'](?:og:image|twitter:image)/gi))n(i[1]);for(let i of t.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi))try{let o=JSON.parse(i[1]),a=[o?.image,o?.logo,o?.thumbnail,o?.primaryImageOfPage];for(let l of a)typeof l=="string"?n(l):typeof l?.url=="string"?n(l.url):typeof l?.contentUrl=="string"?n(l.contentUrl):Array.isArray(l)&&l.forEach(c=>{typeof c=="string"?n(c):c?.url&&n(c.url)})}catch{}for(let i of t.matchAll(/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<img[^>]+data-(?:src|lazy|original|lazy-src)=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/srcset=["']([^"']+)["']/gi)){let o=i[1].split(",").map(a=>{let l=a.trim().split(/\s+/);return{url:l[0],w:parseInt(l[1]??"0")||0}}).sort((a,l)=>l.w-a.w)[0];o?.url&&n(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))n(i[1]);return s.filter(i=>/\/(icon|favicon|logo-|pixel|tracking|spacer|blank)\b/i.test(i)||/data:image\//i.test(i)||/\d{1,3}x\d{1,3}\.(gif|png)/i.test(i)?!1:Pt(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function al(t,e){let r=new Set,s=[];for(let n of t.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))try{let i=new URL(n[1],e),o=i.hostname.toLowerCase(),a=i.pathname;(o==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(a)||(o==="www.pexels.com"||o==="pexels.com")&&/^\/photo\/[^?#]+/i.test(a)||o==="pixabay.com"&&/^\/(?:photos|images)\/[^?#]+/i.test(a)||o==="commons.wikimedia.org"&&/^\/wiki\/File:/i.test(a))&&!r.has(i.href)&&(r.add(i.href),s.push(i.href))}catch{}return s.slice(0,20)}var ll=15*1024*1024,cl=15e3,_m=5;function km(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return ge.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function ul(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,text/html,application/xhtml+xml;q=0.9","Accept-Language":"en-US,en;q=0.9",...e?{Referer:e}:{}}}async function $m(t){let e=await fetch(t,{signal:AbortSignal.timeout(cl),redirect:"follow",headers:ul(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",s=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r))throw new Error("HTML page returned where a direct image was expected");let n=await e.arrayBuffer(),i=Buffer.from(n);if(i.length>ll)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:s}}async function Tm(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let s=await fetch(t,{signal:AbortSignal.timeout(cl),redirect:"follow",headers:ul(t)});if(!s.ok)throw new Error(`HTTP ${s.status} while downloading asset`);let n=s.headers.get("content-type")||"",i=s.url||t;if(/text\/html|application\/xhtml\+xml/i.test(n)){let l=await s.text(),c=ft(l,i).map(d=>({url:d,..._r(d,"","",e)})).sort((d,h)=>h.score-d.score).slice(0,_m);if(c.length===0)throw new Error("HTML page did not expose a direct image candidate");let f="no candidate attempt made";for(let d of c)try{return await $m(d.url)}catch(h){f=String(h?.message||h)}throw new Error(`all ranked HTML image candidates failed: ${f}`)}let o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>ll)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:n,finalUrl:i}}function Cm(t){let e=t.toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("products")?"product":"generic"}function fl(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),s=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!s)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:n,contentType:i,finalUrl:o}=await Tm(r,Cm(s)),a=ge.resolve(t,s),c=ge.extname(a)?a:a+km(i,o);return kr.mkdirSync(ge.dirname(c),{recursive:!0}),kr.writeFileSync(c,n),{success:!0,output:`Downloaded asset: ${ge.relative(t,c)||ge.basename(c)}
|
|
112
120
|
Final source: ${o}
|
|
113
121
|
Type: ${i||"unknown"}
|
|
114
|
-
Size: ${
|
|
115
|
-
|
|
122
|
+
Size: ${n.length} bytes`}}catch(n){return{success:!1,output:"",error:`download failed: ${n?.message||String(n)}`}}}}}var $r=k(require("fs")),Tr=k(require("path"));var wn=15e3,dl=5;function pl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function hl(t,e){return t[e]|t[e+1]<<8}function Em(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],s=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+s}return{}}function Am(t){let e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30){let r=(t.readUInt16LE(26)&16383)+1,s=(t.readUInt16LE(28)&16383)+1;return{width:r,height:s}}return{}}function yn(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:pl(t,16),height:pl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:hl(t,6),height:hl(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Em(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Am(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function yl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{}return{"User-Agent":"Mozilla/5.0 (compatible; HablasBot/2.0; +https://hablas.dev)",Accept:"image/*,text/html,*/*;q=0.8",...e?{Referer:e}:{}}}async function ml(t){let e=await fetch(t,{signal:AbortSignal.timeout(wn),redirect:"follow",headers:yl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let r=e.headers.get("content-type")||"",s=e.url||t,n=await e.arrayBuffer(),i=Buffer.from(n).subarray(0,2*1024*1024),o=/text\/html|application\/xhtml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:s,html:o}}async function gl(t){let e=await fetch(t,{signal:AbortSignal.timeout(wn),redirect:"follow",headers:{...yl(t),Accept:"text/html,application/xhtml+xml;q=0.9,*/*;q=0.8"}});if(!e.ok)throw new Error(`HTTP ${e.status}`);return{finalUrl:e.url||t,html:await e.text()}}async function Om(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:vr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),s=await fetch(`https://commons.wikimedia.org/w/api.php?${r}`,{signal:AbortSignal.timeout(wn),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!s.ok)throw new Error(`Wikimedia HTTP ${s.status}`);let n=await s.json();return Object.values(n?.query?.pages||{}).map(i=>({title:String(i?.title||""),url:String(i?.imageinfo?.[0]?.url||i?.imageinfo?.[0]?.thumburl||""),snippet:String(i?.title||"").replace(/^File:/i,""),source:"wikimedia"})).filter(i=>i.url.startsWith("http")).slice(0,e)}function Rm(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
|
|
123
|
+
|
|
124
|
+
Context from user: "${t}"
|
|
125
|
+
|
|
126
|
+
Return this exact JSON structure \u2014 no markdown, no commentary:
|
|
116
127
|
{
|
|
117
|
-
"
|
|
118
|
-
"
|
|
119
|
-
"
|
|
120
|
-
"
|
|
121
|
-
"
|
|
122
|
-
"
|
|
123
|
-
"summary": "one short sentence"
|
|
128
|
+
"description": "one sentence describing what is in the image",
|
|
129
|
+
"suitable": true,
|
|
130
|
+
"confidence": 0.85,
|
|
131
|
+
"issues": [],
|
|
132
|
+
"suggestedUse": "generic",
|
|
133
|
+
"summary": "one short sentence verdict"
|
|
124
134
|
}
|
|
135
|
+
|
|
125
136
|
Rules:
|
|
126
|
-
-
|
|
127
|
-
-
|
|
128
|
-
-
|
|
129
|
-
-
|
|
130
|
-
-
|
|
131
|
-
|
|
132
|
-
-
|
|
133
|
-
- `)
|
|
134
|
-
`)}}},{name:"inspect_image",description:"
|
|
135
|
-
`)}}
|
|
137
|
+
- suitable: true if the image matches the user context, false otherwise
|
|
138
|
+
- confidence: float 0.0\u20131.0
|
|
139
|
+
- suggestedUse: one of "hero", "product", "icon", "generic", "reject"
|
|
140
|
+
- issues: list any quality or relevance problems (empty array if none)
|
|
141
|
+
- Do NOT output anything outside the JSON object`}async function Im(t,e,r,s){let n=t.provider==="nvidia"?oe.apiUrl:t.apiUrl;if(!n)throw new Error("No API URL configured for vision");let i=`data:${r};base64,${e.toString("base64")}`,o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=t.vision.primaryModel,l=await fetch(n.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:Rm(s)},{role:"user",content:[{type:"text",text:"Inspect this image."},{type:"image_url",image_url:{url:i}}]}],temperature:.1,max_tokens:300})});if(!l.ok)throw new Error(`Vision API HTTP ${l.status}`);let c=await l.json(),f=String(c?.choices?.[0]?.message?.content??""),d=null,h=f.indexOf("{"),p=f.lastIndexOf("}");if(h!==-1&&p>h)try{d=JSON.parse(f.slice(h,p+1))}catch{}if(!d)throw new Error("Vision response was not valid JSON");return{model:a,success:!0,description:String(d.description??""),suitable:!!d.suitable,confidence:Number(d.confidence??0),issues:Array.isArray(d.issues)?d.issues.map(String):[],suggestedUse:String(d.suggestedUse??"generic"),summary:String(d.summary??""),raw:f}}function Pm(t,e,r){return!e||!r?0:(t==="hero"||t==="banner")&&e>=1200&&r>=500?12:(t==="product"||t==="thumbnail")&&e>=400&&r>=400?8:t==="icon"&&e>=64&&e<=512?6:t==="generic"&&e>=600&&r>=400?5:0}function wl(t,e){return[{name:"search_image_candidates",description:["Search for ranked image URL candidates from trusted stock sites (Unsplash, Pexels, Pixabay, Wikimedia).","Returns a scored list of direct image URLs ready for inspect_image.","Use kind to signal intended use: hero, product, icon, avatar, banner, thumbnail, or generic.",'query should describe what you need visually (e.g. "mountain sunset landscape", "red sports car", "smiling woman portrait").'].join(" "),safety:"safe",parameters:{query:{type:"string",description:"Visual description of the image you need",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic (default: generic)",required:!1},max_results:{type:"number",description:"Max candidates to return (1\u201310, default: 5)",required:!1}},execute:async r=>{let s=String(r.query||"").trim();if(!s)return{success:!1,output:"",error:"query is required"};let n=gn(r.kind),i=Math.min(Math.max(1,Number(r.max_results??5)),10),o=Sr(s),a=new Map,l=[],c=(h,p,u,g)=>{if(a.has(h))return;let m=_r(h,p,u,n,o);a.set(h,{url:h,title:p,snippet:u,source:g,...m})};for(let h of il(s,n))try{let{finalUrl:p,html:u}=await gl(h.url),g=al(u,p),m=0;for(let b of g.slice(0,dl*2)){if(m>=dl)break;try{let{finalUrl:w,html:v}=await gl(b),C=ft(v,w)[0];C&&(c(C,h.source+" photo",s,h.source),m++)}catch{}}let x=ft(u,p);for(let b of x.slice(0,6))c(b,h.source,s,h.source);m===0&&x.length===0&&l.push(`${h.source}: no images found`)}catch(p){l.push(`${h.source}: ${String(p?.message??p)}`)}try{let h=await Om(s,Math.max(4,i));for(let p of h)c(p.url,p.title,p.snippet,p.source)}catch(h){l.push(`wikimedia: ${String(h?.message??h)}`)}if(a.size<i)for(let h of ol(s,n))try{let p=await mn(h,Math.max(6,i));for(let u of p)c(u.url,u.title,u.snippet,u.source);if(a.size>=i*2)break}catch{}let f=[...a.values()].sort((h,p)=>p.score-h.score).slice(0,i);if(f.length===0)return{success:!0,output:`No image candidates found for "${s}".${l.length?`
|
|
142
|
+
Notes:
|
|
143
|
+
- `+l.join(`
|
|
144
|
+
- `):""}`};let d=[`Image candidates for: "${s}" (kind=${n}) \u2014 ${f.length} results`,""];return f.forEach((h,p)=>{d.push(`[${p+1}] score=${h.score} trusted=${h.trusted?"yes":"no"} source=${h.source}`),d.push(` url: ${h.url}`),h.title&&d.push(` title: ${h.title}`),h.positives.length&&d.push(` \u2713 ${h.positives.join(", ")}`),h.negatives.length&&d.push(` \u2717 ${h.negatives.join(", ")}`),d.push("")}),l.length&&(d.push("Notes:"),l.slice(0,5).forEach(h=>d.push(" - "+h))),{success:!0,output:d.join(`
|
|
145
|
+
`)}}},{name:"inspect_image",description:["Deeply inspect a remote image URL or local file path.","Returns: content-type, dimensions (w\xD7h), direct-image confirmation, trusted-host status, scoring, and an optional vision analysis.","Use after search_image_candidates to verify the best pick before adopting it.","Set use_vision=false to skip vision (faster, cheaper). Default: true when configured.",'The context parameter tells the vision model what you need (e.g. "hero image for a tech startup landing page").'].join(" "),safety:"safe",parameters:{source:{type:"string",description:"Remote URL (https://...) or local file path",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic",required:!1},context:{type:"string",description:"Describe what you need this image for (used for vision analysis)",required:!1},use_vision:{type:"string",description:'"true" or "false" \u2014 whether to run vision model analysis (default: true)',required:!1}},execute:async r=>{let s=String(r.source||"").trim();if(!s)return{success:!1,output:"",error:"source is required"};let n=gn(r.kind),i=String(r.context||s).slice(0,200),o=String(r.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${s}`,""],l="unknown",c,f,d=!1,h=!1,p=s,u=null,g=!1,m=[];try{if(/^https?:\/\//i.test(s)){let w=await ml(s);if(p=w.finalUrl,l=w.contentType,h=Pt(p),w.html){if(g=!0,m=ft(w.html,p),m.length>0){let v=m[0];try{let _=await ml(v);p=_.finalUrl,l=_.contentType,u=_.bytes,h=Pt(p);let C=yn(u,l);c=C.width,f=C.height,d=/^image\//i.test(l)}catch(_){a.push(` [warn] could not fetch best candidate: ${_.message}`)}}}else{u=w.bytes,d=/^image\//i.test(l)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(p);let v=yn(u,l);c=v.width,f=v.height}}else{let w=Tr.resolve(t,s);if(!$r.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${s}`};u=$r.readFileSync(w).subarray(0,2*1024*1024);let v=Tr.extname(w).toLowerCase();l={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml"}[v]||"application/octet-stream",d=!0,h=!1;let _=yn(u,l);c=_.width,f=_.height}}catch(w){return{success:!1,output:"",error:`Failed to fetch/read source: ${w.message}`}}a.push(` final URL: ${p}`),a.push(` content-type: ${l}`),a.push(` direct image: ${d?"yes":"no (HTML page)"}`),a.push(` trusted host: ${h?"yes":"no"}`),c&&f&&a.push(` dimensions: ${c} \xD7 ${f} px`),u&&a.push(` size (fetched): ${(u.length/1024).toFixed(1)} KB`),g&&(a.push(" resolved via: HTML page extraction"),m.length>1&&(a.push(` other candidates found (${m.length-1}):`),m.slice(1,4).forEach(w=>a.push(` - ${w}`))));let x=Pm(n,c,f);if(c&&f){let w=x>0;a.push(` size verdict: ${w?"\u2713 adequate for "+n:"\u2717 may be too small for "+n} (${c}\xD7${f})`)}if(o&&e.vision.enabled&&u&&/^image\//i.test(l)){a.push(""),a.push(" Vision analysis:");try{let w=await Im(e,u.subarray(0,e.vision.maxImageBytes),l,i);a.push(` model: ${w.model}`),a.push(` description: ${w.description}`),a.push(` suitable: ${w.suitable?"yes":"no"}`),a.push(` confidence: ${(w.confidence*100).toFixed(0)}%`),a.push(` suggested: ${w.suggestedUse}`),a.push(` summary: ${w.summary}`),w.issues.length>0&&a.push(` issues: ${w.issues.join("; ")}`)}catch(w){a.push(` [vision unavailable: ${w.message}]`),e.vision.enabled||a.push(" (enable vision in config to use this feature)")}}else e.vision.enabled||(a.push(""),a.push(" [vision: disabled in config]"));a.push("");let b=d&&(h||/^image\//i.test(l));return a.push(` VERDICT: ${b?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
|
|
146
|
+
`)}}}]}var te=k(require("fs")),Sn=k(require("path")),vl=k(require("os")),_l=k(require("crypto")),Mt=Sn.join(vl.homedir(),".hablas"),bn=Sn.join(Mt,"memory.json"),bl=1,xl=2e3,Mm=1600,jm=8e3;function Lm(){return _l.randomBytes(8).toString("hex")}function Sl(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Dm(t,e){let r=t+".tmp."+process.pid;te.writeFileSync(r,e,"utf-8"),te.renameSync(r,t)}var xn=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(te.existsSync(Mt)||te.mkdirSync(Mt,{recursive:!0}),te.existsSync(bn)){let e=JSON.parse(te.readFileSync(bn,"utf-8"));if(e.version===bl)return e}}catch{}return{version:bl,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{te.existsSync(Mt)||te.mkdirSync(Mt,{recursive:!0}),Dm(bn,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(s=>s!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],s=Date.now(),n=e.value.slice(0,jm);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=n,a.updatedAt=s,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=s+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=Lm(),o={id:i,kind:e.kind,key:e.key,value:n,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:s,updatedAt:s,accessCount:0,lastAccessed:s,ttl:e.ttl?s+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let s=this.store.entries[r];return s?s.ttl&&Date.now()>s.ttl?(this.forget(e),null):(s.accessCount++,s.lastAccessed=Date.now(),this.scheduleFlush(),s):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let s=this.store.entries[r];return s?(this.removeFromIndex(s),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let s=Date.now(),n=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&s>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let f=0,d="value",h=c.key.toLowerCase(),p=c.value.toLowerCase();if(h===o)f=1,d="key";else if(h.includes(o))f=Math.max(f,.8),d="key";else if(c.tags.some(u=>u.toLowerCase().includes(o)))f=Math.max(f,.7),d="tag";else{let u=a.filter(g=>p.includes(g)).length;u>0&&(f=Math.max(f,u/Math.max(a.length,1)*.6),d="value")}f>0&&(f=Math.min(1,f+Sl(c.priority)*.05+Math.min(.1,c.accessCount*.01)),l.push({entry:c,score:f,matchedOn:d}))}return l.filter(c=>c.score>=i).sort((c,f)=>f.score-c.score).slice(0,n)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(s=>s.kind===e&&(!s.ttl||Date.now()<s.ttl)).sort((s,n)=>n.updatedAt-s.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,s)=>s.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<xl)return;let r=Date.now();for(let s of Object.values(this.store.entries))s.ttl&&r>s.ttl&&(this.removeFromIndex(s),delete this.store.entries[s.id],e--);if(e>=xl){let s=Object.values(this.store.entries).map(n=>({id:n.id,score:Sl(n.priority)*10+n.accessCount+n.lastAccessed/1e12})).sort((n,i)=>n.score-i.score);for(let{id:n}of s.slice(0,e-Mm)){let i=this.store.entries[n];i&&(this.removeFromIndex(i),delete this.store.entries[n])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
|
|
136
147
|
Stack: ${r.stack}${r.summary?`
|
|
137
|
-
Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,
|
|
138
|
-
Rationale: ${
|
|
139
|
-
Outcome: ${
|
|
140
|
-
`).slice(0,r)}},
|
|
148
|
+
Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,s){this.remember({kind:"decision",key:`decision:${e}:${r.slice(0,60)}`,value:`Decision: ${r}
|
|
149
|
+
Rationale: ${s}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,r){this.remember({kind:"preference",key:`pref:${e}`,value:r,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,r,s){this.remember({kind:"task_summary",key:`task:${e}:${r.slice(0,60)}:${Date.now()}`,value:`Task: ${r}
|
|
150
|
+
Outcome: ${s}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,r=3e3){let s=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){s.push("## Memory: this project");for(let o of i.slice(0,8))s.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let n=this.getByKind("preference",5);if(n.length>0){s.push("## Memory: user preferences");for(let i of n)s.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return s.join(`
|
|
151
|
+
`).slice(0,r)}},Cr=null;function z(){return Cr||(Cr=new xn),Cr}function kl(){Cr?.flush()}var Er=["project","preference","decision","pattern","tool_outcome","fact","task_summary"];function $l(){return[{name:"remember",description:"Store a fact, decision, preference, or pattern in persistent memory that survives across sessions. Use this to remember important project decisions, user preferences, or recurring patterns you want to recall later.",safety:"safe",parameters:{key:{type:"string",description:'Unique semantic key, e.g. "pref:coding-style" or "decision:/home/user/app:state-management"',required:!0},value:{type:"string",description:"The content to remember \u2014 decision, preference, fact, or outcome text",required:!0},kind:{type:"string",description:`Category: ${Er.join(" | ")}`,required:!0},tags:{type:"string",description:'Comma-separated tags for grouping, e.g. "typescript,react,architecture"',required:!1},project:{type:"string",description:"Absolute project path this memory belongs to (optional)",required:!1},priority:{type:"string",description:"critical | high | normal | low (default: normal)",required:!1}},execute:async t=>{try{let e=t.kind;if(!Er.includes(e))return{success:!1,output:"",error:`Invalid kind "${t.kind}". Must be one of: ${Er.join(", ")}`};let r=t.key,s=t.value;if(!r||!s)return{success:!1,output:"",error:"key and value are required"};let n=t.tags?t.tags.split(",").map(a=>a.trim()).filter(Boolean):[],i=t.priority??"normal",o=z().remember({kind:e,key:r,value:s,tags:n,project:t.project,priority:i});return{success:!0,output:`Remembered [${e}] key="${r}" (id=${o})`}}catch(e){return{success:!1,output:"",error:`[remember]: ${e.message}`}}}},{name:"recall",description:"Retrieve a specific memory entry by its exact key. Returns null if not found.",safety:"safe",parameters:{key:{type:"string",description:"The exact key used when storing the memory",required:!0}},execute:async t=>{try{let e=z().recall(t.key);return e?{success:!0,output:[`Key: ${e.key}`,`Kind: ${e.kind}`,`Priority: ${e.priority}`,`Tags: ${e.tags.join(", ")||"\u2014"}`,`Value:
|
|
141
152
|
${e.value}`,`Last accessed: ${new Date(e.lastAccessed).toISOString()} (${e.accessCount}x)`].join(`
|
|
142
|
-
`)}:{success:!0,output:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[recall]: ${e.message}`}}}},{name:"search_memory",description:"Semantic search across all persistent memories. Use this at the start of complex tasks to retrieve relevant past decisions, preferences, and project knowledge.",safety:"safe",parameters:{query:{type:"string",description:"Natural language search query",required:!0},kind:{type:"string",description:`Optional filter by kind: ${
|
|
143
|
-
${
|
|
153
|
+
`)}:{success:!0,output:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[recall]: ${e.message}`}}}},{name:"search_memory",description:"Semantic search across all persistent memories. Use this at the start of complex tasks to retrieve relevant past decisions, preferences, and project knowledge.",safety:"safe",parameters:{query:{type:"string",description:"Natural language search query",required:!0},kind:{type:"string",description:`Optional filter by kind: ${Er.join(" | ")}`,required:!1},project:{type:"string",description:"Optional: limit to a specific project path",required:!1},limit:{type:"number",description:"Max results (default: 8)",required:!1}},execute:async t=>{try{let e=z().search(t.query,{kind:t.kind,project:t.project,limit:t.limit||8});if(e.length===0)return{success:!0,output:"No relevant memories found."};let r=e.map((s,n)=>`${n+1}. [${s.entry.kind}] key="${s.entry.key}" score=${s.score.toFixed(2)}
|
|
154
|
+
${s.entry.value.replace(/\n/g," \u2014 ").slice(0,180)}`);return{success:!0,output:`Found ${e.length} relevant memories:
|
|
144
155
|
|
|
145
156
|
${r.join(`
|
|
146
157
|
|
|
147
|
-
`)}`}}catch(e){return{success:!1,output:"",error:`[search_memory]: ${e.message}`}}}},{name:"forget",description:"Delete a memory entry by its exact key. Use when a decision or preference is no longer valid.",safety:"safe",parameters:{key:{type:"string",description:"The exact key of the memory to delete",required:!0}},execute:async t=>{try{return{success:!0,output:
|
|
148
|
-
`)}}catch(t){return{success:!1,output:"",error:`[memory_stats]: ${t.message}`}}}}]}var
|
|
149
|
-
`).filter(Boolean),
|
|
150
|
-
`).filter(Boolean).length;
|
|
151
|
-
`)}}},{name:"git_diff",description:"Show the diff for a file or the whole working tree. Useful to understand exactly what changed before or after edits.",safety:"safe",parameters:{path:{type:"string",description:"File path to diff (optional \u2014 omit for full diff)",required:!1},staged:{type:"string",description:'Set "true" to show staged diff (default: unstaged)',required:!1},lines:{type:"number",description:"Context lines around each change (default: 3)",required:!1}},execute:async e=>{if(!
|
|
152
|
-
... [diff truncated]`:o.output}}},{name:"git_log",description:"Show recent git commit history with author, date, and message. Optionally filter by file.",safety:"safe",parameters:{limit:{type:"number",description:"Number of commits to show (default: 10)",required:!1},path:{type:"string",description:"File path to filter commits by (optional)",required:!1},stats:{type:"string",description:'Set "true" to include file change stats per commit',required:!1}},execute:async e=>{if(!
|
|
158
|
+
`)}`}}catch(e){return{success:!1,output:"",error:`[search_memory]: ${e.message}`}}}},{name:"forget",description:"Delete a memory entry by its exact key. Use when a decision or preference is no longer valid.",safety:"safe",parameters:{key:{type:"string",description:"The exact key of the memory to delete",required:!0}},execute:async t=>{try{return{success:!0,output:z().forget(t.key)?`Deleted memory "${t.key}"`:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[forget]: ${e.message}`}}}},{name:"memory_stats",description:"Show memory storage statistics: total entries, breakdown by kind, most recently accessed.",safety:"safe",parameters:{},execute:async()=>{try{let t=z().getStats(),e=z().getRecent(5);return{success:!0,output:[`Total memories: ${t.total}`,"Breakdown:",...Object.entries(t).filter(([s])=>s!=="total").map(([s,n])=>` ${s}: ${n}`),"","Most recently accessed:",...e.map(s=>` [${s.kind}] ${s.key.slice(0,60)} \u2014 ${new Date(s.lastAccessed).toISOString()}`)].join(`
|
|
159
|
+
`)}}catch(t){return{success:!1,output:"",error:`[memory_stats]: ${t.message}`}}}}]}var Tl=require("child_process");function Te(t,e,r=1e4){try{return{ok:!0,output:(0,Tl.execSync)(t,{cwd:e,timeout:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{ok:!1,output:(s.stderr?.toString()||s.stdout?.toString()||s.message||"command failed").trim()}}}function Ar(t){let e=Te("git rev-parse --is-inside-work-tree",t,3e3);return e.ok&&e.output==="true"}function Cl(t){return[{name:"git_status",description:"Show the current git status: staged files, unstaged changes, untracked files, stash count, branch tracking state (ahead/behind remote). Use this to understand the state of the repository before making changes.",safety:"safe",parameters:{short:{type:"string",description:'Set to "true" for a compact one-line-per-file view (default: false)',required:!1}},execute:async e=>{if(!Ar(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.short==="true",s=[],n=Te("git branch --show-current",t),i=Te('git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no-remote"',t);if(s.push(`Branch: ${n.output||"(detached HEAD)"}`),i.ok&&i.output!=="no-remote"){let c=Te(`git rev-list --left-right --count HEAD...${i.output}`,t);if(c.ok){let[f,d]=c.output.split(" ").map(Number);f>0&&s.push(`Ahead of remote: ${f} commit(s)`),d>0&&s.push(`Behind remote: ${d} commit(s)`)}s.push(`Remote: ${i.output}`)}let a=Te(r?"git status --short":"git status --porcelain=v1",t);if(a.ok&&a.output){s.push(""),s.push("Changes:");let c=a.output.split(`
|
|
160
|
+
`).filter(Boolean),f=c.filter(p=>!"? ".includes(p[0])),d=c.filter(p=>p[1]!==" "&&p[0]===" "),h=c.filter(p=>p.startsWith("??"));f.length>0&&(s.push(" Staged:"),f.forEach(p=>s.push(` ${p.slice(0,2)} ${p.slice(3)}`))),d.length>0&&(s.push(" Unstaged:"),d.forEach(p=>s.push(` ${p.slice(0,2)} ${p.slice(3)}`))),h.length>0&&(s.push(` Untracked: ${h.length} file(s)`),h.length<=5&&h.forEach(p=>s.push(` ${p.slice(3)}`)))}else s.push("Working tree: clean");let l=Te("git stash list --oneline",t);if(l.ok&&l.output){let c=l.output.split(`
|
|
161
|
+
`).filter(Boolean).length;s.push(`Stash: ${c} stashed change(s)`)}return{success:!0,output:s.join(`
|
|
162
|
+
`)}}},{name:"git_diff",description:"Show the diff for a file or the whole working tree. Useful to understand exactly what changed before or after edits.",safety:"safe",parameters:{path:{type:"string",description:"File path to diff (optional \u2014 omit for full diff)",required:!1},staged:{type:"string",description:'Set "true" to show staged diff (default: unstaged)',required:!1},lines:{type:"number",description:"Context lines around each change (default: 3)",required:!1}},execute:async e=>{if(!Ar(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.staged==="true"?"--cached ":"",s=e.lines?`-U${e.lines}`:"-U3",n=e.path?`-- "${e.path}"`:"",i=`git diff ${r}${s} ${n}`.trim(),o=Te(i,t);if(!o.ok)return{success:!1,output:"",error:o.output};if(!o.output)return{success:!0,output:e.path?`No diff for ${e.path}`:"No changes detected."};let a=8e3;return{success:!0,output:o.output.length>a?o.output.slice(0,a)+`
|
|
163
|
+
... [diff truncated]`:o.output}}},{name:"git_log",description:"Show recent git commit history with author, date, and message. Optionally filter by file.",safety:"safe",parameters:{limit:{type:"number",description:"Number of commits to show (default: 10)",required:!1},path:{type:"string",description:"File path to filter commits by (optional)",required:!1},stats:{type:"string",description:'Set "true" to include file change stats per commit',required:!1}},execute:async e=>{if(!Ar(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.limit||10,s=e.path?`-- "${e.path}"`:"",n=e.stats==="true"?"--stat":"",o=`git log -${r} --format="%h %as %an %s" ${n} ${s}`.trim(),a=Te(o,t);return a.ok?{success:!0,output:a.output||"No commits found."}:{success:!1,output:"",error:a.output}}},{name:"git_branch",description:"List git branches, show current branch, and tracking info.",safety:"safe",parameters:{all:{type:"string",description:'Set "true" to include remote branches (default: local only)',required:!1}},execute:async e=>{if(!Ar(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.all==="true"?"-a":"",s=Te(`git branch ${r} -vv`,t);return s.ok?{success:!0,output:s.output||"No branches found."}:{success:!1,output:"",error:s.output}}}]}var dt=class{tools=new Map;constructor(e,r){let s=Aa(e);for(let n of s)this.tools.set(n.name,n);this.tools.set("run_command",Pa(e,r)),this.tools.set("bash_output",Ma(e)),this.tools.set("kill_shell",ja(e)),this.tools.set("search_codebase",La(e)),this.tools.set("detect_bugs",Na(e)),this.tools.set("web_search",Va());for(let n of Wa())this.tools.set(n.name,n);for(let n of Xa(e))this.tools.set(n.name,n);for(let n of nl())this.tools.set(n.name,n);this.tools.set("download_asset",fl(e));for(let n of wl(e,r))this.tools.set(n.name,n);for(let n of $l())this.tools.set(n.name,n);for(let n of Cl(e))this.tools.set(n.name,n)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},s=[];for(let[n,i]of Object.entries(e.parameters))r[n]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(n);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:s}}}})}getToolDescriptions(){return this.getAll().map(r=>{let s=Object.entries(r.parameters).map(([n,i])=>` ${n}: ${i.type} \u2014 ${i.description}`).join(`
|
|
153
164
|
`);return`- ${r.name} [${r.safety}]: ${r.description}
|
|
154
|
-
${
|
|
165
|
+
${s}`}).join(`
|
|
155
166
|
|
|
156
|
-
`)}};var
|
|
157
|
-
... [truncated to fit context budget]`}var pt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,
|
|
158
|
-
${l}`),
|
|
159
|
-
${o.content}`),
|
|
167
|
+
`)}};var El=k(require("crypto"));function vn(t){return Math.ceil(t.length/3.5)}function jt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
|
|
168
|
+
... [truncated to fit context budget]`}var pt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,s){let n=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===n){i.lastUsed=Date.now(),i.accessCount++;return}let o=vn(r),a=s?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:n,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let s=this.cache.get(e);return s?s.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),n=0,i=[];for(let o of s){if(n+o.tokenCount>r){if(o.importance>=7){let a=r-n;if(a>200){let l=jt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
169
|
+
${l}`),n+=a}}continue}i.push(`--- ${o.path} ---
|
|
170
|
+
${o.content}`),n+=o.tokenCount}return i.join(`
|
|
160
171
|
|
|
161
|
-
`)}buildAgentContext(e,r){let
|
|
172
|
+
`)}buildAgentContext(e,r){let s=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(f=>c.path.includes(f))).sort((c,f)=>this.computeScore(f)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>s)break;l.push(`--- ${c.path} ---
|
|
162
173
|
${c.content}`),a+=c.tokenCount}return l.join(`
|
|
163
174
|
|
|
164
|
-
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([
|
|
175
|
+
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([n,i])=>({key:n,...i,score:this.computeScore(i)})).sort((n,i)=>n.score-i.score),s=0;for(let n of r){if(s>=e)break;n.importance>=9||(s+=n.tokenCount,this.usedTokens-=n.tokenCount,this.cache.delete(n.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let n=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-n/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let n=vn(r);return n>2e3&&(s=Math.max(1,s-1)),n>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let s of r)if(s!==e){let n=this.cache.get(s);n&&!n.relatedFiles.includes(e)&&n.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return El.createHash("md5").update(e).digest("hex")}};var Fm=0;function Lt(){return`msg_${Date.now()}_${++Fm}`}function ht(t){return Math.ceil(t.length/4)}var mt=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,s=32e3){this.maxMessages=r,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let n=ht(e);this.messages.push({id:Lt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:n,compressed:!1,tags:["system"]}),this.totalTokens=n}getSessionId(){return this.sessionId}addUserMessage(e,r){let s=Lt(),n=ht(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:n,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=n,this.trimIfNeeded(),s}addAssistantMessage(e,r,s){let n=Lt(),i=ht(e),o={id:n,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),n}addToolMessage(e,r){let s=Lt(),n=ht(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:n,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=n,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=ht(e),s={id:Lt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[s],this.recalculateTokens();return}this.messages[0]=s,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(s=>s.id===e);return r?(this.messages=r.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let s=this.messages.length,n=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?n.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&n.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:n}),n}mergeFork(e,r){let s=this.forks.get(e);if(!s)return!1;let n=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(n.length>0){let i=n.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(s=>s.role===e).slice(-r)}compress(){let e=this.totalTokens,r=this.messages.filter(n=>n.role==="tool"&&!n.compressed&&n.tokenEstimate>100);for(let n of r.slice(0,-2))this.compressMessage(n);let s=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>150);for(let n of s.slice(0,-2))this.compressMessage(n);return e-this.totalTokens}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],s=this.messages.slice(1),n={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=n[a.priority]-n[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
|
|
165
176
|
...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
|
|
166
|
-
...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=
|
|
167
|
-
`)}async function wt(t,e){let r=[],
|
|
168
|
-
`)}function Gh(t,e){try{return yt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function bt(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",Q("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",Q("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",Q("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",Q("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",Q("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",Q("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",Q("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",Q("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",Q("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",Q("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",Q("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",Q("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let n=V().buildContextBlock(r,2500);return n.trim()?[Q("PERSISTENT MEMORY",n),""]:[]})(),Q("TASK PROFILE",Yh(e)),"",Q("CURRENT PROJECT CONTEXT",Jh(t))].join(`
|
|
177
|
+
...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=ht(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var yt=k(require("fs")),Al=k(require("path"));var O=k(require("fs")),R=k(require("path"));function Nm(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let r=JSON.parse(O.readFileSync(e,"utf-8")),s={...r.dependencies,...r.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let r=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Um(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 qm(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 Bm(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let r=O.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function gt(t){let e=Nm(t),r=Um(t),s=qm(t),n=Bm(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 g of f)O.existsSync(R.join(t,g))&&c.push(g);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 g of h)O.existsSync(R.join(t,g))&&d.push(g);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 g of u)O.existsSync(R.join(t,g))&&p.push(g);return{rootPath:t,framework:e,packageManager:r,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:n,envFiles:c,configFiles:d,entryPoints:p}}function Or(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(`
|
|
178
|
+
`)}async function wt(t,e){let r=[],s=Al.join(t,"package.json");if(yt.existsSync(s))try{let o=JSON.parse(yt.readFileSync(s,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let n=gt(t);r.push(`Framework: ${n.framework}`),r.push(`Language: ${n.language}`),r.push(`Package Manager: ${n.packageManager}`),r.push(`Git: ${n.hasGit?n.gitBranch||"present":"absent"}`);let i=Hm(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&n.envFiles.length>0&&r.push(`Env files: ${n.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
|
|
179
|
+
`)}function Hm(t,e){try{return yt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function bt(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",Q("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",Q("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",Q("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",Q("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",Q("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",Q("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",Q("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",Q("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",Q("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",Q("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",Q("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",Q("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let s=z().buildContextBlock(r,2500);return s.trim()?[Q("PERSISTENT MEMORY",s),""]:[]})(),Q("TASK PROFILE",Vm(e)),"",Q("CURRENT PROJECT CONTEXT",Wm(t))].join(`
|
|
169
180
|
`)}function Q(t,e){let r=Array.isArray(e)?e.join(`
|
|
170
181
|
`):e;return["====================",t,"====================",r].join(`
|
|
171
|
-
`)}function
|
|
182
|
+
`)}function Wm(t){return t.trim()||"No project context captured."}function Vm(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
|
|
172
183
|
`):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Answer directly, then support with observed facts when useful.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
|
|
173
184
|
`):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning from constraints first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, practical guidance, and the best next move."].join(`
|
|
174
185
|
`):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with minimal follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Preserve the existing architecture unless the user explicitly asks for a structural change.","- Verify changes before claiming completion.","- End with a compact executive report, not a vague narrative."].join(`
|
|
175
|
-
`)}var
|
|
176
|
-
`)&&(r+=1),
|
|
177
|
-
`)}function
|
|
178
|
-
`+y.border(
|
|
186
|
+
`)}var zm=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|configure|setup|set\s*up|install|integrate|connect|enable|disable|replace|rewrite|convert|transform|optimize|improve|upgrade|scaffold|init|initialize|bootstrap|wire|patch|apply|inject)\b/i,Km=/\b(انشئ|اعمل|ابني|طور|عدل|صلح|حدث|اضف|احذف|ارسل|فعل|شغل|حول|ضبط|هيئ|نفذ|اكتب|غير|بناء|تطوير|تعديل|اضافة|حذف|انشاء|تنفيذ|كود|برمج)\b/i,Gm=/\b(continue|resume|proceed|keep|finish|complete|pick\s*up|unfinished|remaining|previous|existing|current project|from the prd|where we left)\b/i,Jm=/\b(كمل|استمر|اكمل|واصل|ارجع|خلينا|لسا|بقي|ما خلصنا)\b/i,Ym=/\b(read|show|list|check|inspect|what|which|where|when|how|explain|describe|tell me|what is|what are|find out|look at|view|examine|analyze|review)\b/i,Xm=/\b(اقرا|اعرض|اشوف|شو|وين|كيف|ليش|وضح|اشرح|فين|ما هو|ما هي|بين|فسر)\b/i,Qm=/\b(architecture|design|blueprint|plan|approach|trade.?off|compare|research|investigate|document|strategy|structure|pattern|best practice|recommendation|suggest|advise|evaluate|assess|pros|cons)\b/i,Zm=/\b(معمارية|تصميم|خطة|مقارنة|بحث|دراسة|هيكل|نهج|اقتراح|توصية|تقييم)\b/i,eg=/\b(one\s*step|no\s*questions|just\s*do|just\s*give|deliver|finished|complete\s*in\s*one|all\s*at\s*once|without\s*asking)\b/i,tg=/\b(بدون\s*اسئلة|مباشرة|فورا|دفعة\s*واحدة|كامل|بس\s*اعمل|عطني\s*النتيجة)\b/i,rg=/^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|sure|got it|great|nice|cool|perfect|awesome)[.!?\s]*$/i,sg=/^(اه|تمام|شكرا|شكراً|مرحبا|اهلا|هلا|يلا|ماشي|حسنا|طيب|كيفك|صح)[.!?\s]*$/i,Ol=/\b(frontend|backend|api|endpoint|database|schema|component|page|route|store|auth|login|signup|dashboard|sidebar|navbar|header|footer|modal|form|button|card|table|chart|css|scss|style|theme|animation|responsive|mobile|typescript|javascript|python|rust|go|java|kotlin|swift|flutter|react|vue|svelte|next|nuxt|express|fastapi|django|rails|docker|k8s|kubernetes|ci|cd|github|actions|workflow|test|spec|coverage|lint|eslint|prettier|webpack|vite|build|bundle|deploy|nginx|postgres|mysql|mongo|redis|graphql|rest|grpc|websocket|socket)\b/i,ng=/\b(واجهة|خلفية|قاعدة\s*بيانات|مكون|صفحة|مسار|تسجيل|لوحة\s*تحكم|تصميم|موبايل|اختبار|نشر|بناء)\b/i,ig=/\b(full|entire|complete|whole|all|comprehensive|production|enterprise|scalable|real-time|multi|complex|advanced|sophisticated|from\s*scratch|ground\s*up)\b/i,og=/\b(كامل|شامل|متكامل|احترافي|متقدم|من\s*الصفر|كل\s*شيء)\b/i,ag=/\b(files?|components?|modules?|pages?|screens?|services?|controllers?|models?|views?|routes?|handlers?|hooks?|utils?|helpers?|types?|interfaces?)\b/i;function lg(t){let e=(t.match(/[\u0600-\u06FF]/g)||[]).length,r=(t.match(/[a-zA-Z]/g)||[]).length,s=e+r;if(s===0)return"english";let n=e/s;return n>.7?"arabic":n<.2?"english":"mixed"}function Dt(t,e){let r=t.trim().replace(/\s+/g," ");if(r.length<=80)return r;let s=r.match(/^[^.!?\n]{10,80}/)?.[0];return s?s.trim()+"\u2026":r.slice(0,80)+"\u2026"}function Ft(t,e){if(e==="casual")return{complexity:"trivial",estimatedSteps:0};if(e==="read")return{complexity:"simple",estimatedSteps:2};let r=0;(ig.test(t)||og.test(t))&&(r+=3),ag.test(t)&&(r+=2);let s=t.split(/\s+/).length;return s>50&&(r+=1),s>100&&(r+=2),t.includes(`
|
|
187
|
+
`)&&(r+=1),Ol.test(t)&&(r+=1),e==="analysis"?r>=4?{complexity:"complex",estimatedSteps:8}:r>=2?{complexity:"moderate",estimatedSteps:4}:{complexity:"simple",estimatedSteps:2}:r>=7?{complexity:"epic",estimatedSteps:40}:r>=5?{complexity:"complex",estimatedSteps:20}:r>=3?{complexity:"moderate",estimatedSteps:10}:r>=1?{complexity:"simple",estimatedSteps:5}:{complexity:"simple",estimatedSteps:3}}function _n(t){let e=t.trim(),r=lg(e),s=[],n=zm.test(e),i=Km.test(e),o=n||i;n&&s.push("impl:en"),i&&s.push("impl:ar");let a=Gm.test(e)||Jm.test(e);a&&s.push("continuity");let l=eg.test(e)||tg.test(e);l&&s.push("one-step");let c=Ym.test(e)||Xm.test(e);c&&s.push("read");let f=Qm.test(e)||Zm.test(e);f&&s.push("analysis");let d=Ol.test(e)||ng.test(e);d&&s.push("eng-context");let h=/\b(project|repo|repository|codebase|workspace|file|src|package\.json|config)\b/i.test(e)||d;if(h&&s.push("project-ref"),(rg.test(e)||sg.test(e))&&!d&&!o&&!f){let{complexity:g,estimatedSteps:m}=Ft(e,"casual");return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Social turn detected.",complexity:g,estimatedSteps:m,intent:Dt(e,r),language:r,confidence:.95,signals:s}}if(o||a||l||d&&e.length>20&&!c&&!f){let{complexity:g,estimatedSteps:m}=Ft(e,"implementation");return{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:a,oneStepDelivery:l,requiresProjectContext:!0,reason:a?"Continuation of previous work.":"Implementation task detected.",complexity:g,estimatedSteps:m,intent:Dt(e,r),language:r,confidence:.9,signals:s}}if(f&&!o){let{complexity:g,estimatedSteps:m}=Ft(e,"analysis");return{kind:"analysis",needsTools:h,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:h,reason:"Architecture or design analysis requested.",complexity:g,estimatedSteps:m,intent:Dt(e,r),language:r,confidence:.85,signals:s}}if(c||h){let{complexity:g,estimatedSteps:m}=Ft(e,"read");return{kind:"read",needsTools:h,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:h,reason:"Read-only or factual query.",complexity:g,estimatedSteps:m,intent:Dt(e,r),language:r,confidence:.8,signals:s}}let{complexity:p,estimatedSteps:u}=Ft(e,"analysis");return{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Default: analytical response.",complexity:p,estimatedSteps:u,intent:Dt(e,r),language:r,confidence:.6,signals:s}}function cg(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(t.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(t.kind==="analysis")return[{id:"memory",title:"Check persistent memory for relevant past decisions."},{id:"inspect",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result clearly."}];let e=[];return e.push({id:"memory",title:"Check persistent memory for relevant project context."}),t.continuity&&e.push({id:"continuity",title:"Load existing project context \u2014 do not restart from zero."}),t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery \u2014 no follow-up questions."}),e.push({id:"inspect",title:"Inspect the relevant files and project structure."}),(t.complexity==="complex"||t.complexity==="epic")&&e.push({id:"plan",title:"Form a concrete step-by-step implementation plan."}),e.push({id:"implement",title:"Apply the correct implementation using tools."}),e.push({id:"verify",title:"Verify: run build/tests, check for regressions."}),e.push({id:"memory-save",title:"Save key decisions to persistent memory."}),e.push({id:"answer",title:"Report: what was done, what was verified, what remains."}),e}function Rl(t){let e=_n(t);return{input:t,profile:e,plan:cg(e)}}var Kl=k(require("readline")),de=k(require("fs")),re=k(require("path")),Gl=k(require("os"));var Le=k(require("process")),Il=Le.stdout.isTTY===!0,ug=Le.env.NO_COLOR!==void 0||Le.env.TERM==="dumb",Pl=Le.stdout.columns||100;Il&&Le.stdout.on("resize",()=>{Pl=Le.stdout.columns||100});var ue=()=>Math.min(Math.max(Pl-4,60),110);function H(t,e){return!Il||ug?t:`${e}${t}\x1B[0m`}var y={strong:t=>H(t,"\x1B[1;38;5;255m"),muted:t=>H(t,"\x1B[38;5;242m"),accent:t=>H(t,"\x1B[38;5;111m"),accentAlt:t=>H(t,"\x1B[38;5;147m"),info:t=>H(t,"\x1B[38;5;117m"),success:t=>H(t,"\x1B[38;5;114m"),warning:t=>H(t,"\x1B[38;5;179m"),error:t=>H(t,"\x1B[38;5;203m"),primary:t=>H(t,"\x1B[38;5;253m"),secondary:t=>H(t,"\x1B[38;5;247m"),border:t=>H(t,"\x1B[38;5;238m"),borderHi:t=>H(t,"\x1B[38;5;244m"),code:t=>H(t,"\x1B[38;5;222m"),lineNum:t=>H(t,"\x1B[38;5;241m"),dim:t=>H(t,"\x1B[2m"),bold:t=>H(t,"\x1B[1m"),green:t=>H(t,"\x1B[38;5;114m"),red:t=>H(t,"\x1B[38;5;203m"),yellow:t=>H(t,"\x1B[38;5;221m"),blue:t=>H(t,"\x1B[38;5;111m"),purple:t=>H(t,"\x1B[38;5;147m"),cyan:t=>H(t,"\x1B[38;5;152m"),orange:t=>H(t,"\x1B[38;5;209m"),white:t=>H(t,"\x1B[38;5;255m")};function ye(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function kn(t,e,r=" "){let s=ye(t);return s<e?t+r.repeat(e-s):t}var L={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",ml:"\u251C",mr:"\u2524",mt:"\u252C",mb:"\u2534",mc:"\u253C"};var $n=k(require("os")),Ir=k(require("fs")),Rr=k(require("path"));function fg(){let t=[Rr.resolve(__dirname,"..","package.json"),Rr.resolve(__dirname,"..","..","package.json"),Rr.resolve(process.cwd(),"package.json")];for(let e of t)try{if(Ir.existsSync(e)){let r=JSON.parse(Ir.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Tn=fg(),Ml=process.stdout.isTTY===!0;function K(t,e=L.h){return e.repeat(t)}function dg(t,e,r){let s=Math.max(1,r-ye(t)-ye(e));return t+" ".repeat(s)+e}function Dl(t,e){let r=Math.min(ue(),86),s=e.replace($n.homedir(),"~"),n=r-2,i=y.border(L.tl+K(n)+L.tr),o=y.border(L.ml+K(n)+L.mr),a=y.border(L.bl+K(n)+L.br),l=m=>{let x=Math.max(0,n-2-ye(m));return y.border(L.v)+" "+m+" ".repeat(x)+" "+y.border(L.v)},c=(m,x)=>y.border(L.v)+" "+dg(m,x,n-2)+" "+y.border(L.v),f=" H A B L A S ",d=Math.max(0,Math.floor((n-ye(f))/2)),h=y.border(L.v)+" ".repeat(d)+y.strong(f)+" ".repeat(n-d-ye(f))+y.border(L.v),p="single-agent engineering runtime",u=Math.max(0,Math.floor((n-p.length)/2)),g=y.border(L.v)+" ".repeat(u)+y.muted(p)+" ".repeat(n-u-p.length)+y.border(L.v);return["",i,h,g,o,c(y.muted("v"+Tn),y.muted(t)),l(y.muted("workspace ")+y.secondary(s)),o,l(y.secondary("Type your task \xB7 /help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C twice to exit")),a,""].join(`
|
|
188
|
+
`)}function Fl(t){let e=ue(),r=` Turn ${t} `,s=Math.floor((e-ye(r)-2)/2);return`
|
|
189
|
+
`+y.border(K(s))+y.borderHi(r)+y.border(K(e-s-ye(r)))+`
|
|
179
190
|
`}function xt(){return`
|
|
180
|
-
${y.accent("\u25C6")} ${y.strong("Hablas")}`}function
|
|
181
|
-
${y.accent("\xB7")} ${y.secondary(t)}`}function
|
|
182
|
-
`),r=[],
|
|
191
|
+
${y.accent("\u25C6")} ${y.strong("Hablas")}`}function Nl(t){return`
|
|
192
|
+
${y.accent("\xB7")} ${y.secondary(t)}`}function Ul(t,e){let r=pg[t]??"\u2699";return` ${y.muted(r+" ")}${y.muted(t)} ${y.dim(e)}`}function ql(t,e,r){let s=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`,n=t?y.success("\u2713"):y.error("\u2717"),i=e.slice(0,60).replace(/\n/g," "),o=e.length>60?"\u2026":"";return` ${n} ${y.dim(s+" ")}${y.muted(i+o)}`}var pg={read_file:"\u{1F4C4}",write_file:"\u270D",edit_file:"\u270F",patch_file:"\u{1FA79}",search_and_replace:"\u2194",append_to_file:"\u2193",delete_file:"\u{1F5D1}",move_file:"\u2192",create_dir:"\u{1F4C1}",list_dir:"\u{1F4C2}",get_file_info:"\u2139",search_codebase:"\u{1F50D}",run_command:"\u25B6",execute_code:"\u26A1",detect_bugs:"\u{1F41B}",web_search:"\u{1F310}",scrape_url:"\u26CF",extract_links:"\u{1F517}",download_asset:"\u2B07",read_pdf:"\u{1F4D5}",pdf_metadata:"\u{1F4CB}",search_image_candidates:"\u{1F5BC}",inspect_image:"\u{1F441}",remember:"\u{1F4BE}",recall:"\u{1F9E0}",search_memory:"\u{1F50E}",forget:"\u{1F5D1}",memory_stats:"\u{1F4CA}",git_status:"\u{1F4E1}",git_diff:"\xB1",git_log:"\u{1F4DC}",git_branch:"\u{1F33F}"};function De(t){return t.replace(/`([^`]+)`/g,(e,r)=>y.code(r)).replace(/\*\*([^*]+)\*\*/g,(e,r)=>y.strong(r)).replace(/\*([^*]+)\*/g,(e,r)=>y.secondary(r)).replace(/~~([^~]+)~~/g,(e,r)=>y.muted(r))}function jl(t,e=2){let r=ue()-e-2,s=t.split(" "),n=[],i="";for(let o of s){let a=i.replace(/\x1b\[[0-9;]*m/g,""),l=o.replace(/\x1b\[[0-9;]*m/g,"");(a+" "+l).trim().length>r&&i?(n.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o}return i.trim()&&n.push(" ".repeat(e)+i.trim()),n}function hg(t,e){let r=[],s=Math.max(28,ue()-6),n=e?` ${y.yellow(e)}`:"";r.push(` ${y.border(L.tl+K(s)+" ")}${n}`);let i=String(t.length).length;for(let o=0;o<t.length;o++){let a=y.lineNum(String(o+1).padStart(i));r.push(` ${y.border(L.v)} ${a} ${y.border("\u2502")} ${y.code(t[o])}`)}return r.push(` ${y.border(L.bl+K(s))}`),r}function mg(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)return[];let s=[];for(let c of r)c.forEach((f,d)=>{s[d]=Math.max(s[d]??0,ye(f))});let n=` ${y.border(L.tl+s.map(c=>K(c+2)).join(L.mt)+L.tr)}`,i=` ${y.border(L.ml+s.map(c=>K(c+2)).join(L.mc)+L.mr)}`,o=` ${y.border(L.bl+s.map(c=>K(c+2)).join(L.mb)+L.br)}`,a=(c,f=!1)=>{let d=c.map((h,p)=>{let u=f?y.strong(De(h)):De(h);return" "+kn(u,s[p])+" "});return` ${y.border(L.v)}${d.join(y.border(L.v))}${y.border(L.v)}`},l=[n,a(r[0],!0)];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Nt(t){let e=t.split(`
|
|
193
|
+
`),r=[],s=!1,n="",i=[],o=[],a=()=>{i.length&&(r.push(...hg(i,n)),i=[],n="")},l=()=>{o.length&&(r.push(...mg(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),s?(a(),s=!1):(s=!0,n=c.trimStart().slice(3).trim());continue}if(s){i.push(c);continue}if(/^\s*\|.*\|\s*$/.test(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${y.border(K(Math.max(28,ue()-6)))}`);continue}let d=c.match(/^#\s+(.*)/),h=c.match(/^##\s+(.*)/),p=c.match(/^###\s+(.*)/);if(d){r.push(""),r.push(` ${y.strong(De(d[1]))}`),r.push(` ${y.border(K(Math.min(ye(d[1])+2,ue()-4)))}`);continue}if(h){r.push(""),r.push(` ${y.accent("\u25C6")} ${y.strong(De(h[1]))}`);continue}if(p){r.push(""),r.push(` ${y.secondary("\u25C7")} ${y.primary(De(p[1]))}`);continue}if(/^\s*>\s/.test(c)){let g=c.replace(/^\s*>\s?/,"");r.push(` ${y.border("\u258E")} ${y.secondary(De(g))}`);continue}let u=c.match(/^(\s*)([-*•]|\d+\.)\s+(.*)/);if(u){let g=u[1].length,x=/\d+\./.test(u[2])?y.accent(u[2]):y.accent("\u25B8"),b=De(u[3]),w=jl(b,g+5);r.push(" ".repeat(g+2)+x+" "+(w[0]?.trimStart()??""));for(let v=1;v<w.length;v++)r.push(" ".repeat(g+5)+w[v].trimStart());continue}r.push(...jl(De(c),2))}return l(),s&&a(),`
|
|
183
194
|
`+r.join(`
|
|
184
195
|
`)+`
|
|
185
|
-
`}function
|
|
186
|
-
`)}var
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
189
|
-
${y.accent("Hablas")} ${y.muted("v"+
|
|
190
|
-
`}function
|
|
191
|
-
`)}var
|
|
196
|
+
`}function we(t){return` ${y.success("\u2713")} ${y.primary(t)}`}function Fe(t){return` ${y.error("\u2717")} ${y.error(t)}`}function fe(t){return` ${y.warning("\u26A0")} ${y.warning(t)}`}function U(t){return` ${y.accent("\xB7")} ${y.secondary(t)}`}function Bl(){let t=Math.min(ue(),72),e=(r,s)=>` ${y.accent(kn(r,20))}${y.muted(s)}`;return["",` ${y.strong("Commands")}`,` ${y.border(K(t-4))}`,e("/help","show this help"),e("/status","runtime status \u2014 model, provider, tokens, tools"),e("/model [name]","show or switch active model"),e("/models [q]","list available models (optional search)"),e("/provider","inspect or switch provider"),e("/history","show recent conversation turns"),e("/clear","clear session history"),e("/workspace","inspect workspace files and git info"),e("/doctor","run diagnostics"),e("/version","show version"),e("/about","product identity and capabilities"),e("/exit","quit"),"",` ${y.strong("Memory")}`,` ${y.border(K(t-4))}`,e("/memory","show memory stats and recent entries"),e("/remember k v","store a persistent fact"),e("/forget k","delete a memory entry"),e("/memory-search q","search memory by keyword"),"",` ${y.strong("Session")}`,` ${y.border(K(t-4))}`,e("/compact","compress context history to free up token budget"),e("/plan","show current execution plan (if any)"),e("/save","save session checkpoint to ~/.hablas/sessions/"),"",` ${y.strong("Tips")}`,` ${y.border(K(t-4))}`,` ${y.muted("\xB7")} ${y.secondary("Ctrl+C cancels the current operation")}`,` ${y.muted("\xB7")} ${y.secondary("Ctrl+C twice exits")}`,` ${y.muted("\xB7")} ${y.secondary("Memory persists across sessions in ~/.hablas/")}`,` ${y.muted("\xB7")} ${y.secondary("Git tools work automatically in repos")}`,` ${y.muted("\xB7")} ${y.secondary("Use /compact when context feels slow or large")}`,""].join(`
|
|
197
|
+
`)}var Ll=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ye=class{label;timer=null;frame=0;active=!1;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!Ml||this.active||(this.active=!0,this.timer=setInterval(()=>{let e=Ll[this.frame%Ll.length];process.stdout.write(`\r ${y.accent(e)} ${y.secondary(this.label+"\u2026")} `),this.frame++},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=null),Ml&&process.stdout.write("\r\x1B[2K"))}};function Cn(t){if(!t.toolsUsed.length)return"";let e=[""],r=Math.min(ue(),72);e.push(` ${y.border(K(r-4))}`);let s=t.durationMs<1e3?`${t.durationMs}ms`:`${(t.durationMs/1e3).toFixed(1)}s`,n=[];if(n.push(y.muted(`${t.toolsUsed.length} ops`)),t.filesChanged.length&&n.push(y.success(`${t.filesChanged.length} files`)),t.commandsRun.length&&n.push(y.accent(`${t.commandsRun.length} cmds`)),t.errors.length&&n.push(y.error(`${t.errors.length} errors`)),n.push(y.muted(s)),e.push(` ${n.join(y.muted(" \xB7 "))}`),t.filesChanged.length){for(let i of t.filesChanged.slice(0,6))e.push(` ${y.muted(" ")}${y.success("~")} ${y.secondary(i)}`);t.filesChanged.length>6&&e.push(` ${y.muted(" \u2026 and "+(t.filesChanged.length-6)+" more")}`)}return e.push(` ${y.border(K(r-4))}`),e.join(`
|
|
198
|
+
`)}function Hl(t){let e=Math.min(ue(),72),r=(i,o)=>` ${y.secondary(i.padEnd(18))}${y.primary(o)}`,s=t.workingDir.replace($n.homedir(),"~"),n=["",` ${y.strong("Runtime status")}`,` ${y.border(K(e-4))}`,r("model",t.model),r("provider",t.provider),r("workspace",s),r("connection",t.connected?y.success("online"):y.warning("offline"))];return t.messageCount!==void 0&&n.push(r("messages",String(t.messageCount))),t.totalTokens!==void 0&&n.push(r("tokens used",String(t.totalTokens))),t.toolCount!==void 0&&n.push(r("tools",String(t.toolCount)+" registered")),t.autoMode!==void 0&&n.push(r("auto mode",t.autoMode?y.warning("on"):y.success("off"))),n.push(""),n.join(`
|
|
199
|
+
`)}function Wl(){return`
|
|
200
|
+
${y.accent("Hablas")} ${y.muted("v"+Tn)} ${y.secondary("\u2014 single-agent engineering runtime")}
|
|
201
|
+
`}function Vl(){let t=Math.min(ue(),72);return["",` ${y.strong("Hablas")} ${y.muted("v"+Tn)}`,` ${y.border(K(t-4))}`,` ${y.secondary("single-agent engineering runtime")}`,"",` ${y.muted("\xB7")} ${y.primary("File I/O")} read, write, patch, search, move, delete`,` ${y.muted("\xB7")} ${y.primary("Shell")} run commands, execute code, detect bugs`,` ${y.muted("\xB7")} ${y.primary("Web")} search, scrape, PDF, image intelligence`,` ${y.muted("\xB7")} ${y.primary("Memory")} persistent cross-session knowledge store`,` ${y.muted("\xB7")} ${y.primary("Git")} status, diff, log, branch \u2014 read-only`,` ${y.muted("\xB7")} ${y.primary("Planning")} automatic execution plans for complex tasks`,` ${y.muted("\xB7")} ${y.primary("Compression")} smart context compression for long sessions`,"",` ${y.muted("by Abdulmoin Hablas")}`,""].join(`
|
|
202
|
+
`)}var Pr=re.join(Gl.homedir(),".hablas","history"),Mr=500,gg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),yg=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],wg=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"]),zl=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],jr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Kl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Mr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{let n=s.trim();n&&(this.history.push(n),this.history=this.history.slice(-Mr),this.saveHistory()),r(s)})})}async confirm(e){return(await this.prompt(` ${y.warning("?")} ${e} ${y.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
192
203
|
${y.error("\u26A0")} ${e}`),console.log(` ${y.muted("Type yes to confirm this dangerous action.")}
|
|
193
|
-
`),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let
|
|
194
|
-
`).filter(Boolean).slice(-
|
|
195
|
-
`),"utf-8")}catch{}}};var
|
|
204
|
+
`),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let s=zl.filter(n=>n.startsWith(e));return[s.length?s:zl,e]}for(let s of yg)if(e.toLowerCase().includes(s)){let n=e.split(s).pop()??"";if(n&&!n.includes(" "))try{let i=re.dirname(n)||".",o=re.basename(n),a=re.resolve(this.workingDir,i),l=de.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(n))+re.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let s=r[1],n=this.getProjectFiles(),i=n.filter(o=>o.toLowerCase().startsWith(s.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:n.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,s,n,i=0){if(!(i>=n))try{let o=de.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||gg.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(re.join(e,a.name),l,s,n,i+1);else{let c=re.extname(a.name).toLowerCase();(wg.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{de.existsSync(Pr)&&(this.history=de.readFileSync(Pr,"utf-8").split(`
|
|
205
|
+
`).filter(Boolean).slice(-Mr))}catch{}}saveHistory(){try{let e=re.dirname(Pr);de.existsSync(e)||de.mkdirSync(e,{recursive:!0}),de.writeFileSync(Pr,this.history.slice(-Mr).join(`
|
|
206
|
+
`),"utf-8")}catch{}}};var bg={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},xg=`
|
|
196
207
|
## Reasoning Protocol
|
|
197
208
|
|
|
198
209
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -221,17 +232,17 @@ After receiving a tool result, think again:
|
|
|
221
232
|
- One tool call per turn. Wait for the result before the next call.
|
|
222
233
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
223
234
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
224
|
-
`.trim(),
|
|
235
|
+
`.trim(),Sg=`
|
|
225
236
|
## Reasoning
|
|
226
237
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
227
238
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
228
|
-
`.trim()
|
|
239
|
+
`.trim(),En=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...bg,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
|
|
229
240
|
|
|
230
|
-
${
|
|
241
|
+
${Sg}`:`${e}
|
|
231
242
|
|
|
232
|
-
${
|
|
243
|
+
${xg}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],s=e,n=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=n.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(r.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(r.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
|
|
233
244
|
|
|
234
|
-
`).trim(),visibleContent:
|
|
245
|
+
`).trim(),visibleContent:s.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let s=this.turnSteps[this.turnSteps.length-1];s&&(s.observation=e,r&&(s.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,s){return`
|
|
235
246
|
<self_eval>
|
|
236
247
|
You just completed this task: "${e}"
|
|
237
248
|
|
|
@@ -240,7 +251,7 @@ Your answer was:
|
|
|
240
251
|
${r.slice(0,1500)}
|
|
241
252
|
"""
|
|
242
253
|
|
|
243
|
-
Tools used: ${
|
|
254
|
+
Tools used: ${s.length>0?s.join(", "):"none"}
|
|
244
255
|
|
|
245
256
|
Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
246
257
|
{
|
|
@@ -251,46 +262,46 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
251
262
|
"confidence": "<high|medium|low>"
|
|
252
263
|
}
|
|
253
264
|
</self_eval>
|
|
254
|
-
`.trim()}parseSelfEval(e){let r=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let
|
|
255
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(
|
|
256
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function
|
|
265
|
+
`.trim()}parseSelfEval(e){let r=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let s of r){let n=e.match(s);if(n)try{let i=JSON.parse(n[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,s=typeof e.completed=="boolean"?e.completed:r>=7,n=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:s,rationale:n,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,r,s){return r?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${s.slice(0,300)}`,"</thinking>"].join(`
|
|
266
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(n=>n.action).length,s=this.turnSteps.filter(n=>n.reflection).length;return`${e} steps, ${r} actions, ${s} reflections`}};function Ut(t){return new En(t)}var vg=[{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}],An=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,s){let n=this.failures.get(e),i=n?n.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of vg)if(a.test(r)){let l=n?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let s=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
|
|
267
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function qt(t=3){return new An(t)}var Ce=k(require("fs")),Dr=k(require("path")),Jl=k(require("os")),Lr=Dr.join(Jl.homedir(),".hablas","model-formats.json");function _g(){try{if(Ce.existsSync(Lr))return JSON.parse(Ce.readFileSync(Lr,"utf-8"))}catch{}return{}}function kg(t){try{let e=Dr.dirname(Lr);Ce.existsSync(e)||Ce.mkdirSync(e,{recursive:!0}),Ce.writeFileSync(Lr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Yl(t,e){let r=0,s=!1,n=!1;for(let i=e;i<t.length;i++){let o=t[i];if(n){n=!1;continue}if(o==="\\"&&s){n=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function Bt(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function $g(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Tg(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=Bt(n);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function Cg(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim());if(n.parameters||n.name){let i=Bt(n);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function Eg(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;){let n=s[1],i=Xl(n);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function Xl(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch"];for(let s of r){let n=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=n.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]=$g(p)}let d=a.trim();d&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=d:s==="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)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Ag(t){return Xl(t)}function Og(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=Bt(n);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function Rg(t){let e=[],r=/\{\s*"function"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=Yl(t,s.index);if(n)try{let i=JSON.parse(n),o=Bt(i);o&&e.push({...o,format:"function_call",rawMatch:n})}catch{}}return e}function Ig(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=Yl(t,s.index);if(n)try{let i=JSON.parse(n),o=Bt(i);o&&e.push({...o,format:"json_object",rawMatch:n})}catch{}}return e}function Pg(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,n=!1;for(;(s=r.exec(t))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){n=!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:s[0]})}}if(!n&&/<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 On=[{format:"xml_tool_call_wrapper",parse:Eg},{format:"xml_prompt",parse:Ag},{format:"xml_tags",parse:Tg},{format:"xml_parameters",parse:Pg},{format:"hermes",parse:Cg},{format:"markdown_json",parse:Og},{format:"function_call",parse:Rg},{format:"json_object",parse:Ig}],In=class{registry;constructor(){this.registry=_g()}parse(e,r,s){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let n=e||"";if(!n.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=On.find(a=>a.format===i.format);if(o){let a=o.parse(n);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,n)}}}for(let{parse:i}of On){let o=i(n);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,n)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(n).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:s}of On)if(s(e).length>0)return r;return"unknown"}learnFormat(e,r){let s=this.registry[e];s&&s.format===r?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},kg(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,s]of Object.entries(this.registry))e[r]={format:s.format,successCount:s.successCount};return e}buildResult(e,r){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),n=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)n=n.replace(o.rawMatch,"");return n=n.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),n=n.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),n=this.sanitizeResidualToolMarkup(n),n=n.replace(/\n{3,}/g,`
|
|
257
268
|
|
|
258
|
-
`),{toolCalls:
|
|
269
|
+
`),{toolCalls:s,displayContent:n.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
|
|
259
270
|
|
|
260
|
-
`)}},Es=null;function Yl(){return Es||(Es=new As),Es}var Ng=600,Ug=2e3,qg=12e3,Xl=2;function Bg(t,e,r){let s=Yl().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Hg(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:["edit_file","patch_file","search_and_replace"].includes(t)&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):t==="remember"&&typeof e.key=="string"?`remember: ${String(e.key).slice(0,60)}`:t==="recall"&&typeof e.key=="string"?`recall: ${String(e.key).slice(0,60)}`:t==="search_memory"&&typeof e.query=="string"?`search memory: "${String(e.query).slice(0,50)}"`:t==="forget"&&typeof e.key=="string"?`forget: ${String(e.key).slice(0,60)}`:t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?`diff ${e.path}`:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?`log ${e.path}`:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Wg(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function Ql(t,e,r,n){let s=0,i=Date.now();for(;s<=Xl;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Xl)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,n.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function Os(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Nt(),m=t.errorRecovery??Ut(),p=u?[]:n.getOllamaTools(),f=r.getModel(),g=t.maxIterations??Ng,h=[],b=[],w=[],x=new Map,S="",E=0,_=!1;for(;E<g;){if(E++,c?.aborted)return{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:"Aborted",completedNaturally:_};let T=d.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let A;try{a.onModelStart?.(b.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),A=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(ee){a.onModelStop?.();let se=ee;if(se.name==="AbortError"||c?.aborted)return{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:"Aborted",completedNaturally:_};if(E<=1){a.onNotice?.(`Transient model error: ${se.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),E--;continue}return a.onError?.(se.message??"Model request failed"),{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!1,error:se.message,completedNaturally:_}}let k=A.message?.content||"",M=A.message?.tool_calls,B=d.parseThinking(k);B.hasThinking&&(d.recordStep({thought:B.thinking}),o.debug({thinking:B.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:F,displayContent:K}=Bg(M,k,f);if(K&&K.trim()&&(S=K,await a.onAssistantText?.(K,e)),F.length===0){s.addAssistantMessage(k,void 0,e.role),_=!0;break}s.addAssistantMessage(k,F,e.role);let J=F.length;for(let ee=0;ee<F.length;ee++){let se=F[ee];if(!se?.function?.name)continue;let P=se.function.name,D=se.function.arguments||{},Wt=n.getSafetyLevel(P)??"confirm";if(!n.get(P)){a.onNotice?.(`Unknown tool: ${P} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${P}". Available: ${n.getAll().map(X=>X.name).join(", ")}`);continue}if(await l(P,Wt,D)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}let Oc=Hg(P,D),St=P==="read_file"?JSON.stringify({path:D.path||"",start:D.start_line||"",end:D.end_line||""}):"";if(P==="read_file"&&St&&x.has(St)){let X=x.get(St)||"";s.addToolMessage(X),d.recordObservation(X.slice(0,300),"Reused cached file read");continue}h.push(P),typeof D.path=="string"&&w.push(D.path),typeof D.from=="string"&&w.push(D.from),typeof D.to=="string"&&w.push(D.to),a.onToolStart?.(P,Oc,D),a.onToolCall?.(),d.recordStep({thought:B.hasThinking?`Executing: ${P}`:"",action:P,actionInput:D});let Y=await Ql(n,P,D,o);a.onToolEnd?.(P,Y.success,Y.error||Y.output,Y.duration,D);let qe;if(Y.success)qe=Zl(P,Y.output),d.recordObservation(qe.slice(0,300)),b.push({tool:P,success:!0,summary:Y.output.slice(0,150)});else{let X=Y.error||"Unknown error",Ze=m.analyze(P,X,D);if(qe=m.buildRecoveryMessage(Ze,X),d.recordObservation(`FAILED: ${X}`,`Recovery: ${Ze.strategy} \u2014 ${Ze.suggestion}`),o.info({tool:P,errorClass:Ze.errorClass,strategy:Ze.strategy},"Error recovery analysis"),b.push({tool:P,success:!1,summary:X.slice(0,150)}),Ze.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let et=await Ql(n,P,D,o);a.onToolEnd?.(P,et.success,et.output,et.duration,D),et.success&&(qe=Zl(P,et.output),d.recordObservation(qe.slice(0,300),"Auto-retry succeeded"),b[b.length-1]={tool:P,success:!0,summary:et.output.slice(0,150)})}}if(s.addToolMessage(qe),Y.success&&P==="read_file"&&typeof D.path=="string"&&(i?.addFile(D.path,Y.output),St&&x.set(St,qe)),Y.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(P)&&typeof D.path=="string")for(let X of[...x.keys()])X.includes(`"path":"${String(D.path).replace(/\"/g,'\\"')}"`)&&x.delete(X);if(Y.success&&P==="move_file")for(let X of[...x.keys()])(D.from&&X.includes(`"path":"${String(D.from).replace(/\"/g,'\\"')}"`)||D.to&&X.includes(`"path":"${String(D.to).replace(/\"/g,'\\"')}"`))&&x.delete(X);if(o.info({tool:P,success:Y.success,durationMs:Y.duration,retries:Y.retries},"Tool executed"),!Y.success&&Wg(Y.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}J>1&&ee<J-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return E>=g&&!_&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:Ue(h),toolResults:b,touchedFiles:Ue(w),iterations:E,success:!0,completedNaturally:_}}function Ue(t){return[...new Set(t)]}function Zl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?jt(e,qg):jt(e,Ug)}function ec(t){return async(e,r)=>{let n=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm(`Proceed with ${n}?`)?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${n}`)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}var tc={kind:"understand",goal:"Understand the current codebase structure and relevant files",toolHints:["list_dir","read_file","search_codebase","git_status"],successCriteria:"Key files identified, architecture understood, no blind spots remain"},Vg={kind:"research",goal:"Research APIs, patterns, or documentation needed for this task",toolHints:["web_search","scrape_url"],successCriteria:"Needed documentation found, approach confirmed"},Kg={kind:"verify",goal:"Build, test, and lint the changes to confirm correctness",toolHints:["run_command","detect_bugs"],successCriteria:"Build passes, no new errors introduced"},zg={kind:"report",goal:"Deliver a clear, honest summary of what was done",toolHints:[],successCriteria:"User has a full picture of changes, verification results, and next steps"},Gg=0;function Jg(){return`step_${Date.now()}_${++Gg}`}function Ee(t,e,r={}){return{id:Jg(),stepNum:t,status:"pending",...e,...r}}function rc(t,e){let r=[],n=1,s=t.complexity==="epic",i=t.complexity==="complex"||s,o=/\b(api|sdk|library|package|npm|docs|documentation|latest|version)\b/i.test(e),a=/\b(build|compile|test|lint|run|verify|check|typecheck)\b/i.test(e)||i,l=t.kind==="implementation",c=t.continuity;if(l&&!c?r.push(Ee(n++,tc)):c&&r.push(Ee(n++,tc,{goal:"Review current state \u2014 what exists, what changed, what remains",toolHints:["git_status","git_diff","read_file","list_dir"]})),o&&r.push(Ee(n++,Vg)),i&&r.push(Ee(n++,{kind:"understand",goal:"Check memory for relevant past decisions and patterns",toolHints:["search_memory"],successCriteria:"Any relevant past context loaded and applied"})),s&&r.push(Ee(n++,{kind:"plan_detail",goal:"Break the implementation into logical file-level tasks before writing any code",toolHints:["list_dir","read_file"],successCriteria:"Clear file-by-file implementation sequence established"})),l){let u=s?"Execute file changes in planned order \u2014 one file at a time, verify each before moving on":"Implement the requested changes in the correct files";r.push(Ee(n++,{kind:"implement",goal:u,toolHints:["read_file","write_file","edit_file","patch_file","search_and_replace","run_command"],successCriteria:"All target files modified correctly with no syntax errors"}))}return(a||i)&&r.push(Ee(n++,Kg)),i&&r.push(Ee(n++,{kind:"commit",goal:"Store key architectural decisions in memory for future sessions",toolHints:["remember"],successCriteria:"Decision stored with a clear, searchable key"})),r.push(Ee(n++,zg)),{id:`plan_${Date.now()}`,intent:t.intent,complexity:t.complexity,steps:r,createdAt:Date.now(),activeStepIndex:0,totalSteps:r.length}}function nc(t){let e=t.steps.filter(s=>s.status==="pending"||s.status==="active"),r=t.steps.filter(s=>s.status==="done"),n=["\u2550\u2550\u2550 EXECUTION PLAN \u2550\u2550\u2550",`Complexity: ${t.complexity} \xB7 Goal: ${t.intent}`,`Progress: ${r.length}/${t.totalSteps} steps complete`,"","Remaining steps (execute in order):"];for(let s of e.slice(0,5)){let i=s.toolHints.length?` [${s.toolHints.slice(0,3).join(", ")}]`:"";n.push(` ${s.stepNum}. [${s.kind.toUpperCase()}] ${s.goal}${i}`),n.push(` \u2713 Done when: ${s.successCriteria}`)}if(e.length>5&&n.push(` \u2026 ${e.length-5} more steps after these`),r.length){n.push(""),n.push("Completed:");for(let s of r)n.push(` \u2713 ${s.stepNum}. ${s.goal}${s.notes?" \u2014 "+s.notes:""}`)}return n.push(""),n.push("RULE: Complete each step before moving to the next. Do not skip verification."),n.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),n.join(`
|
|
261
|
-
`)}function
|
|
262
|
-
`).length}function
|
|
271
|
+
`)}},Rn=null;function Ql(){return Rn||(Rn=new In),Rn}var Mg=600,jg=2e3,Lg=12e3,Zl=2;function Dg(t,e,r){let n=Ql().parse(e,t,r);return{toolCalls:n.toolCalls,displayContent:n.displayContent}}function Fg(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:["edit_file","patch_file","search_and_replace"].includes(t)&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):t==="remember"&&typeof e.key=="string"?`remember: ${String(e.key).slice(0,60)}`:t==="recall"&&typeof e.key=="string"?`recall: ${String(e.key).slice(0,60)}`:t==="search_memory"&&typeof e.query=="string"?`search memory: "${String(e.query).slice(0,50)}"`:t==="forget"&&typeof e.key=="string"?`forget: ${String(e.key).slice(0,60)}`:t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?`diff ${e.path}`:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?`log ${e.path}`:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Ng(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 ec(t,e,r,s){let n=0,i=Date.now();for(;n<=Zl;){let o=await t.execute({name:e,arguments:r});if(o.success||n>=Zl)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:n};n++,s.info({tool:e,retry:n,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:n}}async function Pn(t){let{identity:e,client:r,registry:s,session:n,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:f}=t,d=t.reactEngine??Ut(),h=t.errorRecovery??qt(),p=f?[]:s.getOllamaTools(),u=r.getModel(),g=t.maxIterations??Mg,m=[],x=[],b=[],w=new Map,v="",_=0,C=!1;for(;_<g;){if(_++,c?.aborted)return{output:v,toolsUsed:Ne(m),toolResults:x,touchedFiles:Ne(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let E=d.buildBudgetWarningPrompt();E&&n.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let A;try{a.onModelStart?.(x.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),A=await r.chatWithTools(n.getMessages(),p,c),a.onModelStop?.()}catch(ee){a.onModelStop?.();let ne=ee;if(ne.name==="AbortError"||c?.aborted)return{output:v,toolsUsed:Ne(m),toolResults:x,touchedFiles:Ne(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){a.onNotice?.(`Transient model error: ${ne.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(j=>setTimeout(j,1e3)),_--;continue}return a.onError?.(ne.message??"Model request failed"),{output:v,toolsUsed:Ne(m),toolResults:x,touchedFiles:Ne(b),iterations:_,success:!1,error:ne.message,completedNaturally:C}}let T=A.message?.content||"",P=A.message?.tool_calls,N=d.parseThinking(T);N.hasThinking&&(d.recordStep({thought:N.thinking}),o.debug({thinking:N.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:D,displayContent:W}=Dg(P,T,u);if(W&&W.trim()&&(v=W,await a.onAssistantText?.(W,e)),D.length===0){n.addAssistantMessage(T,void 0,e.role),C=!0;break}n.addAssistantMessage(T,D,e.role);let J=D.length;for(let ee=0;ee<D.length;ee++){let ne=D[ee];if(!ne?.function?.name)continue;let j=ne.function.name,F=ne.function.arguments||{},Vt=s.getSafetyLevel(j)??"confirm";if(!s.get(j)){a.onNotice?.(`Unknown tool: ${j} \u2014 skipping`,"warn"),n.addToolMessage(`Error: Unknown tool "${j}". Available: ${s.getAll().map(X=>X.name).join(", ")}`);continue}if(await l(j,Vt,F)==="skip"){n.addToolMessage(`Tool ${j} was skipped by policy/user.`);break}let Rc=Fg(j,F),_t=j==="read_file"?JSON.stringify({path:F.path||"",start:F.start_line||"",end:F.end_line||""}):"";if(j==="read_file"&&_t&&w.has(_t)){let X=w.get(_t)||"";n.addToolMessage(X),d.recordObservation(X.slice(0,300),"Reused cached file read");continue}m.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,Rc,F),a.onToolCall?.(),d.recordStep({thought:N.hasThinking?`Executing: ${j}`:"",action:j,actionInput:F});let Y=await ec(s,j,F,o);a.onToolEnd?.(j,Y.success,Y.error||Y.output,Y.duration,F);let Ue;if(Y.success)Ue=tc(j,Y.output),d.recordObservation(Ue.slice(0,300)),x.push({tool:j,success:!0,summary:Y.output.slice(0,150)});else{let X=Y.error||"Unknown error",Qe=h.analyze(j,X,F);if(Ue=h.buildRecoveryMessage(Qe,X),d.recordObservation(`FAILED: ${X}`,`Recovery: ${Qe.strategy} \u2014 ${Qe.suggestion}`),o.info({tool:j,errorClass:Qe.errorClass,strategy:Qe.strategy},"Error recovery analysis"),x.push({tool:j,success:!1,summary:X.slice(0,150)}),Qe.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Ze=await ec(s,j,F,o);a.onToolEnd?.(j,Ze.success,Ze.output,Ze.duration,F),Ze.success&&(Ue=tc(j,Ze.output),d.recordObservation(Ue.slice(0,300),"Auto-retry succeeded"),x[x.length-1]={tool:j,success:!0,summary:Ze.output.slice(0,150)})}}if(n.addToolMessage(Ue),Y.success&&j==="read_file"&&typeof F.path=="string"&&(i?.addFile(F.path,Y.output),_t&&w.set(_t,Ue)),Y.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(j)&&typeof F.path=="string")for(let X of[...w.keys()])X.includes(`"path":"${String(F.path).replace(/\"/g,'\\"')}"`)&&w.delete(X);if(Y.success&&j==="move_file")for(let X of[...w.keys()])(F.from&&X.includes(`"path":"${String(F.from).replace(/\"/g,'\\"')}"`)||F.to&&X.includes(`"path":"${String(F.to).replace(/\"/g,'\\"')}"`))&&w.delete(X);if(o.info({tool:j,success:Y.success,durationMs:Y.duration,retries:Y.retries},"Tool executed"),!Y.success&&Ng(Y.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}J>1&&ee<J-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return _>=g&&!C&&a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Ne(m),toolResults:x,touchedFiles:Ne(b),iterations:_,success:!0,completedNaturally:C}}function Ne(t){return[...new Set(t)]}function tc(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?jt(e,Lg):jt(e,jg)}function rc(t){return async(e,r)=>{let s=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm(`Proceed with ${s}?`)?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${s}`)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}var sc={kind:"understand",goal:"Understand the current codebase structure and relevant files",toolHints:["list_dir","read_file","search_codebase","git_status"],successCriteria:"Key files identified, architecture understood, no blind spots remain"},Ug={kind:"research",goal:"Research APIs, patterns, or documentation needed for this task",toolHints:["web_search","scrape_url"],successCriteria:"Needed documentation found, approach confirmed"},qg={kind:"verify",goal:"Build, test, and lint the changes to confirm correctness",toolHints:["run_command","detect_bugs"],successCriteria:"Build passes, no new errors introduced"},Bg={kind:"report",goal:"Deliver a clear, honest summary of what was done",toolHints:[],successCriteria:"User has a full picture of changes, verification results, and next steps"},Hg=0;function Wg(){return`step_${Date.now()}_${++Hg}`}function Ee(t,e,r={}){return{id:Wg(),stepNum:t,status:"pending",...e,...r}}function nc(t,e){let r=[],s=1,n=t.complexity==="epic",i=t.complexity==="complex"||n,o=/\b(api|sdk|library|package|npm|docs|documentation|latest|version)\b/i.test(e),a=/\b(build|compile|test|lint|run|verify|check|typecheck)\b/i.test(e)||i,l=t.kind==="implementation",c=t.continuity;if(l&&!c?r.push(Ee(s++,sc)):c&&r.push(Ee(s++,sc,{goal:"Review current state \u2014 what exists, what changed, what remains",toolHints:["git_status","git_diff","read_file","list_dir"]})),o&&r.push(Ee(s++,Ug)),i&&r.push(Ee(s++,{kind:"understand",goal:"Check memory for relevant past decisions and patterns",toolHints:["search_memory"],successCriteria:"Any relevant past context loaded and applied"})),n&&r.push(Ee(s++,{kind:"plan_detail",goal:"Break the implementation into logical file-level tasks before writing any code",toolHints:["list_dir","read_file"],successCriteria:"Clear file-by-file implementation sequence established"})),l){let f=n?"Execute file changes in planned order \u2014 one file at a time, verify each before moving on":"Implement the requested changes in the correct files";r.push(Ee(s++,{kind:"implement",goal:f,toolHints:["read_file","write_file","edit_file","patch_file","search_and_replace","run_command"],successCriteria:"All target files modified correctly with no syntax errors"}))}return(a||i)&&r.push(Ee(s++,qg)),i&&r.push(Ee(s++,{kind:"commit",goal:"Store key architectural decisions in memory for future sessions",toolHints:["remember"],successCriteria:"Decision stored with a clear, searchable key"})),r.push(Ee(s++,Bg)),{id:`plan_${Date.now()}`,intent:t.intent,complexity:t.complexity,steps:r,createdAt:Date.now(),activeStepIndex:0,totalSteps:r.length}}function ic(t){let e=t.steps.filter(n=>n.status==="pending"||n.status==="active"),r=t.steps.filter(n=>n.status==="done"),s=["\u2550\u2550\u2550 EXECUTION PLAN \u2550\u2550\u2550",`Complexity: ${t.complexity} \xB7 Goal: ${t.intent}`,`Progress: ${r.length}/${t.totalSteps} steps complete`,"","Remaining steps (execute in order):"];for(let n of e.slice(0,5)){let i=n.toolHints.length?` [${n.toolHints.slice(0,3).join(", ")}]`:"";s.push(` ${n.stepNum}. [${n.kind.toUpperCase()}] ${n.goal}${i}`),s.push(` \u2713 Done when: ${n.successCriteria}`)}if(e.length>5&&s.push(` \u2026 ${e.length-5} more steps after these`),r.length){s.push(""),s.push("Completed:");for(let n of r)s.push(` \u2713 ${n.stepNum}. ${n.goal}${n.notes?" \u2014 "+n.notes:""}`)}return s.push(""),s.push("RULE: Complete each step before moving to the next. Do not skip verification."),s.push("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"),s.join(`
|
|
272
|
+
`)}function oc(t,e){let r=new Set(e);for(let n of t.steps){if(n.status!=="pending"&&n.status!=="active")continue;let i=new Set(n.toolHints);e.filter(a=>i.has(a)).length>0&&(n.status="active",(n.kind==="understand"&&(r.has("list_dir")||r.has("read_file")||r.has("git_status"))||n.kind==="research"&&r.has("web_search")||n.kind==="implement"&&(r.has("write_file")||r.has("edit_file")||r.has("patch_file")||r.has("search_and_replace"))||n.kind==="verify"&&r.has("run_command")||n.kind==="commit"&&r.has("remember")||n.kind==="plan_detail"&&(r.has("read_file")||r.has("list_dir"))||n.kind==="report")&&(n.status="done"))}let s=t.steps.findIndex(n=>n.status==="pending");t.activeStepIndex=s===-1?t.steps.length:s,t.steps.every(n=>n.status==="done"||n.status==="skipped")&&(t.completedAt=Date.now())}function Mn(t){let e=t.steps.filter(r=>r.status==="done"||r.status==="skipped").length;return{done:e,total:t.totalSteps,pct:Math.round(e/t.totalSteps*100)}}function jn(t){return t.split(`
|
|
273
|
+
`).length}function ac(t,e){return t.split(`
|
|
263
274
|
`).slice(-e).join(`
|
|
264
|
-
`)}function
|
|
275
|
+
`)}function lc(t,e){return t.split(`
|
|
265
276
|
`).slice(0,e).join(`
|
|
266
|
-
`)}function
|
|
267
|
-
`).filter(Boolean);if(r.length<=20)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let
|
|
268
|
-
`);if(r.length<=15)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let
|
|
277
|
+
`)}function Vg(t,e){let r=jn(t);if(r<=30)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let s=String(e.path??""),i=(t.match(/^export\s+(const|function|class|interface|type|enum)\s+(\w+)/gm)??[]).map(l=>l.split(/\s+/).pop()).filter(Boolean).slice(0,8),o=i.length?` \u2014 exports: ${i.join(", ")}`:"",a=`[file read: ${s} (${r} lines)${o}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"file_read"}}function zg(t,e){let r=t.split(`
|
|
278
|
+
`).filter(Boolean);if(r.length<=20)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let s=String(e.path??"."),n=r.filter(l=>!l.endsWith("/")).length,i=r.filter(l=>l.endsWith("/")).length,o=r.slice(0,5).join(", "),a=`[list_dir: ${s} \u2014 ${n} files, ${i} dirs. Sample: ${o}${r.length>5?", \u2026":""}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"list_dir"}}function Kg(t,e){let r=t.split(`
|
|
279
|
+
`);if(r.length<=15)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let s=String(e.command??"").slice(0,60),n=ac(t,8),i=`[run_command: ${s}
|
|
269
280
|
\u2026 (${r.length} lines total, showing last 8):
|
|
270
|
-
${
|
|
281
|
+
${n}]`;return{original:t,compressed:i,savedChars:t.length-i.length,strategy:"run_command"}}function Gg(t){if(t.length<=1e3)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=t.match(/https?:\/\/[^\s"')>]+/g)??[],r=[...new Set(e)].slice(0,5),n=`[web_search results:
|
|
271
282
|
Titles: ${t.split(`
|
|
272
283
|
`).filter(i=>i.trim().length>10&&i.trim().length<100&&!i.startsWith("http")).slice(0,5).join(" | ")}
|
|
273
284
|
URLs: ${r.join(`
|
|
274
|
-
`)}]`;return{original:t,compressed:
|
|
275
|
-
`);if(e.length<=40)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let r=e.filter(a=>a.startsWith("+++")||a.startsWith("---")||a.startsWith("diff --git")),
|
|
276
|
-
\u2026`:"");return{original:t,compressed:e,savedChars:t.length-e.length,strategy:"git_log"}}function
|
|
277
|
-
\u2026 (compressed \u2014 ${
|
|
278
|
-
${
|
|
285
|
+
`)}]`;return{original:t,compressed:n,savedChars:t.length-n.length,strategy:"web_search"}}function Jg(t){let e=t.split(`
|
|
286
|
+
`);if(e.length<=40)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let r=e.filter(a=>a.startsWith("+++")||a.startsWith("---")||a.startsWith("diff --git")),s=[...new Set(r.map(a=>a.split(" ").pop()).filter(Boolean))].slice(0,8),n=e.filter(a=>a.startsWith("+")&&!a.startsWith("+++")).length,i=e.filter(a=>a.startsWith("-")&&!a.startsWith("---")).length,o=`[git_diff: ${s.join(", ")} \u2014 +${n} -${i} lines (${e.length} total diff lines)]`;return{original:t,compressed:o,savedChars:t.length-o.length,strategy:"git_diff"}}function Yg(t){if(t.length<=500)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=lc(t,10)+(jn(t)>10?`
|
|
287
|
+
\u2026`:"");return{original:t,compressed:e,savedChars:t.length-e.length,strategy:"git_log"}}function cc(t,e,r={}){if(e.length<400)return{original:e,compressed:e,savedChars:0,strategy:"passthrough"};switch(t){case"read_file":return Vg(e,r);case"list_dir":return zg(e,r);case"run_command":return Kg(e,r);case"web_search":return Gg(e);case"git_diff":return Jg(e);case"git_log":return Yg(e);default:if(e.length>2e3){let s=lc(e,10),n=ac(e,5),i=`${s}
|
|
288
|
+
\u2026 (compressed \u2014 ${jn(e)} lines) \u2026
|
|
289
|
+
${n}`;return{original:e,compressed:i,savedChars:e.length-i.length,strategy:"generic_trim"}}return{original:e,compressed:e,savedChars:0,strategy:"passthrough"}}}async function uc(t){let{client:e,session:r,abortSignal:s,onStart:n,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",n?.();for await(let f of e.streamChat(r.getMessages(),s))a+=f,i?.(f);return r.addAssistantMessage(a||""),o?.(),a}catch(f){if(l=f,f?.name==="AbortError"||s?.aborted)throw f;if(c===1)break}throw l||new Error("Text turn failed")}function Xg(t){return["list_dir","read_file","get_file_info"].includes(t)?"Reading project":["search_codebase"].includes(t)?"Searching codebase":["web_search"].includes(t)?"Searching the web":["scrape_url","extract_links"].includes(t)?"Fetching web content":["search_image_candidates","inspect_image"].includes(t)?"Analyzing images":["download_asset"].includes(t)?"Downloading asset":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing files":["run_command","execute_code","detect_bugs"].includes(t)?"Running commands":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Accessing memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Reading git":["read_pdf","pdf_metadata"].includes(t)?"Reading document":"Working"}function fc(t,e){let r=[],s=[],n=[];for(let i of t){if(["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file","move_file"].includes(i.tool)){let o=i.summary.replace(/^(create|modify|delete|move)\s+/,"");r.includes(o)||r.push(o)}["run_command","execute_code"].includes(i.tool)&&s.push(i.summary.slice(0,60)),i.success||n.push(`${i.tool}: ${i.summary.slice(0,80)}`)}return{toolsUsed:[...new Set(t.map(i=>i.tool))],filesChanged:r,commandsRun:s,durationMs:e,errors:n}}async function Fr(t,e){let s=Rl(t).profile,n=Date.now(),i=await wt(e.workingDir,e.config),o=bt(i,s,e.workingDir);if((s.complexity==="complex"||s.complexity==="epic")&&s.needsTools)try{let x=z().search(s.intent,{limit:5});if(x.length>0){let b=x.map(w=>` - [${w.entry.key}] ${w.entry.value}`).join(`
|
|
279
290
|
`);o+=`
|
|
280
291
|
|
|
281
292
|
\u2550\u2550\u2550 RELEVANT MEMORY \u2550\u2550\u2550
|
|
282
293
|
Past decisions and preferences:
|
|
283
|
-
${
|
|
284
|
-
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`}}catch{}let a=null;if(
|
|
294
|
+
${b}
|
|
295
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`}}catch{}let a=null;if(s.needsTools&&(s.complexity==="complex"||s.complexity==="epic")&&s.kind==="implementation"){a=nc(s,t);let m=ic(a);o+=`
|
|
285
296
|
|
|
286
|
-
${
|
|
287
|
-
`)}});
|
|
288
|
-
${y.success("\u2713")} ${y.muted(`Plan: ${
|
|
289
|
-
`)}async function dc(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ul());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Hl());return;case"/version":console.log(Bl());return;case"/clear":e.session.clear(),console.log(Te("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(W("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(ql({model:e.client.getModel(),provider:Ge(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(W(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),st(e.config),console.log(Te(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let f=s[s.length-1],g=parseInt(f,10);!Number.isNaN(g)&&g>0?(a=g,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(f=>f.toLowerCase().includes(l)):i;if(c.length===0){console.log(fe("No matching models found."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),m=(d-1)*o,p=c.slice(m,m+o);console.log(""),console.log(W(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${u}`)),console.log(""),p.forEach((f,g)=>{let h=f===e.client.getModel();console.log(` ${String(m+g+1).padStart(2," ")}. ${f}${h?" * active":""}`)}),console.log(""),u>1&&console.log(W(`Use /models ${l?l+" ":""}${d<u?d+1:u} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(W(`Provider: ${Ge(e.config)}`)),console.log(W(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Te("Connection OK"):Ne("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=oe.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=oe.defaultModel);else if(i==="custom"){if(!s[1]){console.log(fe("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(fe("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=lt(e.config);e.setClient(o),st(e.config),console.log(Te(`Provider switched to ${Ge(e.config)}`));return}case"/doctor":{let i=await Lr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Dr(i));return}case"/workspace":{console.log(""),console.log(Cr(gt(e.workingDir))),console.log("");return}case"/memory":{let i=V().getStats(),o=V().getRecent(5);console.log(""),console.log(W(`Persistent memory \u2014 ${i.total??0} total entries`));let a=Object.entries(i).filter(([l])=>l!=="total");if(a.length>0)for(let[l,c]of a)console.log(W(` ${l}: ${c}`));if(o.length>0){console.log(W("Recent:"));for(let l of o)console.log(W(` \xB7 [${l.kind}] ${l.key.slice(0,60)}`))}console.log("");return}case"/remember":{if(s.length<2){console.log(fe("Usage: /remember <key> <value>"));return}let i=s[0],o=s.slice(1).join(" ");V().remember({kind:"preference",key:`manual:${i}`,value:o,tags:["manual"],priority:"high"}),V().flush(),console.log(Te(`Remembered: ${i} = ${o.slice(0,60)}`));return}case"/forget":{if(s.length===0){console.log(fe("Usage: /forget <key>"));return}let i=s.join(" "),o=V().forget(i)||V().forget(`manual:${i}`);V().flush(),console.log(o?Te(`Forgotten: ${i}`):fe(`No memory found for: ${i}`));return}case"/memory-search":{if(s.length===0){console.log(fe("Usage: /memory-search <query>"));return}let i=s.join(" "),o=V().search(i,{limit:8});if(o.length===0){console.log(W("No memories found."));return}console.log(W(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(W(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(W(` ${a.entry.value.replace(/\n/g," \u2014 ").slice(0,120)}`));return}default:console.log(fe(`Unknown command: ${n}`))}}var Ae=C(require("fs")),js=C(require("path"));function Ps(t){let e=js.join(t,".hablas");return Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0}),e}function pc(t){return js.join(Ps(t),"session.json")}function Fr(t,e){let r=pc(t);try{return Ae.existsSync(r)?(e.fromJSON(Ae.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Bt(t,e){let r=pc(t);try{Ae.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function gc(t,e){ei();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=lt(t);Ps(r);let s=new dt(r,t),i=new pt(t),o=await wt(r,t),a=new ht(bt(o,xs("hello"),r),t.historySize,t.contextBudget);Fr(r,a);let l=new Ir(r);console.log(Pl(t.model,r));let c=new Xe("Connecting");c.start();let u=await n.checkConnection();if(c.stop(),u){let h=await n.listModels();console.log(Te(`online \xB7 ${Ge(t)} \xB7 ${h.length} models available`))}else console.log(fe(`offline \xB7 ${Ge(t)} \xB7 you can still inspect local files and switch provider with /provider`));mc.existsSync(hc.join(r,".git"))||console.log(W("workspace mode: standalone (no git repository detected)")),console.log(W("Hablas is ready.")),console.log("");let d=0,m=0,p=Date.now(),f=new AbortController,g=0;for(process.on("SIGINT",()=>{let h=Date.now();h-g<1500&&(console.log(""),console.log(W(`Session summary \xB7 turns=${d} \xB7 toolCalls=${m} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),g=h,f.abort(),f=new AbortController,console.log(""),console.log(fe("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){let w=await dc(b,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r});if(Bt(r,a),w==="quit")break;continue}d+=1,console.log(Ll(d)),f=new AbortController;try{await Pr(b,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{m+=1}}),Bt(r,a)}catch(w){if(w?.name==="AbortError")continue;console.log(Ne(w?.message||"Turn failed")),e.error(w,"interactive turn failed")}}}Sl(),l.close()}var ny=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,sy=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,iy=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,oy=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,ay=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,ly=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,cy=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,uy=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,yc=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function wc(t){let e=t.trim(),r=e.toLowerCase(),n=sy.test(r),s=iy.test(r),i=oy.test(r)||ay.test(r),o=ly.test(r),a=cy.test(r),l=i||n||s||o&&e.length>18&&!yc.test(r)&&!a,c=a&&!i&&!n&&!s,u=uy.test(r)||o,d=!l&&!c&&(yc.test(r)||e.endsWith("?"));return ny.test(e)&&!u&&!l&&!c?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function bc(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=lt(e),i=new dt(n,e),o=new pt(e),a=await wt(n,e),l=new ht(bt(a,wc(t)),e.historySize,e.contextBudget);Fr(n,l),await Pr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Bt(n,l)}var Nr=C(require("fs")),Qe=C(require("path")),fy=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],dy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),py=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function my(t,e){let r=[],n=e.split(`
|
|
290
|
-
`);for(let{pattern:
|
|
291
|
-
`).length,
|
|
292
|
-
`),
|
|
293
|
-
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((n
|
|
294
|
-
`)}var vt=
|
|
295
|
-
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((
|
|
296
|
-
`)}var
|
|
297
|
+
${m}`;let x=Mn(a);console.log(` ${y.accent("\u25C9")} ${y.secondary("Execution plan ready")} ${y.muted(`\xB7 ${x.total} steps \xB7 complexity: ${s.complexity}`)}`)}if(e.session.updateSystemPrompt(o),s.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),s.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:${s.kind}`]}),!s.needsTools){let m=new Ye("Thinking"),x=!1;m.start();try{let b=await uc({client:e.client,session:e.session,onStart:()=>m.start(),onChunk:w=>{x||(m.stop(),console.log(xt()),process.stdout.write(" "),x=!0),process.stdout.write(w)},onComplete:()=>{x&&process.stdout.write(`
|
|
298
|
+
`)}});x||(m.stop(),console.log(xt()),console.log(Nt(b)))}catch(b){m.stop(),console.log(Fe(b?.message||"Text turn failed"))}return}let l=Ut({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),c=qt(3),f=[],d=new Ye("Thinking"),h="",p={onModelStart:m=>{d.stop(),d.setLabel(m),d.start()},onModelStop:()=>d.stop(),onAssistantText:async m=>{f.push(m),s.kind!=="implementation"&&(console.log(xt()),console.log(Nt(m)))},onToolStart:(m,x)=>{d.stop();let b=Xg(m);b!==h&&(console.log(Nl(b)),h=b),console.log(Ul(m,x))},onToolEnd:(m,x,b,w)=>{let v=cc(m,b),_=v.savedChars>200?v.compressed:b;console.log(ql(x,_,w))},onNotice:(m,x)=>{console.log(x==="retry"?U(`Retrying: ${m}`):U(m))},onError:m=>console.log(Fe(m)),onToolCall:()=>e.onToolCall?.()},u=rc({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?m=>e.input.confirm(m):void 0,confirmDangerous:e.input?m=>e.input.confirmDangerous(m):void 0}),g=await Pn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:p,safetyPolicy:u,reactEngine:l,errorRecovery:c,skipTools:!1});if(a){oc(a,g.toolsUsed);let m=Mn(a);m.done>0&&console.log(`
|
|
299
|
+
${y.success("\u2713")} ${y.muted(`Plan: ${m.done}/${m.total} steps complete`)}`)}if(s.kind==="implementation"&&g.toolsUsed.length>0&&f.length>0&&(console.log(xt()),console.log(Nt(f[f.length-1]))),g.toolsUsed.length>0){let m=Date.now()-n,x=fc(g.toolResults,m),b=Cn(x);b&&console.log(b)}try{z().flush()}catch{}if(s.kind==="implementation"&&g.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools and modify actual files. Retry now.",{priority:"critical",tags:["system-correction","force-tools"]});let m=[],x=await Pn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...p,onAssistantText:async b=>{m.push(b)}},safetyPolicy:u,reactEngine:Ut({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:qt(3),skipTools:!1});if(x.toolsUsed.length===0)console.log(Fe("Implementation request failed to enter a tool-execution path."));else if(m.length>0){console.log(xt()),console.log(Nt(m[m.length-1]));let b=fc(x.toolResults,Date.now()-n),w=Cn(b);w&&console.log(w)}}}var Ln=k(require("fs")),dc=k(require("path")),be=k(require("os")),pc=require("child_process");async function Nr(t){let e=[],r=process.version,s=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${r} (recommended)`:s>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let n=dc.join(be.homedir(),".hablas");if(e.push({name:"Config directory",status:Ln.existsSync(n)?"ok":"warn",message:Ln.existsSync(n)?n:"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=be.homedir();if(process.platform!=="win32"){let a=(0,pc.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:`${be.platform()} ${be.arch()} \u2014 ${be.cpus().length} cores, ${Math.round(be.totalmem()/1024/1024/1024)}GB RAM`}),e}function Ur(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",n="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let c=`${r[l.status]}${e[l.status]}${s}`,f=l.name.padEnd(18);i.push(` ${c} ${f}${n}${l.message}${s}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
|
|
300
|
+
`)}async function hc(t,e){let r=t.trim().split(/\s+/),s=r[0],n=r.slice(1);switch(s){case"/help":console.log(Bl());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Vl());return;case"/version":console.log(Wl());return;case"/clear":e.session.clear(),console.log(we("Session cleared."));return;case"/history":{let i=parseInt(n[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(U("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(Hl({model:e.client.getModel(),provider:Ke(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(n.length===0){console.log(U(`Current model: ${e.client.getModel()}`));return}let i=n.join(" ");e.config.model=i,e.client.setModel(i),st(e.config),console.log(we(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(n.length>0){let u=n[n.length-1],g=parseInt(u,10);!Number.isNaN(g)&&g>0?(a=g,l=n.slice(0,-1).join(" ").toLowerCase().trim()):l=n.join(" ").toLowerCase().trim()}let c=l?i.filter(u=>u.toLowerCase().includes(l)):i;if(c.length===0){console.log(fe("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(U(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${f}`)),console.log(""),p.forEach((u,g)=>{let m=u===e.client.getModel();console.log(` ${String(h+g+1).padStart(2," ")}. ${u}${m?" * active":""}`)}),console.log(""),f>1&&console.log(U(`Use /models ${l?l+" ":""}${d<f?d+1:f} for next page.`)),console.log("");return}case"/provider":{let i=n[0];if(!i){console.log(U(`Provider: ${Ke(e.config)}`)),console.log(U(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?we("Connection OK"):Fe("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=oe.apiUrl,n[1]&&(e.config.apiKey=n[1]),e.config.model||(e.config.model=oe.defaultModel);else if(i==="custom"){if(!n[1]){console.log(fe("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=n[1],n[2]&&(e.config.apiKey=n[2])}else{console.log(fe("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=at(e.config);e.setClient(o),st(e.config),console.log(we(`Provider switched to ${Ke(e.config)}`));return}case"/doctor":{let i=await Nr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Ur(i));return}case"/workspace":{console.log(""),console.log(Or(gt(e.workingDir))),console.log("");return}case"/memory":{let i=z().getStats(),o=z().getRecent(5);console.log(""),console.log(U(`Persistent memory \u2014 ${i.total??0} total entries`));let a=Object.entries(i).filter(([l])=>l!=="total");if(a.length>0)for(let[l,c]of a)console.log(U(` ${l}: ${c}`));if(o.length>0){console.log(U("Recent:"));for(let l of o)console.log(U(` \xB7 [${l.kind}] ${l.key.slice(0,60)}`))}console.log("");return}case"/remember":{if(n.length<2){console.log(fe("Usage: /remember <key> <value>"));return}let i=n[0],o=n.slice(1).join(" ");z().remember({kind:"preference",key:`manual:${i}`,value:o,tags:["manual"],priority:"high"}),z().flush(),console.log(we(`Remembered: ${i} = ${o.slice(0,60)}`));return}case"/forget":{if(n.length===0){console.log(fe("Usage: /forget <key>"));return}let i=n.join(" "),o=z().forget(i)||z().forget(`manual:${i}`);z().flush(),console.log(o?we(`Forgotten: ${i}`):fe(`No memory found for: ${i}`));return}case"/memory-search":{if(n.length===0){console.log(fe("Usage: /memory-search <query>"));return}let i=n.join(" "),o=z().search(i,{limit:8});if(o.length===0){console.log(U("No memories found."));return}console.log(U(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(U(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(U(` ${a.entry.value.replace(/\n/g," \u2014 ").slice(0,120)}`));return}case"/compact":{let i=e.session.getTotalTokens(),o=e.session.getMessageCount();e.session.compress();let a=e.session.getTotalTokens(),l=e.session.getMessageCount(),c=i-a;console.log(""),console.log(we(`Context compacted: ${i.toLocaleString()} \u2192 ${a.toLocaleString()} tokens (saved ${c.toLocaleString()})`)),console.log(U(`Messages: ${o} \u2192 ${l}`)),console.log("");return}case"/plan":{let o=e.session.getMessages().filter(a=>a.role==="user"&&typeof a.content=="string"&&a.content.includes("[PLAN]"));console.log(""),o.length===0?console.log(U("No active plan in current session. Plans are created automatically for complex tasks.")):(console.log(U(`Active plan (${o.length} plan message(s) in session):`)),console.log(o[o.length-1].content?.slice(0,2e3))),console.log("");return}case"/save":{let i=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),{default:o}=await import("fs"),{default:a}=await import("path"),{default:l}=await import("os"),c=a.join(l.homedir(),".hablas","sessions");o.mkdirSync(c,{recursive:!0});let f=a.join(c,`session-${i}.json`),d={savedAt:new Date().toISOString(),tokens:e.session.getTotalTokens(),messages:e.session.getMessages()};o.writeFileSync(f,JSON.stringify(d,null,2),"utf-8"),console.log(""),console.log(we(`Session saved: ${f}`)),console.log(U(`${d.messages.length} messages, ${d.tokens.toLocaleString()} tokens`)),console.log("");return}default:console.log(fe(`Unknown command: ${s}`))}}var Ae=k(require("fs")),Dn=k(require("path"));function Fn(t){let e=Dn.join(t,".hablas");return Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0}),e}function mc(t){return Dn.join(Fn(t),"session.json")}function qr(t,e){let r=mc(t);try{return Ae.existsSync(r)?(e.fromJSON(Ae.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Ht(t,e){let r=mc(t);try{Ae.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function yc(t,e){si();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,s=at(t);Fn(r);let n=new dt(r,t),i=new pt(t),o=await wt(r,t),a=new mt(bt(o,_n("hello"),r),t.historySize,t.contextBudget);qr(r,a);let l=new jr(r);console.log(Dl(t.model,r));let c=new Ye("Connecting");c.start();let f=await s.checkConnection();if(c.stop(),f){let m=await s.listModels();console.log(we(`online \xB7 ${Ke(t)} \xB7 ${m.length} models available`))}else console.log(fe(`offline \xB7 ${Ke(t)} \xB7 you can still inspect local files and switch provider with /provider`));St.existsSync(Br.join(r,".git"))||console.log(U("workspace mode: standalone (no git repository detected)")),console.log(U("Hablas is ready.")),console.log("");let d=0,h=0,p=Date.now(),u=new AbortController,g=0;for(process.on("SIGINT",()=>{let m=Date.now();m-g<1500&&(console.log(""),console.log(U(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),g=m,u.abort(),u=new AbortController,console.log(""),console.log(fe("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let x=(await l.prompt(" \u203A ")).trim();if(x){if(x.startsWith("/")){let b=await hc(x,{config:t,client:s,setClient:w=>{s=w},session:a,workingDir:r});if(Ht(r,a),b==="quit")break;continue}d+=1,console.log(Fl(d)),u=new AbortController;try{if(await Fr(x,{config:t,client:s,registry:n,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),Ht(r,a),d>0&&d%10===0)try{let w=Br.join(gc.homedir(),".hablas","sessions");St.mkdirSync(w,{recursive:!0});let v=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),_=Br.join(w,`auto-${v}-turn${d}.json`);St.writeFileSync(_,JSON.stringify({savedAt:new Date().toISOString(),turn:d,tokens:a.getTotalTokens(),messages:a.getMessages()},null,2),"utf-8")}catch{}}catch(b){if(b?.name==="AbortError")continue;console.log(Fe(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}kl(),l.close()}var Qg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Zg=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,ey=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,ty=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,ry=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,sy=/\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,ny=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,iy=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,wc=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function bc(t){let e=t.trim(),r=e.toLowerCase(),s=Zg.test(r),n=ey.test(r),i=ty.test(r)||ry.test(r),o=sy.test(r),a=ny.test(r),l=i||s||n||o&&e.length>18&&!wc.test(r)&&!a,c=a&&!i&&!s&&!n,f=iy.test(r)||o,d=!l&&!c&&(wc.test(r)||e.endsWith("?"));return Qg.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:s,oneStepDelivery:n,requiresProjectContext:!0,reason:s?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:s,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 xc(t,e,r){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,n=at(e),i=new dt(s,e),o=new pt(e),a=await wt(s,e),l=new mt(bt(a,bc(t)),e.historySize,e.contextBudget);qr(s,l),await Fr(t,{config:e,client:n,registry:i,contextManager:o,session:l,workingDir:s,logger:r,interactive:!1}),Ht(s,l)}var Hr=k(require("fs")),Xe=k(require("path")),oy=[{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"}],ay=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),ly=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function cy(t,e){let r=[],s=e.split(`
|
|
301
|
+
`);for(let{pattern:n,name:i,severity:o}of oy){n.lastIndex=0;let a;for(;(a=n.exec(e))!==null;){let c=e.substring(0,a.index).split(`
|
|
302
|
+
`).length,f=s[c-1]||"";f.trim().startsWith("#")||f.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function uy(t,e){let r=[],s=e.split(`
|
|
303
|
+
`),n=Xe.extname(t);return[".ts",".js",".tsx",".jsx"].includes(n)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function Sc(t,e=[]){try{let r=Hr.readdirSync(t,{withFileTypes:!0});for(let s of r){if(ay.has(s.name))continue;let n=Xe.join(t,s.name);if(s.isDirectory())Sc(n,e);else if(s.isFile()){let i=Xe.extname(s.name);ly.has(i)||e.push(n)}}}catch{}return e}function vc(t){let e=Date.now(),r=Sc(t),s=[];for(let o of r)try{let a=Hr.readFileSync(o,"utf-8"),l=Xe.relative(t,o),c=cy(l,a);s.push(...c);let f=uy(l,a);s.push(...f)}catch{}let n=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:r.length,duration:n,summary:i}}function _c(t){let e=[];if(e.push(`
|
|
304
|
+
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((s,n)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[s.severity]-i[n.severity]}).slice(0,10);for(let s of r){let n=s.severity==="critical"?"\u{1F534}":s.severity==="high"?"\u{1F7E0}":s.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${n} [${s.severity.toUpperCase()}] ${s.message}`),e.push(` File: ${s.file}${s.line?`:${s.line}`:""}`),e.push(` Fix: ${s.suggestion}`),e.push("")}}return e.join(`
|
|
305
|
+
`)}var vt=k(require("fs")),Nn=k(require("path")),$c=k(require("os")),fy=Nn.join($c.homedir(),".hablas"),kc=Nn.join(fy,"analytics.json");function Tc(){try{if(vt.existsSync(kc))return JSON.parse(vt.readFileSync(kc,"utf-8"))}catch{}return dy()}function dy(){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 Cc(t){let e=[];e.push(`
|
|
306
|
+
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((n,i)=>i[1]-n[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[n,i]of r)e.push(` @${n}: ${i} uses`);e.push("")}let s=Object.entries(t.commandUsage).sort((n,i)=>i[1]-n[1]).slice(0,5);if(s.length>0){e.push(" Top Commands:");for(let[n,i]of s)e.push(` ${n}: ${i} calls`)}return e.join(`
|
|
307
|
+
`)}var Ec=k(require("readline"));var Z="\x1B[36m",Wr="\x1B[32m",Oe="\x1B[33m",M="\x1B[2m",Re="\x1B[1m",$="\x1B[0m",py="\x1B[35m";function G(t,e){return new Promise(r=>t.question(e,s=>r(s)))}function hy(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Wt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function Ac(t){let e=Ec.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Re}${Z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(`${Re}${Z} hablas \u2014 Setup Wizard${$}`),console.log(`${M} Configure your AI provider and model${$}`),console.log(`${Re}${Z} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${$}`),console.log(),console.log(`${Re} Choose your setup:${$}`),console.log(),console.log(` ${py}${Re}1${$}. ${Re}Hablas Integrated Engine${$} ${Wr}(instant \u2014 no setup needed)${$}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${$}`),console.log(),console.log(` ${Z}${Re}2${$}. ${Re}Custom Provider${$} ${M}(bring your own API key)${$}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${$}`),console.log(),(await G(e,` ${M}Your choice (1-2):${$} `)).trim()){case"1":{t.provider=Wt.provider,t.apiUrl=Wt.apiUrl,t.apiKey=hy(),t.model=Wt.model,st(t),console.log(),console.log(`${Wr} \u2713 Hablas Integrated Engine activated!${$}`),console.log(`${M} Model: ${Wt.model}${$}`),console.log(`${M} API: ${Wt.apiUrl}${$}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${$}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${$}`),console.log(` ${Z}a${$}. Ollama (local, free, private)`),console.log(` ${Z}b${$}. OpenAI API`),console.log(` ${Z}c${$}. Groq (fast, free tier)`),console.log(` ${Z}d${$}. OpenRouter (many models)`),console.log(` ${Z}e${$}. Together AI`),console.log(` ${Z}f${$}. DeepSeek`),console.log(` ${Z}g${$}. Custom OpenAI-compatible API`),console.log(` ${Z}h${$}. NVIDIA NIM (powerful cloud models)`),console.log(),(await G(e,` ${M}Your choice (a-h):${$} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let n=(await G(e,` ${M}Ollama host [http://localhost:11434]:${$} `)).trim(),i=(await G(e,` ${M}Model [qwen2.5-coder:7b]:${$} `)).trim();t.ollamaHost=n||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let n=(await G(e,` ${M}OpenAI API Key (sk-...):${$} `)).trim(),i=(await G(e,` ${M}Model [gpt-4o]:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=n,t.model=i||"gpt-4o";break}case"c":{let n=(await G(e,` ${M}Groq API Key (gsk_...):${$} `)).trim(),i=(await G(e,` ${M}Model [llama-3.3-70b-versatile]:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=n,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let n=(await G(e,` ${M}OpenRouter API Key (sk-or-...):${$} `)).trim(),i=(await G(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=n,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let n=(await G(e,` ${M}Together API Key:${$} `)).trim(),i=(await G(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=n,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let n=(await G(e,` ${M}DeepSeek API Key:${$} `)).trim(),i=(await G(e,` ${M}Model [deepseek-chat]:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=n,t.model=i||"deepseek-chat";break}case"g":{let n=(await G(e,` ${M}API base URL:${$} `)).trim(),i=(await G(e,` ${M}API key (optional):${$} `)).trim(),o=(await G(e,` ${M}Model ID:${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 URL is required \u2014 cancelled${$}`),e.close();return}t.provider="custom",t.apiUrl=n,t.apiKey=i,o&&(t.model=o);break}case"h":{let n=(await G(e,` ${M}NVIDIA API Key (nvapi-...):${$} `)).trim();if(!n){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${$}`),console.log(`${M} Get your key at: https://build.nvidia.com/${$}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${$}`),oe.models.forEach((a,l)=>{console.log(` ${Z}${l+1}${$}. ${a}`)}),console.log();let i=(await G(e,` ${M}Model number [1]:${$} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=oe.apiUrl,t.apiKey=n,t.model=oe.models[o]||oe.defaultModel;break}default:console.log(`${Oe} \u26A0 Invalid choice${$}`),e.close();return}st(t),console.log(),console.log(`${Wr} \u2713 Custom provider configured successfully${$}`),console.log(`${M} Provider: ${t.provider}${$}`),console.log(`${M} Model: ${t.model}${$}`);break}default:console.log(`${Oe} \u26A0 Invalid choice \u2014 please select 1 or 2${$}`),e.close();return}console.log(),console.log(`${Re}${Wr} \u2713 Setup complete!${$}`),console.log(`${M} Use ${Z}hablas${$}${M} for interactive mode or ${Z}hablas run "..."${$}${M} for one-shot execution.${$}`),console.log(),e.close()}var Oc=ga(),se=new ti;se.name("hablas").description(`Hablas CLI v${Oc} \u2014 single-agent engineering runtime for the terminal.`).version(Oc).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");se.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=se.opts(),r=rt({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let s=rn(r);await xc(t,r,s)});se.command("doctor").description("Run system diagnostics").action(async()=>{let t=se.opts(),e=rt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Nr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Ur(r))});se.command("info").description("Show workspace information").action(async()=>{let t=se.opts(),e=rt({project:t.project});console.log(""),console.log(Or(gt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});se.command("security").description("Run a security scan on the current project").action(async()=>{let t=se.opts(),e=rt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(_c(vc(r)))});se.command("stats").description("Show local usage statistics").action(async()=>{console.log(Cc(Tc()))});se.action(async()=>{let t=se.opts(),e=rt({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 Ac(e);return}let r=rn(e);await yc(e,r)});se.parse();
|