hablas-ai 2.2.12 → 2.2.14
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 +172 -140
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,196 +1,201 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],
|
|
2
|
+
"use strict";var Ac=Object.create;var Ds=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Rc=Object.getOwnPropertyNames;var Ic=Object.getPrototypeOf,Pc=Object.prototype.hasOwnProperty;var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Mc=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Rc(e))!Pc.call(t,s)&&s!==r&&Ds(t,s,{get:()=>e[s],enumerable:!(n=Oc(e,s))||n.enumerable});return t};var $=(t,e,r)=>(r=t!=null?Ac(Ic(t)):{},Mc(e||!t||!t.__esModule?Ds(r,"default",{value:t,enumerable:!0}):r,t));var _t=I(Hr=>{var Vt=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},Br=class extends Vt{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Hr.CommanderError=Vt;Hr.InvalidArgumentError=Br});var zt=I(Vr=>{var{InvalidArgumentError:jc}=_t(),Wr=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new jc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Lc(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Vr.Argument=Wr;Vr.humanReadableArgName=Lc});var Kr=I(Fs=>{var{humanReadableArgName:Dc}=zt(),zr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Dc(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(u,g){if(g){let m=`${u.padEnd(n+o)}${g}`;return r.wrap(m,s-i,n+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,s,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
4
|
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let l=e.slice(0,n),c=e.slice(n).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),
|
|
7
|
-
|.{1,${a-1}}([${
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
6
|
+
`),f=" ".repeat(n),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
|
+
`)}};Fs.Help=zr});var Xr=I(Yr=>{var{InvalidArgumentError:Fc}=_t(),Gr=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=Uc(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Fc(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Nc(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Jr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return r.negate===(i===e)}};function Nc(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Uc(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}Yr.Option=Gr;Yr.DualOptions=Jr});var Us=I(Ns=>{function qc(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[n-1]?i=0:i=1,r[s][n]=Math.min(r[s-1][n]+1,r[s][n-1]+1,r[s-1][n-1]+i),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1]&&(r[s][n]=Math.min(r[s][n],r[s-2][n-2]+1))}return r[t.length][e.length]}function Bc(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=qc(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new
|
|
13
|
-
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Ns.suggestSimilar=Bc});var Vs=I(Ws=>{var Hc=require("node:events").EventEmitter,Qr=require("node:child_process"),Se=require("node:path"),Zr=require("node:fs"),H=require("node:process"),{Argument:Wc,humanReadableArgName:Vc}=zt(),{CommanderError:en}=_t(),{Help:zc}=Kr(),{Option:qs,DualOptions:Kc}=Xr(),{suggestSimilar:Bs}=Us(),tn=class t extends Hc{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>H.stdout.write(r),writeErr:r=>H.stderr.write(r),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let s=r,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return s&&(l.description(s),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),s?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new zc,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 Wc(e,r)}argument(e,r,n,s){let i=this.createArgument(e,r);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new en(e,r,n)),H.exit(e)}action(e){let r=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new qs(e,r)}_callParseArg(e,r,n,s){try{return e.parseArg(r,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof qs)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(l,c)=>{let f=a.exec(l);return f?f[0]:c},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,r,n,s){return this._optionEx({},e,r,n,s)}requiredOption(e,r,n,s){return this._optionEx({mandatory:!0},e,r,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){H.versions?.electron&&(r.from="electron");let s=H.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=H.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":H.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(f,d){let h=Se.resolve(f,d);if(Zr.existsSync(h))return h;if(s.includes(Se.extname(d)))return;let p=s.find(u=>Zr.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=Zr.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=Se.resolve(Se.dirname(f),a)}if(a){let f=i(a,o);if(!f&&!e._executableFile&&this._scriptPath){let d=Se.basename(this._scriptPath,Se.extname(this._scriptPath));d!==this._name&&(f=i(a,`${d}-${e._name}`))}o=f||o}n=s.includes(Se.extname(o));let l;H.platform!=="win32"?n?(r.unshift(o),r=Hs(H.execArgv).concat(r),l=Qr.spawn(H.argv[0],r,{stdio:"inherit"})):l=Qr.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Hs(H.execArgv).concat(r),l=Qr.spawn(H.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{H.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",f=>{f=f??1,c?c(new en(f,"commander.executeSubCommandAsync","(close)")):H.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)H.exit(1);else{let d=new en(1,"commander.executeSubCommandAsync","(error)");d.nestedError=f,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,r.concat(n));else return s._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),r[s]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),r==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,r))}),s}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],s=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){s===n&&s.push(l),s.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let f=i.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;i.length>0&&!o(i[0])&&(f=i.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),f=this._findOption(l.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(c+1));continue}}if(o(l)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(l),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(l),i.length>0&&s.push(...i);break}s.push(l)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in H.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,H.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Kc(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),f=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:f||o},s=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=Bs(e,s)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),r=Bs(e,s)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>Vc(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Se.basename(e,Se.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=H.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
24
|
-
causes have become circular...`;let n=
|
|
25
|
-
caused by: `+Gs(n,e)):r},jc=t=>Gs(t,new Set),Js=(t,e,r)=>{if(!xt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Zr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+Js(s,e,i)}else return n},Pc=t=>Js(t,new Set);Ys.exports={isErrorLike:xt,getErrorCause:Zr,stackWithCauses:jc,messageWithCauses:Pc}});var tn=R((gy,Qs)=>{"use strict";var Lc=Symbol("circular-ref-tag"),Ht=Symbol("pino-raw-err-ref"),Xs=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[Ht]},set:function(t){this[Ht]=t}}});Object.defineProperty(Xs,Ht,{writable:!0,value:{}});Qs.exports={pinoErrProto:Xs,pinoErrorSymbols:{seen:Lc,rawSymbol:Ht}}});var ti=R((yy,ei)=>{"use strict";ei.exports=nn;var{messageWithCauses:Dc,stackWithCauses:Fc,isErrorLike:Zs}=en(),{pinoErrProto:Nc,pinoErrorSymbols:qc}=tn(),{seen:rn}=qc,{toString:Uc}=Object.prototype;function nn(t){if(!Zs(t))return t;t[rn]=void 0;let e=Object.create(Nc);e.type=Uc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Dc(t),e.stack=Fc(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>nn(r)));for(let r in t)if(e[r]===void 0){let n=t[r];Zs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,rn)&&(e[r]=nn(n)):e[r]=n}return delete t[rn],e.raw=t,e}});var ni=R((wy,ri)=>{"use strict";ri.exports=Vt;var{isErrorLike:sn}=en(),{pinoErrProto:Bc,pinoErrorSymbols:Hc}=tn(),{seen:Wt}=Hc,{toString:Wc}=Object.prototype;function Vt(t){if(!sn(t))return t;t[Wt]=void 0;let e=Object.create(Bc);e.type=Wc.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Vt(r))),sn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,Wt)&&(e.cause=Vt(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];sn(n)?Object.prototype.hasOwnProperty.call(n,Wt)||(e[r]=Vt(n)):e[r]=n}return delete t[Wt],e.raw=t,e}});var ai=R((by,oi)=>{"use strict";oi.exports={mapHttpRequest:Vc,reqSerializer:ii};var on=Symbol("pino-raw-req-ref"),si=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[on]},set:function(t){this[on]=t}}});Object.defineProperty(si,on,{writable:!0,value:{}});function ii(t){let e=t.info||t.socket,r=Object.create(si);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function Vc(t){return{req:ii(t)}}});var fi=R((xy,ui)=>{"use strict";ui.exports={mapHttpResponse:zc,resSerializer:ci};var an=Symbol("pino-raw-res-ref"),li=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[an]},set:function(t){this[an]=t}}});Object.defineProperty(li,an,{writable:!0,value:{}});function ci(t){let e=Object.create(li);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function zc(t){return{res:ci(t)}}});var cn=R((Sy,di)=>{"use strict";var ln=ti(),Kc=ni(),zt=ai(),Kt=fi();di.exports={err:ln,errWithCause:Kc,mapHttpRequest:zt.mapHttpRequest,mapHttpResponse:Kt.mapHttpResponse,req:zt.reqSerializer,res:Kt.resSerializer,wrapErrorSerializer:function(e){return e===ln?e:function(n){return e(ln(n))}},wrapRequestSerializer:function(e){return e===zt.reqSerializer?e:function(n){return e(zt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Kt.resSerializer?e:function(n){return e(Kt.resSerializer(n))}}}});var un=R((vy,pi)=>{"use strict";function Gc(t,e){return e}pi.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Gc;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var bi=R((_y,wi)=>{"use strict";function fn(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=fn(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=fn(t[r]));return e}return t}function mi(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function hi(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function gi(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var Gt=Symbol("PATH_NOT_FOUND");function Jc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return Gt;r=r[n]}return r}function Yc(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function Xc(t,e,r,n=!1){for(let s of e){let i=mi(s);if(i.includes("*"))yi(t,i,r,s,n);else if(n)gi(t,i);else{let o=Jc(t,i);if(o===Gt)continue;let a=typeof r=="function"?r(o,i):r;hi(t,i,a)}}}function yi(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else Qc(t,e,r,i,n,s)}function Qc(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let m=0;m<u.length;m++)l[d]=m.toString(),c(u[m],d+1);else if(typeof u=="object"&&u!==null)for(let m in u)l[d]=m,c(u[m],d+1)}else if(d<o.length){let m=o[d];u&&typeof u=="object"&&u!==null&&m in u&&(l[d]=m,c(u[m],d+1))}else if(a.includes("*"))yi(u,a,typeof r=="function"?(p,f)=>{let h=[...l.slice(0,d),...f];return r(p,h)}:r,s,i);else if(i)gi(u,a);else{let m=typeof r=="function"?r(Yc(u,a),[...l.slice(0,d),...a]):r;hi(u,a,m)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let m=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[m],l[d]=m}u!=null&&c(u,o.length)}}function Zc(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=mi(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function eu(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let c=l.toString();s.has(c)||s.has("*")?a[l]=r(n[l],s.get(c)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function tu(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function ru(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)tu(e)}function nu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;ru(e);let o=Zc(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=eu(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Xc(c,e,d,i),n===!1?(c.restore=function(){return fn(u)},c):typeof n=="function"?n(c):JSON.stringify(c)}}wi.exports=nu});var et=R((ky,xi)=>{"use strict";var su=Symbol("pino.setLevel"),iu=Symbol("pino.getLevel"),ou=Symbol("pino.levelVal"),au=Symbol("pino.levelComp"),lu=Symbol("pino.useLevelLabels"),cu=Symbol("pino.useOnlyCustomLevels"),uu=Symbol("pino.mixin"),fu=Symbol("pino.lsCache"),du=Symbol("pino.chindings"),pu=Symbol("pino.asJson"),mu=Symbol("pino.write"),hu=Symbol("pino.redactFmt"),gu=Symbol("pino.time"),yu=Symbol("pino.timeSliceIndex"),wu=Symbol("pino.stream"),bu=Symbol("pino.stringify"),xu=Symbol("pino.stringifySafe"),Su=Symbol("pino.stringifiers"),vu=Symbol("pino.end"),_u=Symbol("pino.formatOpts"),ku=Symbol("pino.messageKey"),$u=Symbol("pino.errorKey"),Tu=Symbol("pino.nestedKey"),Cu=Symbol("pino.nestedKeyStr"),Eu=Symbol("pino.mixinMergeStrategy"),Au=Symbol("pino.msgPrefix"),Ou=Symbol("pino.wildcardFirst"),Iu=Symbol.for("pino.serializers"),Ru=Symbol.for("pino.formatters"),Mu=Symbol.for("pino.hooks"),ju=Symbol.for("pino.metadata");xi.exports={setLevelSym:su,getLevelSym:iu,levelValSym:ou,levelCompSym:au,useLevelLabelsSym:lu,mixinSym:uu,lsCacheSym:fu,chindingsSym:du,asJsonSym:pu,writeSym:mu,serializersSym:Iu,redactFmtSym:hu,timeSym:gu,timeSliceIndexSym:yu,streamSym:wu,stringifySym:bu,stringifySafeSym:xu,stringifiersSym:Su,endSym:vu,formatOptsSym:_u,messageKeySym:ku,errorKeySym:$u,nestedKeySym:Tu,wildcardFirstSym:Ou,needsMetadataGsym:ju,useOnlyCustomLevelsSym:cu,formattersSym:Ru,hooksSym:Mu,nestedKeyStrSym:Cu,mixinMergeStrategySym:Eu,msgPrefixSym:Au}});var pn=R(($y,ki)=>{"use strict";var Si=bi(),{redactFmtSym:Pu,wildcardFirstSym:Jt}=et(),dn=/[^.[\]]+|\[([^[\]]*?)\]/g,vi="[Redacted]",_i=!1;function Lu(t,e){let{paths:r,censor:n,remove:s}=Du(t),i=r.reduce((l,c)=>{dn.lastIndex=0;let u=dn.exec(c),d=dn.exec(c),m=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(m==="*"&&(m=Jt),d===null)return l[m]=null,l;if(l[m]===null)return l;let{index:p}=d,f=`${c.substr(p,c.length-1)}`;return l[m]=l[m]||[],m!==Jt&&l[m].length===0&&l[m].push(...l[Jt]||[]),m===Jt&&Object.keys(l).forEach(function(h){l[h]&&l[h].push(f)}),l[m].push(f),l},{}),o={[Pu]:Si({paths:r,censor:n,serialize:e,strict:_i,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=u=>a(u,[c]);else{let u=typeof n=="function"?(d,m)=>n(d,[c,...m]):n;l[c]=Si({paths:i[c],censor:u,serialize:e,strict:_i,remove:s})}return l},o)}function Du(t){if(Array.isArray(t))return t={paths:t,censor:vi},t;let{paths:e,censor:r=vi,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}ki.exports=Lu});var Ci=R((Ty,Ti)=>{"use strict";var Fu=()=>"",Nu=()=>`,"time":${Date.now()}`,qu=()=>`,"time":${Math.round(Date.now()/1e3)}`,Uu=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Bu=1000000n,$i=1000000000n,Hu=BigInt(Date.now())*Bu,Wu=process.hrtime.bigint(),Vu=()=>{let t=process.hrtime.bigint()-Wu,e=Hu+t,r=e/$i,n=e%$i,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Ti.exports={nullTime:Fu,epochTime:Nu,unixTime:qu,isoTime:Uu,isoTimeNano:Vu}});var Ai=R((Cy,Ei)=>{"use strict";function zu(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Ei.exports=Ku;function Ku(t,e,r){var n=r&&r.stringify||zu,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",u=1-s,d=-1,m=t&&t.length||0,p=0;p<m;){if(t.charCodeAt(p)===37&&p+1<m){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(c+=t.slice(d,p));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=p+2,p++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=p+2,p++;break}c+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<m&&(c+=t.slice(d)),c)}});var hn=R((Ey,mn)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));mn.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};mn.exports=t}});var Di=R((Ay,Li)=>{"use strict";var F=require("fs"),Gu=require("events"),Ju=require("util").inherits,Oi=require("path"),yn=hn(),Yu=require("assert"),Yt=100,Xt=Buffer.allocUnsafe(0),Xu=16*1024,Ii="buffer",Ri="utf8",[Qu,Zu]=(process.versions.node||"0.0").split(".").map(Number),ef=Qu>=22&&Zu>=7;function Mi(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&F.mkdirSync(Oi.dirname(t),{recursive:!0});let i=F.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?F.mkdir(Oi.dirname(t),{recursive:!0},i=>{if(i)return r(i);F.open(t,n,s,r)}):F.open(t,n,s,r)}function fe(t){if(!(this instanceof fe))return new fe(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:m,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Xu,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,h;if(m===Ii)this._writingBuf=Xt,this.write=nf,this.flush=of,this.flushSync=lf,this._actualWrite=uf,f=()=>F.writeSync(this.fd,this._writingBuf),h=()=>F.write(this.fd,this._writingBuf,this.release);else if(m===void 0||m===Ri)this._writingBuf="",this.write=rf,this.flush=sf,this.flushSync=af,this._actualWrite=cf,f=()=>Buffer.isBuffer(this._writingBuf)?F.writeSync(this.fd,this._writingBuf):F.writeSync(this.fd,this._writingBuf,"utf8"),h=()=>Buffer.isBuffer(this._writingBuf)?F.write(this.fd,this._writingBuf,this.release):F.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ri}" and "${Ii}", but passed ${m}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Mi(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,S)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{yn(Yt),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(h,Yt);else this._writing=!1,this.emit("error",g);return}this.emit("write",S);let b=gn(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){h();return}try{do{let v=f(),E=gn(this._writingBuf,this._len,v);this._len=E.len,this._writingBuf=E.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&F.fsyncSync(this.fd);let x=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):x>this.minLength?this._actualWrite():this._ending?x>0?this._actualWrite():(this._writing=!1,Qt(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(tf,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function gn(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function tf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Ju(fe,Gu);function ji(t,e){return t.length===0?Xt:t.length===1?t[0]:Buffer.concat(t,e)}function rf(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function nf(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Pi(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{F.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function sf(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Pi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function of(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Pi.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}fe.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&F.close(e,r=>{if(r)return this.emit("error",r)})}),Mi(this.file,this)};fe.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Qt(this)))};function af(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?F.writeSync(this.fd,t):F.writeSync(this.fd,t,"utf8"),r=gn(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;yn(Yt)}}try{F.fsyncSync(this.fd)}catch{}}function lf(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Xt);let t=Xt;for(;this._bufs.length||t.length;){t.length<=0&&(t=ji(this._bufs[0],this._lens[0]));try{let e=F.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;yn(Yt)}}}fe.prototype.destroy=function(){this.destroyed||Qt(this)};function cf(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?F.writeSync(this.fd,this._writingBuf):F.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else F.write(this.fd,this._writingBuf,t)}function uf(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ji(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=F.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else ef&&(this._writingBuf=Buffer.from(this._writingBuf)),F.write(this.fd,this._writingBuf,t)}function Qt(t){if(t.fd===-1){t.once("ready",Qt.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Yu(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{F.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?F.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}fe.SonicBoom=fe;fe.default=fe;Li.exports=fe});var wn=R((Oy,Bi)=>{"use strict";var de={exit:[],beforeExit:[]},Fi={exit:pf,beforeExit:mf},tt;function ff(){tt===void 0&&(tt=new FinalizationRegistry(hf))}function df(t){de[t].length>0||process.on(t,Fi[t])}function Ni(t){de[t].length>0||(process.removeListener(t,Fi[t]),de.exit.length===0&&de.beforeExit.length===0&&(tt=void 0))}function pf(){qi("exit")}function mf(){qi("beforeExit")}function qi(t){for(let e of de[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}de[t]=[]}function hf(t){for(let e of["exit","beforeExit"]){let r=de[e].indexOf(t);de[e].splice(r,r+1),Ni(e)}}function Ui(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");df(t);let n=new WeakRef(e);n.fn=r,ff(),tt.register(e,n),de[t].push(n)}function gf(t,e){Ui("exit",t,e)}function yf(t,e){Ui("beforeExit",t,e)}function wf(t){if(tt!==void 0){tt.unregister(t);for(let e of["exit","beforeExit"])de[e]=de[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ni(e)}}Bi.exports={register:gf,registerBeforeExit:yf,unregister:wf}});var Hi=R((Iy,bf)=>{bf.exports={name:"thread-stream",version:"4.2.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",engines:{node:">=20"},dependencies:{"real-require":"^1.0.0"},devDependencies:{"@types/node":"^25.0.2","@yao-pkg/pkg":"^6.0.0",borp:"^1.0.0",desm:"^1.3.0",eslint:"^9.39.1",fastbench:"^1.0.1",neostandard:"^0.13.0","pino-elasticsearch":"^9.0.0","sonic-boom":"^5.0.0","ts-node":"^10.8.0",typescript:"~5.7.3"},scripts:{build:"tsc --noEmit",lint:"eslint",test:'npm run lint && npm run build && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:ci":'npm run lint && npm run transpile && borp --pattern "test/*.test.{js,mjs}"',"test:yarn":'npm run transpile && borp --pattern "test/*.test.js"',transpile:"sh ./test/ts/transpile.sh"},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina <hello@matteocollina.com>",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var Vi=R((Ry,Wi)=>{"use strict";function xf(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function Sf(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Wi.exports={wait:xf,waitDiff:Sf}});var Ki=R((My,zi)=>{"use strict";zi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var io=R((jy,so)=>{"use strict";var{version:vf}=Hi(),{EventEmitter:_f}=require("events"),{Worker:kf}=require("worker_threads"),{join:$f}=require("path"),{pathToFileURL:Tf}=require("url"),{wait:Cf}=Vi(),{WRITE_INDEX:we,READ_INDEX:Fe,SEQ_INDEX:bn}=Ki(),Ef=require("buffer"),Af=require("assert"),w=Symbol("kImpl"),Of=Ef.constants.MAX_STRING_LENGTH;function Gi(){}function _n(t,e){Atomics.add(t[w].state,bn,1),e(),Atomics.add(t[w].state,bn,1),Atomics.notify(t[w].state,bn)}function Ji(t){_n(t,()=>{Atomics.store(t[w].state,Fe,0),Atomics.store(t[w].state,we,0)})}var St=class{constructor(e){this._value=e}deref(){return this._value}},Zt=class{register(){}unregister(){}},If=process.env.NODE_V8_COVERAGE?Zt:global.FinalizationRegistry||Zt,Rf=process.env.NODE_V8_COVERAGE?St:global.WeakRef||St,Yi=new If(t=>{t.exited||t.terminate()});function Mf(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||$f(__dirname,"lib","worker.js"),o=new kf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Tf(r).href,dataBuf:t[w].dataBuf,stateBuf:t[w].stateBuf,workerData:{$context:{threadStreamVersion:vf},...n}}});return o.stream=new St(t),o.on("message",jf),o.on("exit",Zi),Yi.register(t,o),o}function Xi(t){Af(!t[w].sync),t[w].needDrain&&(t[w].needDrain=!1,t.emit("drain"))}function Qi(t){for(;;){let e=Atomics.load(t[w].state,we),r=t[w].data.length-e;if(r>0){if(t[w].bufLen===0){t[w].flushing=!1,t[w].ending?kn(t):t[w].needDrain&&process.nextTick(Xi,t);return}ro(t,r,Gi);continue}if(r===0){if(e===0&&t[w].bufLen===0)return;er(t,()=>{t.destroyed||(Ji(t),Qi(t))});return}se(t,new Error("overwritten"));return}}function jf(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new Rf(e),er(e,()=>{e[w].ready=!0,e.emit("ready")});break;case"ERROR":se(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){se(e,new Error("this should not happen: "+t.code));break}let r=e[w].flushCallbacks.get(t.id);r&&(e[w].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:se(e,new Error("this should not happen: "+t.code))}}function Zi(t){let e=this.stream.deref();e!==void 0&&(Yi.unregister(e),e.worker.exited=!0,e.worker.off("exit",Zi),se(e,t!==0?new Error("the worker thread exited"):null))}var Sn=class extends _f{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[w]={},this[w].stateBuf=new SharedArrayBuffer(128),this[w].state=new Int32Array(this[w].stateBuf),this[w].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[w].data=Buffer.from(this[w].dataBuf),this[w].sync=e.sync||!1,this[w].ending=!1,this[w].ended=!1,this[w].needDrain=!1,this[w].destroyed=!1,this[w].flushing=!1,this[w].ready=!1,this[w].finished=!1,this[w].errored=null,this[w].closed=!1,this[w].buf=[],this[w].bufHead=0,this[w].bufLen=0,this[w].flushCallbacks=new Map,this[w].nextFlushId=0,this.worker=Mf(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[w].destroyed)return vn(this,new Error("the worker has exited")),!1;if(this[w].ending)return vn(this,new Error("the worker is ending")),!1;if(this[w].flushing&&this[w].bufLen+r.length>=Of)try{xn(this),this[w].flushing=!0}catch(n){return se(this,n),!1}if(this[w].buf.push(r),this[w].bufLen+=r.length,this[w].sync)try{return xn(this),!0}catch(n){return se(this,n),!1}return this[w].flushing||(this[w].flushing=!0,setImmediate(Qi,this)),this[w].needDrain=this[w].data.length-this[w].bufLen-Atomics.load(this[w].state,we)<=0,!this[w].needDrain}end(){this[w].destroyed||(this[w].ending=!0,kn(this))}flush(e){e=typeof e=="function"?e:Gi,eo(this,r=>{if(r){process.nextTick(e,r);return}to(this,e)})}flushSync(){this[w].destroyed||(xn(this),no(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[w].ready}get destroyed(){return this[w].destroyed}get closed(){return this[w].closed}get writable(){return!this[w].destroyed&&!this[w].ending}get writableEnded(){return this[w].ending}get writableFinished(){return this[w].finished}get writableNeedDrain(){return this[w].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[w].errored}};function eo(t,e){if(t[w].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[w].sync&&(t[w].flushing||t[w].bufLen>0)){setImmediate(eo,t,e);return}er(t,e)}function er(t,e){let r=Atomics.load(t[w].state,we);Cf(t[w].state,Fe,r,1/0,(n,s)=>{if(n){se(t,n),e(n);return}if(s!=="ok"){er(t,e);return}e()})}function to(t,e){if(t[w].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[w].ready){let n=()=>{i(),to(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[w].nextFlushId;t[w].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[w].flushCallbacks.delete(r),se(t,n),process.nextTick(e,n)}}function Pf(t,e){let r=t[w].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function vn(t,e){setImmediate(()=>{t.emit("error",e)})}function se(t,e){t[w].destroyed||(t[w].destroyed=!0,Pf(t,e),e&&(t[w].errored=e,vn(t,e)),t.worker.exited?setImmediate(()=>{t[w].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[w].closed=!0,t.emit("close")}))}function ro(t,e,r){let s=Atomics.load(t[w].state,we),i=e;for(;i>0&&t[w].bufLen!==0;){let o=t[w].bufHead,a=t[w].buf[o];if(a.length<=i){a.copy(t[w].data,s),s+=a.length,i-=a.length,t[w].bufLen-=a.length,t[w].bufHead=o+1,t[w].bufHead===t[w].buf.length?(t[w].buf.length=0,t[w].bufHead=0):t[w].bufHead>=1024&&t[w].bufHead*2>=t[w].buf.length&&(t[w].buf.splice(0,t[w].bufHead),t[w].bufHead=0);continue}a.copy(t[w].data,s,0,i),t[w].buf[o]=a.subarray(i),t[w].bufLen-=i,s+=i,i=0}return _n(t,()=>{Atomics.store(t[w].state,we,s)}),r(),!0}function kn(t){if(!(t[w].ended||!t[w].ending||t[w].flushing)){t[w].ended=!0;try{t.flushSync();let e=Atomics.load(t[w].state,Fe);_n(t,()=>{Atomics.store(t[w].state,we,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[w].state,Fe,e,1e3),e=Atomics.load(t[w].state,Fe),e===-2){se(t,new Error("end() failed"));return}if(++r===10){se(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[w].finished=!0,t.emit("finish")})}catch(e){se(t,e)}}}function xn(t){let e=()=>{t[w].ending?kn(t):t[w].needDrain&&process.nextTick(Xi,t)};for(t[w].flushing=!1;t[w].bufLen!==0;){let r=Atomics.load(t[w].state,we),n=t[w].data.length-r;if(n===0){no(t),Ji(t);continue}else if(n<0)throw new Error("overwritten");ro(t,n,e)}}function no(t){if(t[w].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[w].state,we),r=0;for(;;){let n=Atomics.load(t[w].state,Fe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[w].state,Fe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}so.exports=Sn});var Cn=R((Py,lo)=>{"use strict";var{createRequire:Lf}=require("module"),{existsSync:Df}=require("node:fs"),Ff=un(),{join:$n,isAbsolute:ao,sep:Nf}=require("node:path"),{fileURLToPath:qf}=require("node:url"),Uf=hn(),Tn=wn(),Bf=io();function Hf(t){Tn.register(t,Gf),Tn.registerBeforeExit(t,Jf),t.on("close",function(){Tn.unregister(t)})}function Wf(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function Vf(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&oo(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(oo(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function oo(t){let e=zf(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=qf(r)}catch{return!1}return ao(r)&&!Df(r)}function zf(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Kf(t,e,r,n,s){if(!r.execArgv&&Wf()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Vf(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new Bf({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&Hf(i)}function a(){i.closed||(i.flushSync(),Uf(100),i.end())}return i}function Gf(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Jf(t){t.flushSync()}function Yf(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=Ff(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||$n(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:p(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(h=>({...h,level:f.level,target:p(h.target)})))):e&&(d=u["pino-worker"]||$n(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:p(f.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let m=r||e?"pino.transport":d;return Kf(p(d),l,i,a,m);function p(f){if(f=u[f]||f,ao(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return $n(__dirname,"..","file.js");let h;for(let g of c)try{let S=g==="node:repl"?process.cwd()+Nf:g;h=Lf(S).resolve(f);break}catch{continue}if(!h)throw new Error(`unable to determine transport target for "${f}"`);return h}}lo.exports=Yf});var nr=R((Ly,vo)=>{"use strict";var Xf=require("node:diagnostics_channel"),co=Ai(),{mapHttpRequest:Qf,mapHttpResponse:Zf}=cn(),An=Di(),uo=wn(),{lsCacheSym:ed,chindingsSym:go,writeSym:fo,serializersSym:yo,formatOptsSym:po,endSym:td,stringifiersSym:wo,stringifySym:bo,stringifySafeSym:On,wildcardFirstSym:xo,nestedKeySym:rd,formattersSym:So,messageKeySym:nd,errorKeySym:sd,nestedKeyStrSym:id,msgPrefixSym:tr}=et(),{isMainThread:od}=require("worker_threads"),ad=Cn(),[ld]=process.versions.node.split(".").map(t=>Number(t)),mo=Xf.tracingChannel("pino_asJson"),En=ld>=25?t=>JSON.stringify(t):ud;function rt(){}function cd(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=Qf(n):typeof n.setHeader=="function"&&(n=Zf(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[tr]=="string"&&i!==void 0&&i!==null&&(i=this[tr]+i),this[fo](n,co(i,o,this[po]),t)}else{let i=n===void 0?s.shift():n;typeof this[tr]=="string"&&i!==void 0&&i!==null&&(i=this[tr]+i),this[fo](null,co(i,s,this[po]),t)}}}function ud(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function fd(t,e,r,n){if(mo.hasSubscribers===!1)return ho.call(this,t,e,r,n);let s={instance:this,arguments};return mo.traceSync(ho,s,this,t,e,r,n)}function ho(t,e,r,n){let s=this[bo],i=this[On],o=this[wo],a=this[td],l=this[go],c=this[yo],u=this[So],d=this[nd],m=this[sd],p=this[ed][r]+n;p=p+l;let f;u.log&&(t=u.log(t));let h=o[xo],g="";for(let b in t)if(f=t[b],Object.prototype.hasOwnProperty.call(t,b)&&f!==void 0){c[b]?f=c[b](f):b===m&&c.err&&(f=c.err(f));let x=o[b]||h;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":x&&(f=x(f));break;case"string":f=(x||En)(f);break;default:f=(x||s)(f,i)}if(f===void 0)continue;let v=En(b);g+=","+v+":"+f}let S="";if(e!==void 0){f=c[d]?c[d](e):e;let b=o[d]||h;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":b&&(f=b(f)),S=',"'+d+'":'+f;break;case"string":f=(b||En)(f),S=',"'+d+'":'+f;break;default:f=(b||s)(f,i),S=',"'+d+'":'+f}}return this[rd]&&g?p+this[id]+g.slice(1)+"}"+S+a:p+g+S+a}function dd(t,e){let r,n=t[go],s=t[bo],i=t[On],o=t[wo],a=o[xo],l=t[yo],c=t[So].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function pd(t){return t.write!==t.constructor.prototype.write}function rr(t){let e=new An(t);return e.on("error",r),!t.sync&&od&&(uo.register(e,md),e.on("close",function(){uo.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=rt,e.end=rt,e.flushSync=rt,e.destroy=rt;return}e.removeListener("error",r),e.emit("error",n)}}function md(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function hd(t){return function(r,n,s={},i){if(typeof s=="string")i=rr({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=rr({dest:i})}else if(s instanceof An||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof An||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=ad({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=rt),i||(pd(process.stdout)?i=process.stdout:i=rr({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function gd(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[On])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function yd(t,e,r){return{level:t,bindings:e,log:r}}function wd(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}vo.exports={noop:rt,buildSafeSonicBoom:rr,asChindings:dd,asJson:fd,genLog:cd,createArgsNormalizer:hd,stringify:gd,buildFormatters:yd,normalizeDestFileDescriptor:wd}});var sr=R((Dy,_o)=>{var bd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},xd={ASC:"ASC",DESC:"DESC"};_o.exports={DEFAULT_LEVELS:bd,SORTING_ORDER:xd}});var Mn=R((Fy,Co)=>{"use strict";var{lsCacheSym:Sd,levelValSym:In,useOnlyCustomLevelsSym:vd,streamSym:_d,formattersSym:kd,hooksSym:$d,levelCompSym:ko}=et(),{noop:Td,genLog:Ne}=nr(),{DEFAULT_LEVELS:he,SORTING_ORDER:$o}=sr(),To={fatal:t=>{let e=Ne(he.fatal,t);return function(...r){let n=this[_d];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>Ne(he.error,t),warn:t=>Ne(he.warn,t),info:t=>Ne(he.info,t),debug:t=>Ne(he.debug,t),trace:t=>Ne(he.trace,t)},Rn=Object.keys(he).reduce((t,e)=>(t[he[e]]=e,t),{}),Cd=Object.keys(Rn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Ed(t){let e=t[kd].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Sd]=n,t}function Ad(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Od(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[In],s=this[In]=r[t],i=this[vd],o=this[ko],a=this[$d].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Td;continue}this[l]=Ad(l,i)?To[l](a):Ne(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Id(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Rd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[ko](r,this[In])}function Md(t,e,r){return t===$o.DESC?e<=r:e>=r}function jd(t){return typeof t=="string"?Md.bind(null,t):t}function Pd(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Rn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:he,t);return{labels:n,values:s}}function Ld(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Rn).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:he,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function Dd(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Fd(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values($o).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Co.exports={initialLsCache:Cd,genLsCache:Ed,levelMethods:To,getLevel:Id,setLevel:Od,isLevelEnabled:Rd,mappings:Pd,assertNoLevelCollisions:Dd,assertDefaultLevelFound:Ld,genLevelComparison:jd,assertLevelComparison:Fd}});var jn=R((Ny,Eo)=>{"use strict";Eo.exports={version:"10.3.1"}});var Lo=R((Uy,Po)=>{"use strict";var{EventEmitter:Nd}=require("node:events"),{lsCacheSym:qd,levelValSym:Ud,setLevelSym:Ln,getLevelSym:Ao,chindingsSym:or,mixinSym:Bd,asJsonSym:Io,writeSym:Hd,mixinMergeStrategySym:Wd,timeSym:Vd,timeSliceIndexSym:zd,streamSym:Ro,serializersSym:qe,formattersSym:vt,errorKeySym:Kd,messageKeySym:Gd,useOnlyCustomLevelsSym:Jd,needsMetadataGsym:Yd,redactFmtSym:Xd,stringifySym:Qd,formatOptsSym:Zd,stringifiersSym:ep,msgPrefixSym:Dn,hooksSym:tp}=et(),{getLevel:rp,setLevel:np,isLevelEnabled:sp,mappings:ip,initialLsCache:op,genLsCache:ap,assertNoLevelCollisions:lp}=Mn(),{asChindings:Fn,asJson:cp,buildFormatters:Pn,stringify:Oo,noop:Mo}=nr(),{version:up}=jn(),fp=pn(),dp=class{},jo={constructor:dp,child:pp,bindings:mp,setBindings:hp,flush:wp,isLevelEnabled:sp,version:up,get level(){return this[Ao]()},set level(t){this[Ln](t)},get levelVal(){return this[Ud]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[Dn]},get[Symbol.toStringTag](){return"Pino"},[qd]:op,[Hd]:yp,[Io]:cp,[Ao]:rp,[Ln]:np};Object.setPrototypeOf(jo,Nd.prototype);Po.exports=function(){return Object.create(jo)};var ir=t=>t;function pp(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[qe],n=this[vt],s=Object.create(this);if(e==null)return s[vt].bindings!==ir&&(s[vt]=Pn(n.level,ir,n.log)),s[or]=Fn(s,t),this.onChild!==Mo&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[qe]=Object.create(null);for(let c in r)s[qe][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[qe][c]=r[c]}for(let c in e.serializers)s[qe][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[qe][c]=e.serializers[c]}}else s[qe]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[vt]=Pn(a||n.level,l||ir,c||n.log)}else s[vt]=Pn(n.level,ir,n.log);if(e.hasOwnProperty("customLevels")===!0&&(lp(this.levels,e.customLevels),s.levels=ip(e.customLevels,s[Jd]),ap(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=fp(s.redact,Oo),l={stringify:a[Xd]};s[Qd]=Oo,s[ep]=a,s[Zd]=l}if(typeof e.msgPrefix=="string"&&(s[Dn]=(this[Dn]||"")+e.msgPrefix),s[or]=Fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[Ln](a)}return this.onChild(s),s}function mp(){let e=`{${this[or].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function hp(t){let e=Fn(this,t);this[or]=e}function gp(t,e){return Object.assign(e,t)}function yp(t,e,r){let n=this[Vd](),s=this[Bd],i=this[Kd],o=this[Gd],a=this[Wd]||gp,l,c=this[tp].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Io](l,e,r,n),d=this[Ro];d[Yd]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[zd]),d.lastLogger=this),d.write(c?c(u):u)}function wp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Ro];typeof e.flush=="function"?e.flush(t||Mo):t&&t()}});var qo=R((Bn,No)=>{"use strict";var{hasOwnProperty:_t}=Object.prototype,Be=Un();Be.configure=Un;Be.stringify=Be;Be.default=Be;Bn.stringify=Be;Bn.configure=Un;No.exports=Be;var bp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ce(t){return t.length<5e3&&!bp.test(t)?`"${t}"`:JSON.stringify(t)}function Nn(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var xp=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function qn(t){return xp.call(t)!==void 0&&t.length!==0}function Do(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Sp(t){if(_t.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function vp(t){let e;if(_t.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function _p(t,e){let r;if(_t.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Fo(t,e){let r;if(_t.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ue(t){return t===1?"1 item":`${t} items`}function kp(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function $p(t){if(_t.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Un(t){t={...t};let e=$p(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Sp(t),n=_p(t,"bigint"),s=vp(t),i=typeof s=="function"?s:void 0,o=Fo(t,"maximumDepth"),a=Fo(t,"maximumBreadth");function l(p,f,h,g,S,b){let x=f[p];switch(typeof x=="object"&&x!==null&&typeof x.toJSON=="function"&&(x=x.toJSON(p)),x=g.call(f,p,x),typeof x){case"string":return Ce(x);case"object":{if(x===null)return"null";if(h.indexOf(x)!==-1)return r;let v="",E=",",_=b;if(Array.isArray(x)){if(x.length===0)return"[]";if(o<h.length+1)return'"[Array]"';h.push(x),S!==""&&(b+=S,v+=`
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Hs(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],n=i[3],s=i[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:e})}Ws.Command=tn});var Js=I(ie=>{var{Argument:zs}=zt(),{Command:rn}=Vs(),{CommanderError:Gc,InvalidArgumentError:Ks}=_t(),{Help:Jc}=Kr(),{Option:Gs}=Xr();ie.program=new rn;ie.createCommand=t=>new rn(t);ie.createOption=(t,e)=>new Gs(t,e);ie.createArgument=(t,e)=>new zs(t,e);ie.Command=rn;ie.Option=Gs;ie.Argument=zs;ie.Help=Jc;ie.CommanderError=Gc;ie.InvalidArgumentError=Ks;ie.InvalidOptionArgumentError=Ks});var on=I((Ly,ri)=>{"use strict";var kt=t=>t&&typeof t.message=="string",sn=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return kt(r)?r:void 0}else return kt(e)?e:void 0},ei=(t,e)=>{if(!kt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
|
|
24
|
+
causes have become circular...`;let n=sn(t);return n?(e.add(t),r+`
|
|
25
|
+
caused by: `+ei(n,e)):r},Yc=t=>ei(t,new Set),ti=(t,e,r)=>{if(!kt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=sn(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+ti(s,e,i)}else return n},Xc=t=>ti(t,new Set);ri.exports={isErrorLike:kt,getErrorCause:sn,stackWithCauses:Yc,messageWithCauses:Xc}});var an=I((Dy,si)=>{"use strict";var Qc=Symbol("circular-ref-tag"),Kt=Symbol("pino-raw-err-ref"),ni=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[Kt]},set:function(t){this[Kt]=t}}});Object.defineProperty(ni,Kt,{writable:!0,value:{}});si.exports={pinoErrProto:ni,pinoErrorSymbols:{seen:Qc,rawSymbol:Kt}}});var ai=I((Fy,oi)=>{"use strict";oi.exports=cn;var{messageWithCauses:Zc,stackWithCauses:eu,isErrorLike:ii}=on(),{pinoErrProto:tu,pinoErrorSymbols:ru}=an(),{seen:ln}=ru,{toString:nu}=Object.prototype;function cn(t){if(!ii(t))return t;t[ln]=void 0;let e=Object.create(tu);e.type=nu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Zc(t),e.stack=eu(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>cn(r)));for(let r in t)if(e[r]===void 0){let n=t[r];ii(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,ln)&&(e[r]=cn(n)):e[r]=n}return delete t[ln],e.raw=t,e}});var ci=I((Ny,li)=>{"use strict";li.exports=Jt;var{isErrorLike:un}=on(),{pinoErrProto:su,pinoErrorSymbols:iu}=an(),{seen:Gt}=iu,{toString:ou}=Object.prototype;function Jt(t){if(!un(t))return t;t[Gt]=void 0;let e=Object.create(su);e.type=ou.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))),un(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];un(n)?Object.prototype.hasOwnProperty.call(n,Gt)||(e[r]=Jt(n)):e[r]=n}return delete t[Gt],e.raw=t,e}});var pi=I((Uy,di)=>{"use strict";di.exports={mapHttpRequest:au,reqSerializer:fi};var fn=Symbol("pino-raw-req-ref"),ui=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[fn]},set:function(t){this[fn]=t}}});Object.defineProperty(ui,fn,{writable:!0,value:{}});function fi(t){let e=t.info||t.socket,r=Object.create(ui);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 au(t){return{req:fi(t)}}});var yi=I((qy,gi)=>{"use strict";gi.exports={mapHttpResponse:lu,resSerializer:mi};var dn=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[dn]},set:function(t){this[dn]=t}}});Object.defineProperty(hi,dn,{writable:!0,value:{}});function mi(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 lu(t){return{res:mi(t)}}});var hn=I((By,wi)=>{"use strict";var pn=ai(),cu=ci(),Yt=pi(),Xt=yi();wi.exports={err:pn,errWithCause:cu,mapHttpRequest:Yt.mapHttpRequest,mapHttpResponse:Xt.mapHttpResponse,req:Yt.reqSerializer,res:Xt.resSerializer,wrapErrorSerializer:function(e){return e===pn?e:function(n){return e(pn(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((Hy,bi)=>{"use strict";function uu(t,e){return e}bi.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=uu;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 $i=I((Wy,ki)=>{"use strict";function gn(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]=gn(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]=gn(t[r]));return e}return t}function xi(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 vi(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 fu(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 du(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 pu(t,e,r,n=!1){for(let s of e){let i=xi(s);if(i.includes("*"))_i(t,i,r,s,n);else if(n)vi(t,i);else{let o=fu(t,i);if(o===Qt)continue;let a=typeof r=="function"?r(o,i):r;Si(t,i,a)}}}function _i(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],f=typeof r=="function"?r(a[l],c):r;a[l]=f}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],f=typeof r=="function"?r(a[l],c):r;a[l]=f}}else hu(t,e,r,i,n,s)}function hu(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function c(f,d){if(d===o.length){if(Array.isArray(f))for(let h=0;h<f.length;h++)l[d]=h.toString(),c(f[h],d+1);else if(typeof f=="object"&&f!==null)for(let h in f)l[d]=h,c(f[h],d+1)}else if(d<o.length){let h=o[d];f&&typeof f=="object"&&f!==null&&h in f&&(l[d]=h,c(f[h],d+1))}else if(a.includes("*"))_i(f,a,typeof r=="function"?(p,u)=>{let g=[...l.slice(0,d),...u];return r(p,g)}:r,s,i);else if(i)vi(f,a);else{let h=typeof r=="function"?r(du(f,a),[...l.slice(0,d),...a]):r;Si(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 mu(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=xi(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 gu(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 yu(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 wu(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)yu(e)}function bu(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;wu(e);let o=mu(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let c=gu(l,o),f=l,d=r;return typeof r=="function"&&(d=r),pu(c,e,d,i),n===!1?(c.restore=function(){return gn(f)},c):typeof n=="function"?n(c):JSON.stringify(c)}}ki.exports=bu});var st=I((Vy,Ti)=>{"use strict";var xu=Symbol("pino.setLevel"),Su=Symbol("pino.getLevel"),vu=Symbol("pino.levelVal"),_u=Symbol("pino.levelComp"),ku=Symbol("pino.useLevelLabels"),$u=Symbol("pino.useOnlyCustomLevels"),Tu=Symbol("pino.mixin"),Cu=Symbol("pino.lsCache"),Eu=Symbol("pino.chindings"),Au=Symbol("pino.asJson"),Ou=Symbol("pino.write"),Ru=Symbol("pino.redactFmt"),Iu=Symbol("pino.time"),Pu=Symbol("pino.timeSliceIndex"),Mu=Symbol("pino.stream"),ju=Symbol("pino.stringify"),Lu=Symbol("pino.stringifySafe"),Du=Symbol("pino.stringifiers"),Fu=Symbol("pino.end"),Nu=Symbol("pino.formatOpts"),Uu=Symbol("pino.messageKey"),qu=Symbol("pino.errorKey"),Bu=Symbol("pino.nestedKey"),Hu=Symbol("pino.nestedKeyStr"),Wu=Symbol("pino.mixinMergeStrategy"),Vu=Symbol("pino.msgPrefix"),zu=Symbol("pino.wildcardFirst"),Ku=Symbol.for("pino.serializers"),Gu=Symbol.for("pino.formatters"),Ju=Symbol.for("pino.hooks"),Yu=Symbol.for("pino.metadata");Ti.exports={setLevelSym:xu,getLevelSym:Su,levelValSym:vu,levelCompSym:_u,useLevelLabelsSym:ku,mixinSym:Tu,lsCacheSym:Cu,chindingsSym:Eu,asJsonSym:Au,writeSym:Ou,serializersSym:Ku,redactFmtSym:Ru,timeSym:Iu,timeSliceIndexSym:Pu,streamSym:Mu,stringifySym:ju,stringifySafeSym:Lu,stringifiersSym:Du,endSym:Fu,formatOptsSym:Nu,messageKeySym:Uu,errorKeySym:qu,nestedKeySym:Bu,wildcardFirstSym:zu,needsMetadataGsym:Yu,useOnlyCustomLevelsSym:$u,formattersSym:Gu,hooksSym:Ju,nestedKeyStrSym:Hu,mixinMergeStrategySym:Wu,msgPrefixSym:Vu}});var wn=I((zy,Oi)=>{"use strict";var Ci=$i(),{redactFmtSym:Xu,wildcardFirstSym:Zt}=st(),yn=/[^.[\]]+|\[([^[\]]*?)\]/g,Ei="[Redacted]",Ai=!1;function Qu(t,e){let{paths:r,censor:n,remove:s}=Zu(t),i=r.reduce((l,c)=>{yn.lastIndex=0;let f=yn.exec(c),d=yn.exec(c),h=f[1]!==void 0?f[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):f[0];if(h==="*"&&(h=Zt),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!==Zt&&l[h].length===0&&l[h].push(...l[Zt]||[]),h===Zt&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(u)}),l[h].push(u),l},{}),o={[Xu]:Ci({paths:r,censor:n,serialize:e,strict:Ai,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=f=>a(f,[c]);else{let f=typeof n=="function"?(d,h)=>n(d,[c,...h]):n;l[c]=Ci({paths:i[c],censor:f,serialize:e,strict:Ai,remove:s})}return l},o)}function Zu(t){if(Array.isArray(t))return t={paths:t,censor:Ei},t;let{paths:e,censor:r=Ei,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}}Oi.exports=Qu});var Pi=I((Ky,Ii)=>{"use strict";var ef=()=>"",tf=()=>`,"time":${Date.now()}`,rf=()=>`,"time":${Math.round(Date.now()/1e3)}`,nf=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,sf=1000000n,Ri=1000000000n,of=BigInt(Date.now())*sf,af=process.hrtime.bigint(),lf=()=>{let t=process.hrtime.bigint()-af,e=of+t,r=e/Ri,n=e%Ri,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),f=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${f}:${d}.${n.toString().padStart(9,"0")}Z"`};Ii.exports={nullTime:ef,epochTime:tf,unixTime:rf,isoTime:nf,isoTimeNano:lf}});var ji=I((Gy,Mi)=>{"use strict";function cf(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Mi.exports=uf;function uf(t,e,r){var n=r&&r.stringify||cf,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",f=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Number(e[f]),d=p+2,p++;break;case 105:if(f>=l||e[f]==null)break;d<p&&(c+=t.slice(d,p)),c+=Math.floor(Number(e[f])),d=p+2,p++;break;case 79:case 111:case 106:if(f>=l||e[f]===void 0)break;d<p&&(c+=t.slice(d,p));var u=typeof e[f];if(u==="string"){c+="'"+e[f]+"'",d=p+2,p++;break}if(u==="function"){c+=e[f].name||"<anonymous>",d=p+2,p++;break}c+=n(e[f]),d=p+2,p++;break;case 115:if(f>=l)break;d<p&&(c+=t.slice(d,p)),c+=String(e[f]),d=p+2,p++;break;case 37:d<p&&(c+=t.slice(d,p)),c+="%",d=p+2,p++,f--;break}++f}++p}return d===-1?t:(d<h&&(c+=t.slice(d)),c)}});var xn=I((Jy,bn)=>{"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));bn.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(););};bn.exports=t}});var Hi=I((Yy,Bi)=>{"use strict";var N=require("fs"),ff=require("events"),df=require("util").inherits,Li=require("path"),vn=xn(),pf=require("assert"),er=100,tr=Buffer.allocUnsafe(0),hf=16*1024,Di="buffer",Fi="utf8",[mf,gf]=(process.versions.node||"0.0").split(".").map(Number),yf=mf>=22&&gf>=7;function Ni(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(Li.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(Li.dirname(t),{recursive:!0},i=>{if(i)return r(i);N.open(t,n,s,r)}):N.open(t,n,s,r)}function he(t){if(!(this instanceof he))return new he(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:f,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||hf,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===Di)this._writingBuf=tr,this.write=xf,this.flush=vf,this.flushSync=kf,this._actualWrite=Tf,u=()=>N.writeSync(this.fd,this._writingBuf),g=()=>N.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Fi)this._writingBuf="",this.write=bf,this.flush=Sf,this.flushSync=_f,this._actualWrite=$f,u=()=>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 "${Fi}" and "${Di}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Ni(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,b)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{vn(er),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(g,er);else this._writing=!1,this.emit("error",m);return}this.emit("write",b);let x=Sn(this._writingBuf,this._len,b);if(this._len=x.len,this._writingBuf=x.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let v=u(),_=Sn(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&N.fsyncSync(this.fd);let 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,rr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(wf,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 Sn(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 wf(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}df(he,ff);function Ui(t,e){return t.length===0?tr:t.length===1?t[0]:Buffer.concat(t,e)}function bf(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 xf(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 qi(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 Sf(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&qi.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function vf(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&&qi.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&&N.close(e,r=>{if(r)return this.emit("error",r)})}),Ni(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():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=Sn(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 kf(){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=Ui(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)}}}he.prototype.destroy=function(){this.destroyed||rr(this)};function $f(){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 Tf(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Ui(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 yf&&(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=[],pf(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")}}he.SonicBoom=he;he.default=he;Bi.exports=he});var _n=I((Xy,Gi)=>{"use strict";var me={exit:[],beforeExit:[]},Wi={exit:Af,beforeExit:Of},it;function Cf(){it===void 0&&(it=new FinalizationRegistry(Rf))}function Ef(t){me[t].length>0||process.on(t,Wi[t])}function Vi(t){me[t].length>0||(process.removeListener(t,Wi[t]),me.exit.length===0&&me.beforeExit.length===0&&(it=void 0))}function Af(){zi("exit")}function Of(){zi("beforeExit")}function zi(t){for(let e of me[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}me[t]=[]}function Rf(t){for(let e of["exit","beforeExit"]){let r=me[e].indexOf(t);me[e].splice(r,r+1),Vi(e)}}function Ki(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Ef(t);let n=new WeakRef(e);n.fn=r,Cf(),it.register(e,n),me[t].push(n)}function If(t,e){Ki("exit",t,e)}function Pf(t,e){Ki("beforeExit",t,e)}function Mf(t){if(it!==void 0){it.unregister(t);for(let e of["exit","beforeExit"])me[e]=me[e].filter(r=>{let n=r.deref();return n&&n!==t}),Vi(e)}}Gi.exports={register:If,registerBeforeExit:Pf,unregister:Mf}});var Ji=I((Qy,jf)=>{jf.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 Xi=I((Zy,Yi)=>{"use strict";function Lf(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 Df(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(f=>{if(f==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Yi.exports={wait:Lf,waitDiff:Df}});var Zi=I((ew,Qi)=>{"use strict";Qi.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var fo=I((tw,uo)=>{"use strict";var{version:Ff}=Ji(),{EventEmitter:Nf}=require("events"),{Worker:Uf}=require("worker_threads"),{join:qf}=require("path"),{pathToFileURL:Bf}=require("url"),{wait:Hf}=Xi(),{WRITE_INDEX:ve,READ_INDEX:Be,SEQ_INDEX:kn}=Zi(),Wf=require("buffer"),Vf=require("assert"),S=Symbol("kImpl"),zf=Wf.constants.MAX_STRING_LENGTH;function eo(){}function En(t,e){Atomics.add(t[S].state,kn,1),e(),Atomics.add(t[S].state,kn,1),Atomics.notify(t[S].state,kn)}function to(t){En(t,()=>{Atomics.store(t[S].state,Be,0),Atomics.store(t[S].state,ve,0)})}var $t=class{constructor(e){this._value=e}deref(){return this._value}},nr=class{register(){}unregister(){}},Kf=process.env.NODE_V8_COVERAGE?nr:global.FinalizationRegistry||nr,Gf=process.env.NODE_V8_COVERAGE?$t:global.WeakRef||$t,ro=new Kf(t=>{t.exited||t.terminate()});function Jf(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||qf(__dirname,"lib","worker.js"),o=new Uf(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Bf(r).href,dataBuf:t[S].dataBuf,stateBuf:t[S].stateBuf,workerData:{$context:{threadStreamVersion:Ff},...n}}});return o.stream=new $t(t),o.on("message",Yf),o.on("exit",io),ro.register(t,o),o}function no(t){Vf(!t[S].sync),t[S].needDrain&&(t[S].needDrain=!1,t.emit("drain"))}function so(t){for(;;){let e=Atomics.load(t[S].state,ve),r=t[S].data.length-e;if(r>0){if(t[S].bufLen===0){t[S].flushing=!1,t[S].ending?An(t):t[S].needDrain&&process.nextTick(no,t);return}lo(t,r,eo);continue}if(r===0){if(e===0&&t[S].bufLen===0)return;sr(t,()=>{t.destroyed||(to(t),so(t))});return}ae(t,new Error("overwritten"));return}}function Yf(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 Gf(e),sr(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 io(t){let e=this.stream.deref();e!==void 0&&(ro.unregister(e),e.worker.exited=!0,e.worker.off("exit",io),ae(e,t!==0?new Error("the worker thread exited"):null))}var Tn=class extends Nf{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=Jf(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[S].destroyed)return Cn(this,new Error("the worker has exited")),!1;if(this[S].ending)return Cn(this,new Error("the worker is ending")),!1;if(this[S].flushing&&this[S].bufLen+r.length>=zf)try{$n(this),this[S].flushing=!0}catch(n){return ae(this,n),!1}if(this[S].buf.push(r),this[S].bufLen+=r.length,this[S].sync)try{return $n(this),!0}catch(n){return ae(this,n),!1}return this[S].flushing||(this[S].flushing=!0,setImmediate(so,this)),this[S].needDrain=this[S].data.length-this[S].bufLen-Atomics.load(this[S].state,ve)<=0,!this[S].needDrain}end(){this[S].destroyed||(this[S].ending=!0,An(this))}flush(e){e=typeof e=="function"?e:eo,oo(this,r=>{if(r){process.nextTick(e,r);return}ao(this,e)})}flushSync(){this[S].destroyed||($n(this),co(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 oo(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(oo,t,e);return}sr(t,e)}function sr(t,e){let r=Atomics.load(t[S].state,ve);Hf(t[S].state,Be,r,1/0,(n,s)=>{if(n){ae(t,n),e(n);return}if(s!=="ok"){sr(t,e);return}e()})}function ao(t,e){if(t[S].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[S].ready){let n=()=>{i(),ao(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[S].nextFlushId;t[S].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[S].flushCallbacks.delete(r),ae(t,n),process.nextTick(e,n)}}function Xf(t,e){let r=t[S].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 Cn(t,e){setImmediate(()=>{t.emit("error",e)})}function ae(t,e){t[S].destroyed||(t[S].destroyed=!0,Xf(t,e),e&&(t[S].errored=e,Cn(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 lo(t,e,r){let s=Atomics.load(t[S].state,ve),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,s),s+=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,s,0,i),t[S].buf[o]=a.subarray(i),t[S].bufLen-=i,s+=i,i=0}return En(t,()=>{Atomics.store(t[S].state,ve,s)}),r(),!0}function An(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);En(t,()=>{Atomics.store(t[S].state,ve,-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 $n(t){let e=()=>{t[S].ending?An(t):t[S].needDrain&&process.nextTick(no,t)};for(t[S].flushing=!1;t[S].bufLen!==0;){let r=Atomics.load(t[S].state,ve),n=t[S].data.length-r;if(n===0){co(t),to(t);continue}else if(n<0)throw new Error("overwritten");lo(t,n,e)}}function co(t){if(t[S].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[S].state,ve),r=0;for(;;){let n=Atomics.load(t[S].state,Be);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[S].state,Be,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}uo.exports=Tn});var In=I((rw,mo)=>{"use strict";var{createRequire:Qf}=require("module"),{existsSync:Zf}=require("node:fs"),ed=mn(),{join:On,isAbsolute:ho,sep:td}=require("node:path"),{fileURLToPath:rd}=require("node:url"),nd=xn(),Rn=_n(),sd=fo();function id(t){Rn.register(t,ud),Rn.registerBeforeExit(t,fd),t.on("close",function(){Rn.unregister(t)})}function od(){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 ad(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&&po(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(po(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function po(t){let e=ld(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=rd(r)}catch{return!1}return ho(r)&&!Zf(r)}function ld(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function cd(t,e,r,n,s){if(!r.execArgv&&od()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=ad(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new sd({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&&id(i)}function a(){i.closed||(i.flushSync(),nd(100),i.end())}return i}function ud(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function fd(t){t.flushSync()}function dd(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=ed(),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"]||On(__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"]||On(__dirname,"worker.js"),l.pipelines=[e.map(u=>({...u,target:p(u.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return cd(p(d),l,i,a,h);function p(u){if(u=f[u]||u,ho(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return On(__dirname,"..","file.js");let g;for(let m of c)try{let b=m==="node:repl"?process.cwd()+td:m;g=Qf(b).resolve(u);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${u}"`);return g}}mo.exports=dd});var ar=I((nw,Eo)=>{"use strict";var pd=require("node:diagnostics_channel"),go=ji(),{mapHttpRequest:hd,mapHttpResponse:md}=hn(),Mn=Hi(),yo=_n(),{lsCacheSym:gd,chindingsSym:vo,writeSym:wo,serializersSym:_o,formatOptsSym:bo,endSym:yd,stringifiersSym:ko,stringifySym:$o,stringifySafeSym:jn,wildcardFirstSym:To,nestedKeySym:wd,formattersSym:Co,messageKeySym:bd,errorKeySym:xd,nestedKeyStrSym:Sd,msgPrefixSym:ir}=st(),{isMainThread:vd}=require("worker_threads"),_d=In(),[kd]=process.versions.node.split(".").map(t=>Number(t)),xo=pd.tracingChannel("pino_asJson"),Pn=kd>=25?t=>JSON.stringify(t):Td;function ot(){}function $d(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=hd(n):typeof n.setHeader=="function"&&(n=md(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[wo](n,go(i,o,this[bo]),t)}else{let i=n===void 0?s.shift():n;typeof this[ir]=="string"&&i!==void 0&&i!==null&&(i=this[ir]+i),this[wo](null,go(i,s,this[bo]),t)}}}function Td(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 Cd(t,e,r,n){if(xo.hasSubscribers===!1)return So.call(this,t,e,r,n);let s={instance:this,arguments};return xo.traceSync(So,s,this,t,e,r,n)}function So(t,e,r,n){let s=this[$o],i=this[jn],o=this[ko],a=this[yd],l=this[vo],c=this[_o],f=this[Co],d=this[bd],h=this[xd],p=this[gd][r]+n;p=p+l;let u;f.log&&(t=f.log(t));let g=o[To],m="";for(let x in t)if(u=t[x],Object.prototype.hasOwnProperty.call(t,x)&&u!==void 0){c[x]?u=c[x](u):x===h&&c.err&&(u=c.err(u));let w=o[x]||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||Pn)(u);break;default:u=(w||s)(u,i)}if(u===void 0)continue;let v=Pn(x);m+=","+v+":"+u}let b="";if(e!==void 0){u=c[d]?c[d](e):e;let x=o[d]||g;switch(typeof u){case"function":break;case"number":Number.isFinite(u)===!1&&(u=null);case"boolean":x&&(u=x(u)),b=',"'+d+'":'+u;break;case"string":u=(x||Pn)(u),b=',"'+d+'":'+u;break;default:u=(x||s)(u,i),b=',"'+d+'":'+u}}return this[wd]&&m?p+this[Sd]+m.slice(1)+"}"+b+a:p+m+b+a}function Ed(t,e){let r,n=t[vo],s=t[$o],i=t[jn],o=t[ko],a=o[To],l=t[_o],c=t[Co].bindings;e=c(e);for(let f in e)if(r=e[f],((f.length<5||f!=="level"&&f!=="serializers"&&f!=="formatters"&&f!=="customLevels")&&e.hasOwnProperty(f)&&r!==void 0)===!0){if(r=l[f]?l[f](r):r,r=(o[f]||a||s)(r,i),r===void 0)continue;n+=',"'+f+'":'+r}return n}function Ad(t){return t.write!==t.constructor.prototype.write}function or(t){let e=new Mn(t);return e.on("error",r),!t.sync&&vd&&(yo.register(e,Od),e.on("close",function(){yo.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=ot,e.end=ot,e.flushSync=ot,e.destroy=ot;return}e.removeListener("error",r),e.emit("error",n)}}function Od(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Rd(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=ot),i||(Ad(process.stdout)?i=process.stdout:i=or({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Id(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 Md(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Eo.exports={noop:ot,buildSafeSonicBoom:or,asChindings:Ed,asJson:Cd,genLog:$d,createArgsNormalizer:Rd,stringify:Id,buildFormatters:Pd,normalizeDestFileDescriptor:Md}});var lr=I((sw,Ao)=>{var jd={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Ld={ASC:"ASC",DESC:"DESC"};Ao.exports={DEFAULT_LEVELS:jd,SORTING_ORDER:Ld}});var Fn=I((iw,Po)=>{"use strict";var{lsCacheSym:Dd,levelValSym:Ln,useOnlyCustomLevelsSym:Fd,streamSym:Nd,formattersSym:Ud,hooksSym:qd,levelCompSym:Oo}=st(),{noop:Bd,genLog:He}=ar(),{DEFAULT_LEVELS:be,SORTING_ORDER:Ro}=lr(),Io={fatal:t=>{let e=He(be.fatal,t);return function(...r){let n=this[Nd];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>He(be.error,t),warn:t=>He(be.warn,t),info:t=>He(be.info,t),debug:t=>He(be.debug,t),trace:t=>He(be.trace,t)},Dn=Object.keys(be).reduce((t,e)=>(t[be[e]]=e,t),{}),Hd=Object.keys(Dn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Wd(t){let e=t[Ud].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[Dd]=n,t}function Vd(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 zd(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[Ln],s=this[Ln]=r[t],i=this[Fd],o=this[Oo],a=this[qd].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=Bd;continue}this[l]=Vd(l,i)?Io[l](a):He(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function Kd(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function Gd(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Oo](r,this[Ln])}function Jd(t,e,r){return t===Ro.DESC?e<=r:e>=r}function Yd(t){return typeof t=="string"?Jd.bind(null,t):t}function Xd(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:Dn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:be,t);return{labels:n,values:s}}function Qd(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Dn).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 Zd(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 ep(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Ro).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Po.exports={initialLsCache:Hd,genLsCache:Wd,levelMethods:Io,getLevel:Kd,setLevel:zd,isLevelEnabled:Gd,mappings:Xd,assertNoLevelCollisions:Zd,assertDefaultLevelFound:Qd,genLevelComparison:Yd,assertLevelComparison:ep}});var Nn=I((ow,Mo)=>{"use strict";Mo.exports={version:"10.3.1"}});var Bo=I((lw,qo)=>{"use strict";var{EventEmitter:tp}=require("node:events"),{lsCacheSym:rp,levelValSym:np,setLevelSym:qn,getLevelSym:jo,chindingsSym:ur,mixinSym:sp,asJsonSym:Do,writeSym:ip,mixinMergeStrategySym:op,timeSym:ap,timeSliceIndexSym:lp,streamSym:Fo,serializersSym:We,formattersSym:Tt,errorKeySym:cp,messageKeySym:up,useOnlyCustomLevelsSym:fp,needsMetadataGsym:dp,redactFmtSym:pp,stringifySym:hp,formatOptsSym:mp,stringifiersSym:gp,msgPrefixSym:Bn,hooksSym:yp}=st(),{getLevel:wp,setLevel:bp,isLevelEnabled:xp,mappings:Sp,initialLsCache:vp,genLsCache:_p,assertNoLevelCollisions:kp}=Fn(),{asChindings:Hn,asJson:$p,buildFormatters:Un,stringify:Lo,noop:No}=ar(),{version:Tp}=Nn(),Cp=wn(),Ep=class{},Uo={constructor:Ep,child:Ap,bindings:Op,setBindings:Rp,flush:Mp,isLevelEnabled:xp,version:Tp,get level(){return this[jo]()},set level(t){this[qn](t)},get levelVal(){return this[np]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[Bn]},get[Symbol.toStringTag](){return"Pino"},[rp]:vp,[ip]:Pp,[Do]:$p,[jo]:wp,[qn]:bp};Object.setPrototypeOf(Uo,tp.prototype);qo.exports=function(){return Object.create(Uo)};var cr=t=>t;function Ap(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[We],n=this[Tt],s=Object.create(this);if(e==null)return s[Tt].bindings!==cr&&(s[Tt]=Un(n.level,cr,n.log)),s[ur]=Hn(s,t),this.onChild!==No&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[We]=Object.create(null);for(let c in r)s[We][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];s[We][c]=r[c]}for(let c in e.serializers)s[We][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];s[We][c]=e.serializers[c]}}else s[We]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;s[Tt]=Un(a||n.level,l||cr,c||n.log)}else s[Tt]=Un(n.level,cr,n.log);if(e.hasOwnProperty("customLevels")===!0&&(kp(this.levels,e.customLevels),s.levels=Sp(e.customLevels,s[fp]),_p(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=Cp(s.redact,Lo),l={stringify:a[pp]};s[hp]=Lo,s[gp]=a,s[mp]=l}if(typeof e.msgPrefix=="string"&&(s[Bn]=(this[Bn]||"")+e.msgPrefix),s[ur]=Hn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[qn](a)}return this.onChild(s),s}function Op(){let e=`{${this[ur].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Rp(t){let e=Hn(this,t);this[ur]=e}function Ip(t,e){return Object.assign(e,t)}function Pp(t,e,r){let n=this[ap](),s=this[sp],i=this[cp],o=this[up],a=this[op]||Ip,l,c=this[yp].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let f=this[Do](l,e,r,n),d=this[Fo];d[dp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[lp]),d.lastLogger=this),d.write(c?c(f):f)}function Mp(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Fo];typeof e.flush=="function"?e.flush(t||No):t&&t()}});var zo=I((Kn,Vo)=>{"use strict";var{hasOwnProperty:Ct}=Object.prototype,ze=zn();ze.configure=zn;ze.stringify=ze;ze.default=ze;Kn.stringify=ze;Kn.configure=zn;Vo.exports=ze;var jp=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ie(t){return t.length<5e3&&!jp.test(t)?`"${t}"`:JSON.stringify(t)}function Wn(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 Lp=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function Vn(t){return Lp.call(t)!==void 0&&t.length!==0}function Ho(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 Dp(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 Fp(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 Np(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 Wo(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 Ve(t){return t===1?"1 item":`${t} items`}function Up(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function qp(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 zn(t){t={...t};let e=qp(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Dp(t),n=Np(t,"bigint"),s=Fp(t),i=typeof s=="function"?s:void 0,o=Wo(t,"maximumDepth"),a=Wo(t,"maximumBreadth");function l(p,u,g,m,b,x){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=x;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(w),b!==""&&(x+=b,v+=`
|
|
26
|
+
${x}`,_=`,
|
|
27
|
+
${x}`);let F=Math.min(w.length,a),z=0;for(;z<F-1;z++){let ee=l(String(z),w,g,m,b,x);v+=ee!==void 0?ee:"null",v+=_}let J=l(String(z),w,g,m,b,x);if(v+=J!==void 0?J:"null",w.length-1>a){let ee=w.length-a-1;v+=`${_}"... ${Ve(ee)} not stringified"`}return b!==""&&(v+=`
|
|
28
|
+
${C}`),g.pop(),`[${v}]`}let E=Object.keys(w),R=E.length;if(R===0)return"{}";if(o<g.length+1)return'"[Object]"';let T="",j="";b!==""&&(x+=b,_=`,
|
|
29
|
+
${x}`,T=" ");let B=Math.min(R,a);s&&!Vn(w)&&(E=Wn(E,i)),g.push(w);for(let F=0;F<B;F++){let z=E[F],J=l(z,w,g,m,b,x);J!==void 0&&(v+=`${j}${Ie(z)}:${T}${J}`,j=_)}if(R>a){let F=R-a;v+=`${j}"...":${T}"${Ve(F)} not stringified"`,j=_}return b!==""&&j.length>1&&(v=`
|
|
30
|
+
${x}${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(n)return String(w);default:return e?e(w):void 0}}function c(p,u,g,m,b,x){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=x,v="",_=",";if(Array.isArray(u)){if(u.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(u),b!==""&&(x+=b,v+=`
|
|
32
|
+
${x}`,_=`,
|
|
33
|
+
${x}`);let R=Math.min(u.length,a),T=0;for(;T<R-1;T++){let B=c(String(T),u[T],g,m,b,x);v+=B!==void 0?B:"null",v+=_}let j=c(String(T),u[T],g,m,b,x);if(v+=j!==void 0?j:"null",u.length-1>a){let B=u.length-a-1;v+=`${_}"... ${Ve(B)} not stringified"`}return b!==""&&(v+=`
|
|
34
|
+
${w}`),g.pop(),`[${v}]`}g.push(u);let C="";b!==""&&(x+=b,_=`,
|
|
35
|
+
${x}`,C=" ");let E="";for(let R of m){let T=c(R,u[R],g,m,b,x);T!==void 0&&(v+=`${E}${Ie(R)}:${C}${T}`,E=_)}return b!==""&&E.length>1&&(v=`
|
|
36
|
+
${x}${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(n)return String(u);default:return e?e(u):void 0}}function f(p,u,g,m,b){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,b);if(u===null)return"null"}if(g.indexOf(u)!==-1)return r;let x=b;if(Array.isArray(u)){if(u.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(u),b+=m;let T=`
|
|
38
|
+
${b}`,j=`,
|
|
39
|
+
${b}`,B=Math.min(u.length,a),F=0;for(;F<B-1;F++){let J=f(String(F),u[F],g,m,b);T+=J!==void 0?J:"null",T+=j}let z=f(String(F),u[F],g,m,b);if(T+=z!==void 0?z:"null",u.length-1>a){let J=u.length-a-1;T+=`${j}"... ${Ve(J)} not stringified"`}return T+=`
|
|
40
|
+
${x}`,g.pop(),`[${T}]`}let w=Object.keys(u),v=w.length;if(v===0)return"{}";if(o<g.length+1)return'"[Object]"';b+=m;let _=`,
|
|
41
|
+
${b}`,C="",E="",R=Math.min(v,a);Vn(u)&&(C+=Ho(u,_,a),w=w.slice(u.length),R-=u.length,E=_),s&&(w=Wn(w,i)),g.push(u);for(let T=0;T<R;T++){let j=w[T],B=f(j,u[j],g,m,b);B!==void 0&&(C+=`${E}${Ie(j)}: ${B}`,E=_)}if(v>a){let T=v-a;C+=`${E}"...": "${Ve(T)} not stringified"`,E=_}return E!==""&&(C=`
|
|
42
|
+
${b}${C}
|
|
43
|
+
${x}`),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(n)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="",b=u.length!==void 0;if(b&&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 R=d(String(E),u[E],g);if(m+=R!==void 0?R:"null",u.length-1>a){let T=u.length-a-1;m+=`,"... ${Ve(T)} not stringified"`}return g.pop(),`[${m}]`}let x=Object.keys(u),w=x.length;if(w===0)return"{}";if(o<g.length+1)return'"[Object]"';let v="",_=Math.min(w,a);b&&Vn(u)&&(m+=Ho(u,",",a),x=x.slice(u.length),_-=u.length,v=","),s&&(x=Wn(x,i)),g.push(u);for(let C=0;C<_;C++){let E=x[C],R=d(E,u[E],g);R!==void 0&&(m+=`${v}${Ie(E)}:${R}`,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(n)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,[],Up(u),m,"")}if(m.length!==0)return f("",p,[],m,"")}return d("",p,[])}return h}});var Yo=I((cw,Jo)=>{"use strict";var Gn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Go}=lr(),Bp=Go.info;function Hp(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Go);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:f,[Gn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let h,p=this.lastLevel,{streams:u}=this,g=0,m;for(let b=Wp(u.length,e.dedupe);zp(b,u.length,e.dedupe);b=Vp(b,e.dedupe))if(h=u[b],h.level<=p){if(g!==0&&g!==h.level)break;if(m=h.stream,m[Gn]){let{lastTime:x,lastMsg:w,lastObj:v,lastLogger:_}=this;m.lastLevel=p,m.lastTime=x,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 n;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams: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=Bp;let b={stream:p,level:m,levelVal:void 0,id:++n.lastId};return u.unshift(b),u.sort(Ko),this.minLevel=u[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(u=>u.id===d);return p>=0&&(h.splice(p,1),h.sort(Ko),this.minLevel=h.length>0?h[0].level:-1),n}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function f(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:f,emit:i,flushSync:o,[Gn]:!0}}}function Ko(t,e){return t.level-e.level}function Wp(t,e){return e?t-1:0}function Vp(t,e){return e?t-1:t+1}function zp(t,e,r){return r?t>=0:t<e}Jo.exports=Hp});var ua=I((uw,le)=>{"use strict";var Kp=require("node:os"),sa=hn(),Gp=mn(),Jp=wn(),ia=Pi(),Yp=Bo(),oa=st(),{configure:Xp}=zo(),{assertDefaultLevelFound:Qp,mappings:aa,genLsCache:Zp,genLevelComparison:eh,assertLevelComparison:th}=Fn(),{DEFAULT_LEVELS:la,SORTING_ORDER:rh}=lr(),{createArgsNormalizer:nh,asChindings:sh,buildSafeSonicBoom:Xo,buildFormatters:ih,stringify:Jn,normalizeDestFileDescriptor:Qo,noop:oh}=ar(),{version:ah}=Nn(),{chindingsSym:Zo,redactFmtSym:lh,serializersSym:ea,timeSym:ch,timeSliceIndexSym:uh,streamSym:fh,stringifySym:ta,stringifySafeSym:Yn,stringifiersSym:ra,setLevelSym:dh,endSym:ph,formatOptsSym:hh,messageKeySym:mh,errorKeySym:gh,nestedKeySym:yh,mixinSym:wh,levelCompSym:bh,useOnlyCustomLevelsSym:xh,formattersSym:na,hooksSym:Sh,nestedKeyStrSym:vh,mixinMergeStrategySym:_h,msgPrefixSym:kh}=oa,{epochTime:ca,nullTime:$h}=ia,{pid:Th}=process,Ch=Kp.hostname(),Eh=sa.err,Ah={level:"info",levelComparison:rh.ASC,levels:la,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Th,hostname:Ch},serializers:Object.assign(Object.create(null),{err:Eh}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:ca,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Oh=nh(Ah),Rh=Object.assign(Object.create(null),sa);function Xn(...t){let e={},{opts:r,stream:n}=Oh(e,Gp(),...t);r.level&&typeof r.level=="string"&&la[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:f,base:d,name:h,level:p,customLevels:u,levelComparison:g,mixin:m,mixinMergeStrategy:b,useOnlyCustomLevels:x,formatters:w,hooks:v,depthLimit:_,edgeLimit:C,onChild:E,msgPrefix:R}=r,T=Xp({maximumDepth:_,maximumBreadth:C}),j=ih(w.level,w.bindings,w.log),B=Jn.bind({[Yn]:T}),F=s?Jp(s,B):{},z=s?{stringify:F[lh]}:{stringify:B},J="}"+(i?`\r
|
|
44
44
|
`:`
|
|
45
|
-
`),
|
|
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 n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function
|
|
49
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
50
|
-
`);if(
|
|
45
|
+
`),ee=sh.bind(null,{[Zo]:"",[ea]:o,[ra]:F,[ta]:Jn,[Yn]:T,[na]:j}),se="";d!==null&&(h===void 0?se=ee(d):se=ee(Object.assign({},d,{name:h})));let M=a instanceof Function?a:a?ca:$h,D=M().indexOf(":")+1;if(x&&!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(R&&typeof R!="string")throw Error(`Unknown msgPrefix type "${typeof R}" - expected "string"`);Qp(p,u,x);let Wt=aa(u,x);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:Wt,messageKey:l,errorKey:c}}),th(g);let Ls=eh(g);return Object.assign(e,{levels:Wt,[bh]:Ls,[xh]:x,[fh]:n,[ch]:M,[uh]:D,[ta]:Jn,[Yn]:T,[ra]:F,[ph]:J,[hh]:z,[mh]:l,[gh]:c,[yh]:f,[vh]:f?`,${JSON.stringify(f)}:{`:"",[ea]:o,[wh]:m,[_h]:b,[Zo]:se,[na]:j,[Sh]:v,silent:oh,onChild:E,[kh]:R}),Object.setPrototypeOf(e,Yp()),Zp(e),e[dh](p),e}le.exports=Xn;le.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Qo(t.dest||process.stdout.fd),Xo(t)):Xo({dest:Qo(t),minLength:0});le.exports.transport=In();le.exports.multistream=Yo();le.exports.levels=aa();le.exports.stdSerializers=Rh;le.exports.stdTimeFunctions=Object.assign({},ia);le.exports.symbols=oa;le.exports.version=ah;le.exports.default=Xn;le.exports.pino=Xn});var Ys=$(Js(),1),{program:xy,createCommand:Sy,createArgument:vy,createOption:_y,CommanderError:ky,InvalidArgumentError:$y,InvalidOptionArgumentError:Ty,Command:Xs,Argument:Cy,Option:Ey,Help:Ay}=Ys.default;var pe=$(require("fs")),qe=$(require("path")),Qs=$(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(Qs.homedir(),".hablas"),nn=qe.join(tt,"config.json");function rt(t={}){let e={};if(pe.existsSync(nn))try{e=JSON.parse(pe.readFileSync(nn,"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 n=process.env.HABLAS_PROVIDER;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=qe.resolve(t.project)),t.provider){let n=t.provider;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function nt(t){pe.existsSync(tt)||pe.mkdirSync(tt,{recursive:!0}),pe.writeFileSync(nn,JSON.stringify(t,null,2),"utf-8")}function Zs(){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 Qn=$(ua()),Zn=$(require("path")),fa=$(require("os")),fr=$(require("fs"));function es(t){let e=Zn.join(fa.homedir(),".hablas","logs");fr.existsSync(e)||fr.mkdirSync(e,{recursive:!0});let r=Zn.join(e,`session-${Date.now()}.log`);return(0,Qn.default)({level:"info"},Qn.default.destination({dest:r,sync:!1}))}var dr=$(require("fs")),Et=$(require("path"));function da(){let t=[Et.resolve(__dirname,"..","package.json"),Et.resolve(__dirname,"..","..","package.json"),Et.resolve(process.cwd(),"package.json"),Et.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(dr.existsSync(e)){let r=JSON.parse(dr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var dc=$(require("fs")),pc=$(require("path"));var pr=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
|
|
46
|
+
`);o=c.pop()||"";for(let f of c)if(f.trim())try{let d=JSON.parse(f);d.message?.content&&(yield d.message.content)}catch{}}}};var pa=12e4,Ih=6e4,hr=3,ha=1e3,Ph=20;function ma(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(n=>n?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((n,s)=>({id:`call_${s}`,type:"function",function:{name:n.function?.name||"",arguments:JSON.stringify(n.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Mh(t){return t.map(e=>({type:"function",function:e.function}))}function jh(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 ga(t){return new Promise(e=>setTimeout(e,t))}function ya(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var At=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,n,s=0;for(;r&&s<Ph;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Ih)});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?(n=f[f.length-1],s++):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,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ma(e)};r.length>0&&(i.tools=Mh(r),i.tool_choice="auto");let o=null;for(let a=0;a<=hr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),pa),f={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,f);if(clearTimeout(c),!d.ok){let g=await d.text().catch(()=>"");if(!ya(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<hr){let m=ha*Math.pow(2,a);await ga(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?jh(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"&&n?.aborted)throw d;if(ya(d)&&(o=d,a<hr)){let h=ha*Math.pow(2,a);await ga(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=hr)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:ma(e),stream:!0}),signal:r||AbortSignal.timeout(pa)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let f=a.split(`
|
|
47
|
+
`);a=f.pop()||"";for(let d of f){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let u=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;u&&(yield u)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function at(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:oe.apiUrl};return new At(e)}return t.provider==="custom"&&t.apiUrl?new At(t):new pr(t)}function 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 U=$(require("fs/promises")),ls=$(require("fs")),Pe=$(require("path"));function _e(){}_e.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(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;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n: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,b=1/0;function x(){for(var v=Math.max(m,-f);v<=Math.min(b,f);v+=2){var _=void 0,C=u[v-1],E=u[v+1];C&&(u[v-1]=void 0);var R=!1;if(E){var T=E.oldPos-v;R=E&&0<=T&&T<l}var j=C&&C.oldPos+1<c;if(!R&&!j){u[v]=void 0;continue}if(!j||R&&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(Lh(o,_.lastComponent,r,e,o.useLongestToken));u[v]=_,_.oldPos+1>=c&&(b=Math.min(b,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();x()||v()},0)})();else for(;f<=d&&Date.now()<=p;){var w=x();if(w)return w}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Lh(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,f=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.slice(f,f+d.count)),f+=d.count,a&&i[a-1].added){var p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=r.slice(c,c+d.count);h=h.map(function(g,m){var b=n[f+m];return b.length>g.length?b: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 $w=new _e;var wa=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,ba=/\S/,xa=new _e;xa.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!ba.test(t)&&!ba.test(e)};xa.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]&&wa.test(e[r])&&wa.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var is=new _e;is.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
48
|
+
`));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function Dh(t,e,r){return is.diff(t,e,r)}var Fh=new _e;Fh.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Nh=new _e;Nh.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function mr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?mr=function(e){return typeof e}:mr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},mr(t)}function ts(t){return Uh(t)||qh(t)||Bh(t)||Hh()}function Uh(t){if(Array.isArray(t))return rs(t)}function qh(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Bh(t,e){if(t){if(typeof t=="string")return rs(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 rs(t,e)}}function rs(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Hh(){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 Wh=Object.prototype.toString,Ot=new _e;Ot.useLongestToken=!0;Ot.tokenize=is.tokenize;Ot.castInput=function(t){var e=this.options,r=e.undefinedReplacement,n=e.stringifyReplacer,s=n===void 0?function(i,o){return typeof o>"u"?r:o}:n;return typeof t=="string"?t:JSON.stringify(ns(t,null,null,s),s," ")};Ot.equals=function(t,e){return _e.prototype.equals.call(Ot,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function ns(t,e,r,n,s){e=e||[],r=r||[],n&&(t=n(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(Wh.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]=ns(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),mr(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]=ns(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var ss=new _e;ss.tokenize=function(t){return t.slice()};ss.join=ss.removeEmpty=function(t){return t};function Vh(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Dh(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(b){return b.map(function(x){return" "+x})}for(var c=[],f=0,d=0,h=[],p=1,u=1,g=function(x){var w=a[x],v=w.lines||w.value.replace(/\n$/,"").split(`
|
|
50
|
+
`);if(w.lines=v,w.added||w.removed){var _;if(!f){var C=a[x-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(_,ts(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&&x<a.length-2){var E;(E=h).push.apply(E,ts(l(v)))}else{var R,T=Math.min(v.length,o.context);(R=h).push.apply(R,ts(l(v.slice(0,T))));var j={oldStart:f,oldLines:p-f+T,newStart:d,newLines:u-d+T,lines:h};if(x>=a.length-2&&v.length<=o.context){var B=/\n$/.test(r),F=/\n$/.test(n),z=v.length==0&&h.length>j.oldLines;!B&&z&&r.length>0&&h.splice(j.oldLines,0,"\"),(!B&&!z||!F)&&h.push("\")}c.push(j),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:s,newHeader:i,hunks:c}}function Sa(t){if(Array.isArray(t))return t.map(Sa).join(`
|
|
51
51
|
`);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var n=t.hunks[r];n.oldLines===0&&(n.oldStart-=1),n.newLines===0&&(n.newStart-=1),e.push("@@ -"+n.oldStart+","+n.oldLines+" +"+n.newStart+","+n.newLines+" @@"),e.push.apply(e,n.lines)}return e.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`}function
|
|
54
|
-
`),
|
|
55
|
-
... [Partial read. Total lines: ${
|
|
56
|
-
${
|
|
57
|
-
`)}${
|
|
58
|
-
${v}`}}catch(
|
|
59
|
-
`),
|
|
60
|
-
`),
|
|
61
|
-
`);await
|
|
62
|
-
${
|
|
63
|
-
`)}}catch(
|
|
64
|
-
`,l.isDirectory()){let
|
|
53
|
+
`}function zh(t,e,r,n,s,i,o){return Sa(Vh(t,e,r,n,s,i,o))}function va(t,e,r,n,s,i){return zh(t,t,e,r,n,s,i)}function os(t,e,r){return va(t,e,r,"original","modified")}var xe=$(require("fs/promises")),as=$(require("fs")),lt=$(require("path")),ka=$(require("os")),Rt=lt.join(ka.homedir(),".hablas","backup"),_a=10;async function Ge(t){try{if(!as.existsSync(t))return;as.existsSync(Rt)||await xe.mkdir(Rt,{recursive:!0});let e=await xe.readFile(t,"utf-8"),r=lt.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=lt.join(Rt,s);await xe.writeFile(i,e,"utf-8");let a=(await xe.readdir(Rt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>_a)for(let l of a.slice(_a))await xe.unlink(lt.join(Rt,l))}catch{}}function Ta(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 U.readFile(u,"utf-8")).split(`
|
|
54
|
+
`),b=m.length,x=p.start_line?Math.max(1,p.start_line):1,w=p.end_line?Math.min(b,p.end_line):b,v=m.slice(x-1,w),_=String(w).length,C=v.map((T,j)=>`${String(x+j).padStart(_," ")} | ${T}`),E=`[${p.path} \u2014 lines ${x}-${w} of ${b}]`,R=w<b?`
|
|
55
|
+
... [Partial read. Total lines: ${b}.]`:"";return{success:!0,output:`${E}
|
|
56
|
+
${C.join(`
|
|
57
|
+
`)}${R}`}}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 ls.existsSync(u)&&await Ge(u),await U.mkdir(Pe.dirname(u),{recursive:!0}),await U.writeFile(u,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[write_file]: ${u.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let u=e(p.path),g=await U.readFile(u,"utf-8"),m=p.old_content,b=p.new_content,x=$a(g,m);if(x===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(x>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${x} locations in the file. Provide more surrounding context to be specific.`};await Ge(u);let w=g.replace(m,b);await U.writeFile(u,w,"utf-8");let v=os(p.path,g,w);return{success:!0,output:`Edited: ${p.path}
|
|
58
|
+
${v}`}}catch(u){return{success:!1,output:"",error:`[edit_file]: ${u.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let u=e(p.path),g=await U.readFile(u,"utf-8"),m=g.split(`
|
|
59
|
+
`),b=m.length,x=p.start_line,w=p.end_line;if(x<1||x>b)return{success:!1,output:"",error:`[patch_file]: start_line ${x} is out of range (file has ${b} lines)`};if(w<x||w>b)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${x}, total=${b})`};await Ge(u);let v=m.slice(0,x-1),_=m.slice(w),C=p.new_content.split(`
|
|
60
|
+
`),E=[...v,...C,..._].join(`
|
|
61
|
+
`);await U.writeFile(u,E,"utf-8");let R=os(p.path,g,E),T=w-x+1,j=C.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${j})
|
|
62
|
+
${R}`}}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 U.readFile(u,"utf-8"),m=p.search,b=p.replace,x=p.is_regex;await Ge(u);let w,v;if(x){let _=new RegExp(m,"g");v=(g.match(_)||[]).length,w=g.replace(_,b)}else v=$a(g,m),w=g.split(m).join(b);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await U.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 U.mkdir(Pe.dirname(u),{recursive:!0}),ls.existsSync(u)&&await Ge(u),await U.appendFile(u,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[append_to_file]: ${u.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let u=e(p.path);return await Ge(u),await U.unlink(u),{success:!0,output:`Deleted: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[delete_file]: ${u.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let u=e(p.from),g=e(p.to);return await U.mkdir(Pe.dirname(g),{recursive:!0}),await U.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 U.mkdir(u,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(u){return{success:!1,output:"",error:`[create_dir]: ${u.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let u=e(p.path||"."),g=p.depth||3;return{success:!0,output:await Ca(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 U.stat(u);return{success:!0,output:[`Path: ${p.path}`,`Size: ${Gh(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
|
|
63
|
+
`)}}catch(u){return{success:!1,output:"",error:`[get_file_info]: ${u.message}`}}}}]}function $a(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)break;r++,n=s+e.length}return r}var Kh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Ca(t,e,r,n){if(n>=r)return"";let i=(await U.readdir(t,{withFileTypes:!0})).filter(a=>!Kh.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,f=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${f}${d} ${l.name}
|
|
64
|
+
`,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await Ca(Pe.join(t,l.name),h,r,n+1)}}return o}function Gh(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Oa=require("child_process");var Ea=require("child_process"),gr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let n=`bg_${this.nextId++}`,s=r?.timeout||this.config.defaultTimeout,i=(0,Ea.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
|
|
65
65
|
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
|
|
66
66
|
Process timed out after ${s}ms`)},s),this.processes.set(n,o),n}readOutput(e,r){let n=this.processes.get(e);if(!n)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=r?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=n.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
|
|
67
67
|
`),i+=n.stderr),r?.lastLines&&(i=i.split(`
|
|
68
68
|
`).slice(-r.lastLines).join(`
|
|
69
|
-
`)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var
|
|
70
|
-
PID: ${
|
|
71
|
-
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,
|
|
69
|
+
`)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var Jh=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],cs=null;function Aa(t){return cs||(cs=new gr({workingDir:t})),cs}function Ra(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let n=r.command,s=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Jh,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Aa(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
|
|
70
|
+
PID: ${Aa(t).getProcess(l)?.pid}
|
|
71
|
+
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Oa.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{l(h===0?{success:!0,output:f||"(no output)"}:{success:!1,output:f,error:d||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var yr=$(require("fs/promises")),Me=$(require("path")),Yh=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Xh=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Ia(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=Me.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await Pa(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
|
|
72
72
|
`),a=i.length>50?`
|
|
73
|
-
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function
|
|
74
|
-
`),c=
|
|
75
|
-
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function
|
|
76
|
-
`);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function
|
|
77
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function
|
|
78
|
-
`)}function
|
|
79
|
-
`);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],
|
|
80
|
-
`),"utf-8"),r.push({bug:n,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:n,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:n,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function
|
|
73
|
+
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function Pa(t,e,r,n){let s=await yr.readdir(t,{withFileTypes:!0});for(let i of s){if(Yh.has(i.name)||i.name.startsWith("."))continue;let o=Me.join(t,i.name);if(i.isDirectory())await Pa(o,e,r,n);else if(Xh.has(Me.extname(i.name)))try{let l=(await yr.readFile(o,"utf-8")).split(`
|
|
74
|
+
`),c=Me.relative(n,o);for(let f=0;f<l.length;f++)e.test(l[f])&&(r.push(`${c}:${f+1}: ${l[f].trim()}`),e.lastIndex=0)}catch{}}}var us=require("child_process"),ce=$(require("fs")),je=$(require("path"));function Qh(t){let e=[],r=je.join(t,"tsconfig.json");if(!ce.existsSync(r))return e;try{(0,us.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
|
|
75
|
+
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Zh(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>ce.existsSync(je.join(t,n))))return e;try{(0,us.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file: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(`
|
|
76
|
+
`);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function em(t,e,r){let n;try{n=ce.readFileSync(t,"utf-8")}catch{return}let s=je.relative(e,t),i=n.split(`
|
|
77
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function tm(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function n(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=ce.readdirSync(s)}catch{return}for(let l of a){if(o.includes(l))continue;let c=je.join(s,l),f;try{f=ce.statSync(c)}catch{continue}f.isDirectory()?n(c,i+1):r.some(d=>l.endsWith(d))&&em(c,t,e)}}return n(t),e.slice(0,20)}function rm(t){let e=[];e.push(...Qh(t)),e.push(...Zh(t)),e.push(...tm(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Ma(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,n=t.filter(i=>i.severity==="warning").length,s=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${n} warnings, ${s} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
|
|
78
|
+
`)}function nm(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=je.join(e,n.file);try{let o=ce.readFileSync(s,"utf-8").split(`
|
|
79
|
+
`);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],ce.writeFileSync(s,o.join(`
|
|
80
|
+
`),"utf-8"),r.push({bug:n,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:n,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:n,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function ja(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,n=e.fix==="true"||e.fix===!0;try{let s=rm(r);if(n&&s.length>0){let o=nm(s,r).filter(l=>l.fixed).length;return{success:!0,output:`${Ma(s)}
|
|
81
81
|
|
|
82
|
-
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:
|
|
82
|
+
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Ma(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var La=2*1024*1024,Da=15e3,Fa=32e3,sm="HablasBot/2.0 (+https://hablas.dev)";function im(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
|
|
83
83
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
84
84
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
85
85
|
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n,s)=>`
|
|
86
86
|
${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
87
87
|
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${n})`:n}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,n)=>"\n```\n"+n.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(r,n)=>String.fromCharCode(parseInt(n))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
88
88
|
|
|
89
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
89
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function om(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 am(t,e){let r=[],n=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=n.exec(t))!==null;){let o=s[1].trim(),a=s[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function Na(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Da);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":sm,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!n.ok)return{html:"",finalUrl:n.url||t,status:n.status};let s=n.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:n.url||t,status:n.status};let i=n.body?.getReader();if(!i)return{html:"",finalUrl:n.url||t,status:n.status};let o=[],a=0;for(;a<La;){let{done:f,value:d}=await i.read();if(f)break;o.push(d),a+=d.length}if(a>=La)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:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Da/1e3}s`):s}}function Ua(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:n,status:s}=await Na(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=om(r),o=im(r);return o.length>Fa&&(o=o.slice(0,Fa)+`
|
|
90
90
|
|
|
91
91
|
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${n}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
92
|
-
`)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await
|
|
92
|
+
`)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await Na(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=am(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
|
|
93
93
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
94
94
|
|
|
95
|
-
${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var
|
|
96
|
-
`)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var
|
|
95
|
+
${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var lm=3600*1e3,ct=new Map;function cm(t){let e=ct.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>lm?(ct.delete(t.toLowerCase().trim()),null):e.results:null}function um(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 fm(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let n=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${n}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return s.ok?((await s.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function dm(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),f=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:f,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let f=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(f)&&!f.includes("duckduckgo.com")&&(c.add(f),i.push({title:d,url:f,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function fs(t,e=5){let r=cm(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>fm(t,e)},{name:"duckduckgo",fn:()=>dm(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return um(t,i),i}catch{}return[]}function qa(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let n=await fs(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
|
|
96
|
+
`)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var ke=$(require("fs")),za=$(require("path")),Ba=50*1024*1024,Ha=4e4;function Wa(t){let e=t.toString("latin1"),r={},n=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=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=Va(p);u.trim()&&n.push(u);try{let g=require("zlib"),m=Buffer.from(p,"latin1"),b=g.inflateSync(m).toString("latin1"),x=Va(b);x.trim()&&!n.includes(x)&&n.push(x)}catch{}}return{text:n.join(`
|
|
97
97
|
`).replace(/\r\n/g,`
|
|
98
98
|
`).replace(/\n{3,}/g,`
|
|
99
99
|
|
|
100
|
-
`).trim(),pages:s,metadata:r}}function
|
|
101
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function
|
|
102
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function
|
|
100
|
+
`).trim(),pages:s,metadata:r}}function Va(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(Je(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let l=n[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(f=>Je(f.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(Je(n[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
|
|
101
|
+
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function Je(t){return t.replace(/\\n/g,`
|
|
102
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Ka(t){let e=r=>za.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let n=e(r.path);if(!ke.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=ke.statSync(n);if(s.size>Ba)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${Ba/1024/1024}MB)`};try{let i=ke.readFileSync(n),{text:o,pages:a,metadata:l}=Wa(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
|
|
103
103
|
|
|
104
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>
|
|
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>Ha&&(c=c.slice(0,Ha)+`
|
|
105
105
|
|
|
106
106
|
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
107
107
|
`)}
|
|
108
|
-
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!
|
|
109
|
-
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var
|
|
108
|
+
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!ke.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ke.statSync(n),i=ke.readFileSync(n),{pages:o,metadata:a}=Wa(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
|
|
109
|
+
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Ya=require("child_process"),wr=$(require("fs")),Xa=$(require("os")),Qa=$(require("path")),Za=1e4,Ga=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 Ja={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 pm(t,e,r=Za){let n=Ja[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ja).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=Xa.tmpdir(),i=Qa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{wr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Ya.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),f="",d="";c.stdout?.on("data",h=>{f+=h}),c.stderr?.on("data",h=>{d+=h}),c.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:f.slice(0,Ga),stderr:d.slice(0,Ga/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{wr.unlinkSync(i)}catch{}}}function hm(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 el(){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()||hm(e),n=Math.min(Math.max(1e3,t.timeout||Za),3e4),s=await pm(e,r,n),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
|
|
110
110
|
Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
|
|
111
|
-
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var
|
|
111
|
+
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var vr=$(require("fs")),ge=$(require("path"));var mm=["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"],gm=[/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 ds(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 ym=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 br(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!ym.has(e))}function xr(t,e){let r=[...new Set(br(t))].slice(0,6);return r.length>0?r.join(" "):t.trim().slice(0,60)}function It(t){try{let e=new URL(t).hostname.toLowerCase();return mm.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function wm(t){return gm.some(e=>e.test(t))}function Sr(t,e,r,n,s=[]){let i=It(t),o=[],a=[],l=0;if(i&&(l+=20,o.push("trusted-host")),wm(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")),s.length>0){let f=br([e,r,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),d=new Set(f),h=s.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(n==="hero"||n==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(c)&&(l+=5,o.push("kind-hero")),(n==="product"||n==="thumbnail")&&/product|closeup|detail|item|buy/i.test(c)&&(l+=5,o.push("kind-product")),(n==="icon"||n==="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 tl(t,e){let r=xr(t,e),n=encodeURIComponent(r);return r?[{source:"unsplash",url:`https://unsplash.com/s/photos/${n}`},{source:"pexels",url:`https://www.pexels.com/search/${n}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${n}/`}]:[]}function rl(t,e){let r=xr(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 bm(t,e){try{let r=t.split(",")[0].trim().split(/\s+/)[0],n=new URL(r,e);return/^https?:$/i.test(n.protocol)?n.href:null}catch{return null}}function ft(t,e){let r=new Set,n=[];function s(i){let o=bm(i,e);o&&!r.has(o)&&(r.add(o),n.push(o))}for(let i of t.matchAll(/<meta[^>]+(?:property|name)=["'](?:og:image(?::secure_url)?|twitter:image(?::src)?)["'][^>]+content=["']([^"']+)["']/gi))s(i[1]);for(let i of t.matchAll(/<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["'](?:og:image|twitter:image)/gi))s(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"?s(l):typeof l?.url=="string"?s(l.url):typeof l?.contentUrl=="string"?s(l.contentUrl):Array.isArray(l)&&l.forEach(c=>{typeof c=="string"?s(c):c?.url&&s(c.url)})}catch{}for(let i of t.matchAll(/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi))s(i[1]);for(let i of t.matchAll(/<img[^>]+data-(?:src|lazy|original|lazy-src)=["']([^"']+)["']/gi))s(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&&s(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))s(i[1]);return n.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:It(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function nl(t,e){let r=new Set,n=[];for(let s of t.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))try{let i=new URL(s[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),n.push(i.href))}catch{}return n.slice(0,20)}var sl=15*1024*1024,il=15e3,xm=5;function Sm(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 ol(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 vm(t){let e=await fetch(t,{signal:AbortSignal.timeout(il),redirect:"follow",headers:ol(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",n=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r))throw new Error("HTML page returned where a direct image was expected");let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>sl)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}async function _m(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let n=await fetch(t,{signal:AbortSignal.timeout(il),redirect:"follow",headers:ol(t)});if(!n.ok)throw new Error(`HTTP ${n.status} while downloading asset`);let s=n.headers.get("content-type")||"",i=n.url||t;if(/text\/html|application\/xhtml\+xml/i.test(s)){let l=await n.text(),c=ft(l,i).map(d=>({url:d,...Sr(d,"","",e)})).sort((d,h)=>h.score-d.score).slice(0,xm);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 vm(d.url)}catch(h){f=String(h?.message||h)}throw new Error(`all ranked HTML image candidates failed: ${f}`)}let o=await n.arrayBuffer(),a=Buffer.from(o);if(a.length>sl)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:s,finalUrl:i}}function km(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 al(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await _m(r,km(n)),a=ge.resolve(t,n),c=ge.extname(a)?a:a+Sm(i,o);return vr.mkdirSync(ge.dirname(c),{recursive:!0}),vr.writeFileSync(c,s),{success:!0,output:`Downloaded asset: ${ge.relative(t,c)||ge.basename(c)}
|
|
112
112
|
Final source: ${o}
|
|
113
113
|
Type: ${i||"unknown"}
|
|
114
|
-
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var
|
|
115
|
-
|
|
114
|
+
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var _r=$(require("fs")),kr=$(require("path"));var hs=15e3,ll=5;function cl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function ul(t,e){return t[e]|t[e+1]<<8}function $m(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],n=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+n}return{}}function Tm(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,n=(t.readUInt16LE(28)&16383)+1;return{width:r,height:n}}return{}}function ps(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:cl(t,16),height:cl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:ul(t,6),height:ul(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...$m(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...Tm(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function pl(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 fl(t){let e=await fetch(t,{signal:AbortSignal.timeout(hs),redirect:"follow",headers:pl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let r=e.headers.get("content-type")||"",n=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).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:n,html:o}}async function dl(t){let e=await fetch(t,{signal:AbortSignal.timeout(hs),redirect:"follow",headers:{...pl(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 Cm(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:xr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),n=await fetch(`https://commons.wikimedia.org/w/api.php?${r}`,{signal:AbortSignal.timeout(hs),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!n.ok)throw new Error(`Wikimedia HTTP ${n.status}`);let s=await n.json();return Object.values(s?.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 Em(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
|
|
115
|
+
|
|
116
|
+
Context from user: "${t}"
|
|
117
|
+
|
|
118
|
+
Return this exact JSON structure \u2014 no markdown, no commentary:
|
|
116
119
|
{
|
|
117
|
-
"
|
|
118
|
-
"
|
|
119
|
-
"
|
|
120
|
-
"
|
|
121
|
-
"
|
|
122
|
-
"
|
|
123
|
-
"summary": "one short sentence"
|
|
120
|
+
"description": "one sentence describing what is in the image",
|
|
121
|
+
"suitable": true,
|
|
122
|
+
"confidence": 0.85,
|
|
123
|
+
"issues": [],
|
|
124
|
+
"suggestedUse": "generic",
|
|
125
|
+
"summary": "one short sentence verdict"
|
|
124
126
|
}
|
|
127
|
+
|
|
125
128
|
Rules:
|
|
126
|
-
-
|
|
127
|
-
-
|
|
128
|
-
-
|
|
129
|
-
-
|
|
130
|
-
-
|
|
131
|
-
|
|
132
|
-
-
|
|
133
|
-
- `)
|
|
134
|
-
`)}}},{name:"inspect_image",description:"
|
|
135
|
-
`)}}
|
|
129
|
+
- suitable: true if the image matches the user context, false otherwise
|
|
130
|
+
- confidence: float 0.0\u20131.0
|
|
131
|
+
- suggestedUse: one of "hero", "product", "icon", "generic", "reject"
|
|
132
|
+
- issues: list any quality or relevance problems (empty array if none)
|
|
133
|
+
- Do NOT output anything outside the JSON object`}async function Am(t,e,r,n){let s=t.provider==="nvidia"?oe.apiUrl:t.apiUrl;if(!s)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(s.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:Em(n)},{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 Om(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 hl(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 n=String(r.query||"").trim();if(!n)return{success:!1,output:"",error:"query is required"};let s=ds(r.kind),i=Math.min(Math.max(1,Number(r.max_results??5)),10),o=br(n),a=new Map,l=[],c=(h,p,u,g)=>{if(a.has(h))return;let m=Sr(h,p,u,s,o);a.set(h,{url:h,title:p,snippet:u,source:g,...m})};for(let h of tl(n,s))try{let{finalUrl:p,html:u}=await dl(h.url),g=nl(u,p),m=0;for(let x of g.slice(0,ll*2)){if(m>=ll)break;try{let{finalUrl:w,html:v}=await dl(x),C=ft(v,w)[0];C&&(c(C,h.source+" photo",n,h.source),m++)}catch{}}let b=ft(u,p);for(let x of b.slice(0,6))c(x,h.source,n,h.source);m===0&&b.length===0&&l.push(`${h.source}: no images found`)}catch(p){l.push(`${h.source}: ${String(p?.message??p)}`)}try{let h=await Cm(n,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 rl(n,s))try{let p=await fs(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 "${n}".${l.length?`
|
|
134
|
+
Notes:
|
|
135
|
+
- `+l.join(`
|
|
136
|
+
- `):""}`};let d=[`Image candidates for: "${n}" (kind=${s}) \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(`
|
|
137
|
+
`)}}},{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 n=String(r.source||"").trim();if(!n)return{success:!1,output:"",error:"source is required"};let s=ds(r.kind),i=String(r.context||n).slice(0,200),o=String(r.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${n}`,""],l="unknown",c,f,d=!1,h=!1,p=n,u=null,g=!1,m=[];try{if(/^https?:\/\//i.test(n)){let w=await fl(n);if(p=w.finalUrl,l=w.contentType,h=It(p),w.html){if(g=!0,m=ft(w.html,p),m.length>0){let v=m[0];try{let _=await fl(v);p=_.finalUrl,l=_.contentType,u=_.bytes,h=It(p);let C=ps(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=ps(u,l);c=v.width,f=v.height}}else{let w=kr.resolve(t,n);if(!_r.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${n}`};u=_r.readFileSync(w).subarray(0,2*1024*1024);let v=kr.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 _=ps(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 b=Om(s,c,f);if(c&&f){let w=b>0;a.push(` size verdict: ${w?"\u2713 adequate for "+s:"\u2717 may be too small for "+s} (${c}\xD7${f})`)}if(o&&e.vision.enabled&&u&&/^image\//i.test(l)){a.push(""),a.push(" Vision analysis:");try{let w=await Am(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 x=d&&(h||/^image\//i.test(l));return a.push(` VERDICT: ${x?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
|
|
138
|
+
`)}}}]}var te=$(require("fs")),ys=$(require("path")),wl=$(require("os")),bl=$(require("crypto")),Pt=ys.join(wl.homedir(),".hablas"),ms=ys.join(Pt,"memory.json"),ml=1,gl=2e3,Rm=1600,Im=8e3;function Pm(){return bl.randomBytes(8).toString("hex")}function yl(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Mm(t,e){let r=t+".tmp."+process.pid;te.writeFileSync(r,e,"utf-8"),te.renameSync(r,t)}var gs=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(te.existsSync(Pt)||te.mkdirSync(Pt,{recursive:!0}),te.existsSync(ms)){let e=JSON.parse(te.readFileSync(ms,"utf-8"));if(e.version===ml)return e}}catch{}return{version:ml,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(Pt)||te.mkdirSync(Pt,{recursive:!0}),Mm(ms,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(n=>n!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],n=Date.now(),s=e.value.slice(0,Im);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=s,a.updatedAt=n,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=n+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=Pm(),o={id:i,kind:e.kind,key:e.key,value:s,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:n,updatedAt:n,accessCount:0,lastAccessed:n,ttl:e.ttl?n+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let n=this.store.entries[r];return n?n.ttl&&Date.now()>n.ttl?(this.forget(e),null):(n.accessCount++,n.lastAccessed=Date.now(),this.scheduleFlush(),n):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let n=this.store.entries[r];return n?(this.removeFromIndex(n),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let n=Date.now(),s=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&n>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let 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+yl(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,s)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(n=>n.kind===e&&(!n.ttl||Date.now()<n.ttl)).sort((n,s)=>s.updatedAt-n.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,n)=>n.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<gl)return;let r=Date.now();for(let n of Object.values(this.store.entries))n.ttl&&r>n.ttl&&(this.removeFromIndex(n),delete this.store.entries[n.id],e--);if(e>=gl){let n=Object.values(this.store.entries).map(s=>({id:s.id,score:yl(s.priority)*10+s.accessCount+s.lastAccessed/1e12})).sort((s,i)=>s.score-i.score);for(let{id:s}of n.slice(0,e-Rm)){let i=this.store.entries[s];i&&(this.removeFromIndex(i),delete this.store.entries[s])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
|
|
136
139
|
Stack: ${r.stack}${r.summary?`
|
|
137
140
|
Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,n){this.remember({kind:"decision",key:`decision:${e}:${r.slice(0,60)}`,value:`Decision: ${r}
|
|
138
141
|
Rationale: ${n}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,r){this.remember({kind:"preference",key:`pref:${e}`,value:r,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,r,n){this.remember({kind:"task_summary",key:`task:${e}:${r.slice(0,60)}:${Date.now()}`,value:`Task: ${r}
|
|
139
142
|
Outcome: ${n}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,r=3e3){let n=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){n.push("## Memory: this project");for(let o of i.slice(0,8))n.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let s=this.getByKind("preference",5);if(s.length>0){n.push("## Memory: user preferences");for(let i of s)n.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return n.join(`
|
|
140
|
-
`).slice(0,r)}}
|
|
143
|
+
`).slice(0,r)}},$r=null;function V(){return $r||($r=new gs),$r}function xl(){$r?.flush()}var Tr=["project","preference","decision","pattern","tool_outcome","fact","task_summary"];function Sl(){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: ${Tr.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(!Tr.includes(e))return{success:!1,output:"",error:`Invalid kind "${t.kind}". Must be one of: ${Tr.join(", ")}`};let r=t.key,n=t.value;if(!r||!n)return{success:!1,output:"",error:"key and value are required"};let s=t.tags?t.tags.split(",").map(a=>a.trim()).filter(Boolean):[],i=t.priority??"normal",o=V().remember({kind:e,key:r,value:n,tags:s,project:t.project,priority:i});return{success:!0,output:`Remembered [${e}] key="${r}" (id=${o})`}}catch(e){return{success:!1,output:"",error:`[remember]: ${e.message}`}}}},{name:"recall",description:"Retrieve a specific memory entry by its exact key. Returns null if not found.",safety:"safe",parameters:{key:{type:"string",description:"The exact key used when storing the memory",required:!0}},execute:async t=>{try{let e=V().recall(t.key);return e?{success:!0,output:[`Key: ${e.key}`,`Kind: ${e.kind}`,`Priority: ${e.priority}`,`Tags: ${e.tags.join(", ")||"\u2014"}`,`Value:
|
|
141
144
|
${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: ${
|
|
145
|
+
`)}:{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: ${Tr.join(" | ")}`,required:!1},project:{type:"string",description:"Optional: limit to a specific project path",required:!1},limit:{type:"number",description:"Max results (default: 8)",required:!1}},execute:async t=>{try{let e=V().search(t.query,{kind:t.kind,project:t.project,limit:t.limit||8});if(e.length===0)return{success:!0,output:"No relevant memories found."};let r=e.map((n,s)=>`${s+1}. [${n.entry.kind}] key="${n.entry.key}" score=${n.score.toFixed(2)}
|
|
143
146
|
${n.entry.value.replace(/\n/g," \u2014 ").slice(0,180)}`);return{success:!0,output:`Found ${e.length} relevant memories:
|
|
144
147
|
|
|
145
148
|
${r.join(`
|
|
146
149
|
|
|
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
|
+
`)}`}}catch(e){return{success:!1,output:"",error:`[search_memory]: ${e.message}`}}}},{name:"forget",description:"Delete a memory entry by its exact key. Use when a decision or preference is no longer valid.",safety:"safe",parameters:{key:{type:"string",description:"The exact key of the memory to delete",required:!0}},execute:async t=>{try{return{success:!0,output:V().forget(t.key)?`Deleted memory "${t.key}"`:`No memory found for key "${t.key}"`}}catch(e){return{success:!1,output:"",error:`[forget]: ${e.message}`}}}},{name:"memory_stats",description:"Show memory storage statistics: total entries, breakdown by kind, most recently accessed.",safety:"safe",parameters:{},execute:async()=>{try{let t=V().getStats(),e=V().getRecent(5);return{success:!0,output:[`Total memories: ${t.total}`,"Breakdown:",...Object.entries(t).filter(([n])=>n!=="total").map(([n,s])=>` ${n}: ${s}`),"","Most recently accessed:",...e.map(n=>` [${n.kind}] ${n.key.slice(0,60)} \u2014 ${new Date(n.lastAccessed).toISOString()}`)].join(`
|
|
151
|
+
`)}}catch(t){return{success:!1,output:"",error:`[memory_stats]: ${t.message}`}}}}]}var vl=require("child_process");function $e(t,e,r=1e4){try{return{ok:!0,output:(0,vl.execSync)(t,{cwd:e,timeout:r,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{ok:!1,output:(n.stderr?.toString()||n.stdout?.toString()||n.message||"command failed").trim()}}}function Cr(t){let e=$e("git rev-parse --is-inside-work-tree",t,3e3);return e.ok&&e.output==="true"}function _l(t){return[{name:"git_status",description:"Show the current git status: staged files, unstaged changes, untracked files, stash count, branch tracking state (ahead/behind remote). Use this to understand the state of the repository before making changes.",safety:"safe",parameters:{short:{type:"string",description:'Set to "true" for a compact one-line-per-file view (default: false)',required:!1}},execute:async e=>{if(!Cr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.short==="true",n=[],s=$e("git branch --show-current",t),i=$e('git rev-parse --abbrev-ref --symbolic-full-name @{u} 2>/dev/null || echo "no-remote"',t);if(n.push(`Branch: ${s.output||"(detached HEAD)"}`),i.ok&&i.output!=="no-remote"){let c=$e(`git rev-list --left-right --count HEAD...${i.output}`,t);if(c.ok){let[f,d]=c.output.split(" ").map(Number);f>0&&n.push(`Ahead of remote: ${f} commit(s)`),d>0&&n.push(`Behind remote: ${d} commit(s)`)}n.push(`Remote: ${i.output}`)}let a=$e(r?"git status --short":"git status --porcelain=v1",t);if(a.ok&&a.output){n.push(""),n.push("Changes:");let c=a.output.split(`
|
|
152
|
+
`).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&&(n.push(" Staged:"),f.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),d.length>0&&(n.push(" Unstaged:"),d.forEach(p=>n.push(` ${p.slice(0,2)} ${p.slice(3)}`))),h.length>0&&(n.push(` Untracked: ${h.length} file(s)`),h.length<=5&&h.forEach(p=>n.push(` ${p.slice(3)}`)))}else n.push("Working tree: clean");let l=$e("git stash list --oneline",t);if(l.ok&&l.output){let c=l.output.split(`
|
|
150
153
|
`).filter(Boolean).length;n.push(`Stash: ${c} stashed change(s)`)}return{success:!0,output:n.join(`
|
|
151
|
-
`)}}},{name:"git_diff",description:"Show the diff for a file or the whole working tree. Useful to understand exactly what changed before or after edits.",safety:"safe",parameters:{path:{type:"string",description:"File path to diff (optional \u2014 omit for full diff)",required:!1},staged:{type:"string",description:'Set "true" to show staged diff (default: unstaged)',required:!1},lines:{type:"number",description:"Context lines around each change (default: 3)",required:!1}},execute:async e=>{if(!
|
|
152
|
-
... [diff truncated]`:o.output}}},{name:"git_log",description:"Show recent git commit history with author, date, and message. Optionally filter by file.",safety:"safe",parameters:{limit:{type:"number",description:"Number of commits to show (default: 10)",required:!1},path:{type:"string",description:"File path to filter commits by (optional)",required:!1},stats:{type:"string",description:'Set "true" to include file change stats per commit',required:!1}},execute:async e=>{if(!
|
|
154
|
+
`)}}},{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(!Cr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.staged==="true"?"--cached ":"",n=e.lines?`-U${e.lines}`:"-U3",s=e.path?`-- "${e.path}"`:"",i=`git diff ${r}${n} ${s}`.trim(),o=$e(i,t);if(!o.ok)return{success:!1,output:"",error:o.output};if(!o.output)return{success:!0,output:e.path?`No diff for ${e.path}`:"No changes detected."};let a=8e3;return{success:!0,output:o.output.length>a?o.output.slice(0,a)+`
|
|
155
|
+
... [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(!Cr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.limit||10,n=e.path?`-- "${e.path}"`:"",s=e.stats==="true"?"--stat":"",o=`git log -${r} --format="%h %as %an %s" ${s} ${n}`.trim(),a=$e(o,t);return a.ok?{success:!0,output:a.output||"No commits found."}:{success:!1,output:"",error:a.output}}},{name:"git_branch",description:"List git branches, show current branch, and tracking info.",safety:"safe",parameters:{all:{type:"string",description:'Set "true" to include remote branches (default: local only)',required:!1}},execute:async e=>{if(!Cr(t))return{success:!1,output:"",error:"Not a git repository"};let r=e.all==="true"?"-a":"",n=$e(`git branch ${r} -vv`,t);return n.ok?{success:!0,output:n.output||"No branches found."}:{success:!1,output:"",error:n.output}}}]}var dt=class{tools=new Map;constructor(e,r){let n=Ta(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Ra(e,r)),this.tools.set("search_codebase",Ia(e)),this.tools.set("detect_bugs",ja(e)),this.tools.set("web_search",qa());for(let s of Ua())this.tools.set(s.name,s);for(let s of Ka(e))this.tools.set(s.name,s);for(let s of el())this.tools.set(s.name,s);this.tools.set("download_asset",al(e));for(let s of hl(e,r))this.tools.set(s.name,s);for(let s of Sl())this.tools.set(s.name,s);for(let s of _l(e))this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
|
|
153
156
|
`);return`- ${r.name} [${r.safety}]: ${r.description}
|
|
154
157
|
${n}`}).join(`
|
|
155
158
|
|
|
156
|
-
`)}};var
|
|
157
|
-
... [truncated to fit context budget]`}var
|
|
159
|
+
`)}};var kl=$(require("crypto"));function ws(t){return Math.ceil(t.length/3.5)}function Mt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
|
|
160
|
+
... [truncated to fit context budget]`}var pt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=ws(r),a=n?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:n?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let n=this.cache.get(e);return n?n.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,n=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of n){if(s+o.tokenCount>r){if(o.importance>=7){let a=r-s;if(a>200){let l=Mt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
158
161
|
${l}`),s+=a}}continue}i.push(`--- ${o.path} ---
|
|
159
162
|
${o.content}`),s+=o.tokenCount}return i.join(`
|
|
160
163
|
|
|
161
|
-
`)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(
|
|
164
|
+
`)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(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>n)break;l.push(`--- ${c.path} ---
|
|
162
165
|
${c.content}`),a+=c.tokenCount}return l.join(`
|
|
163
166
|
|
|
164
|
-
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=
|
|
167
|
+
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=ws(r);return s>2e3&&(n=Math.max(1,n-1)),s>5e3&&(n=Math.max(1,n-2)),n}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let n of r)if(n!==e){let s=this.cache.get(n);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return kl.createHash("md5").update(e).digest("hex")}};var jm=0;function jt(){return`msg_${Date.now()}_${++jm}`}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,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=ht(e);this.messages.push({id:jt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,r){let n=jt(),s=ht(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=jt(),i=ht(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=jt(),s=ht(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=ht(e),n={id:jt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[n],this.recalculateTokens();return}this.messages[0]=n,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
|
|
165
168
|
...(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
|
|
168
|
-
`)}function Oh(t,e){try{return dt.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function mt(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",J("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",J("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",J("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",J("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",J("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",J("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",J("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",J("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",J("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",J("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",J("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",J("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let n=W().buildContextBlock(r,2500);return n.trim()?[J("PERSISTENT MEMORY",n),""]:[]})(),J("TASK PROFILE",Rh(e)),"",J("CURRENT PROJECT CONTEXT",Ih(t))].join(`
|
|
169
|
-
`)}function
|
|
169
|
+
...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=ht(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var yt=$(require("fs")),$l=$(require("path"));var A=$(require("fs")),O=$(require("path"));function Lm(t){let e=O.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(O.join(t,"requirements.txt"))||A.existsSync(O.join(t,"pyproject.toml")))try{let r=A.existsSync(O.join(t,"requirements.txt"))?A.readFileSync(O.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(O.join(t,"Cargo.toml")))try{if(A.readFileSync(O.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(O.join(t,"go.mod")))try{if(A.readFileSync(O.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Dm(t){return A.existsSync(O.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(O.join(t,"yarn.lock"))?"yarn":A.existsSync(O.join(t,"bun.lockb"))?"bun":A.existsSync(O.join(t,"package-lock.json"))?"npm":A.existsSync(O.join(t,"Cargo.toml"))?"cargo":A.existsSync(O.join(t,"go.mod"))?"go":A.existsSync(O.join(t,"requirements.txt"))||A.existsSync(O.join(t,"pyproject.toml"))?"pip":"unknown"}function Fm(t){return A.existsSync(O.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(O.join(t,"package.json"))?"JavaScript":A.existsSync(O.join(t,"Cargo.toml"))?"Rust":A.existsSync(O.join(t,"go.mod"))?"Go":A.existsSync(O.join(t,"pyproject.toml"))||A.existsSync(O.join(t,"requirements.txt"))?"Python":"Unknown"}function Nm(t){let e=O.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function gt(t){let e=Lm(t),r=Dm(t),n=Fm(t),s=Nm(t),i=A.existsSync(O.join(t,"Dockerfile"))||A.existsSync(O.join(t,"docker-compose.yml"))||A.existsSync(O.join(t,"docker-compose.yaml")),o=A.existsSync(O.join(t,".github","workflows"))||A.existsSync(O.join(t,".gitlab-ci.yml"))||A.existsSync(O.join(t,"Jenkinsfile")),a=A.existsSync(O.join(t,"__tests__"))||A.existsSync(O.join(t,"tests"))||A.existsSync(O.join(t,"test"))||A.existsSync(O.join(t,"spec")),l=A.existsSync(O.join(t,".git")),c=[],f=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of f)A.existsSync(O.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)A.existsSync(O.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)A.existsSync(O.join(t,g))&&p.push(g);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:c,configFiles:d,entryPoints:p}}function Er(t){let e=[` Project: ${O.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(`
|
|
170
|
+
`)}async function wt(t,e){let r=[],n=$l.join(t,"package.json");if(yt.existsSync(n))try{let o=JSON.parse(yt.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=gt(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Um(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
|
|
171
|
+
`)}function Um(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",Bm(e)),"",Q("CURRENT PROJECT CONTEXT",qm(t))].join(`
|
|
172
|
+
`)}function Q(t,e){let r=Array.isArray(e)?e.join(`
|
|
170
173
|
`):e;return["====================",t,"====================",r].join(`
|
|
171
|
-
`)}function
|
|
174
|
+
`)}function qm(t){return t.trim()||"No project context captured."}function Bm(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
175
|
`):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
176
|
`):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
177
|
`):[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
|
-
`+
|
|
179
|
-
|
|
180
|
-
|
|
178
|
+
`)}var Hm=/\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,Wm=/\b(انشئ|اعمل|ابني|طور|عدل|صلح|حدث|اضف|احذف|ارسل|فعل|شغل|حول|ضبط|هيئ|نفذ|اكتب|غير|بناء|تطوير|تعديل|اضافة|حذف|انشاء|تنفيذ|كود|برمج)\b/i,Vm=/\b(continue|resume|proceed|keep|finish|complete|pick\s*up|unfinished|remaining|previous|existing|current project|from the prd|where we left)\b/i,zm=/\b(كمل|استمر|اكمل|واصل|ارجع|خلينا|لسا|بقي|ما خلصنا)\b/i,Km=/\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,Gm=/\b(اقرا|اعرض|اشوف|شو|وين|كيف|ليش|وضح|اشرح|فين|ما هو|ما هي|بين|فسر)\b/i,Jm=/\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,Ym=/\b(معمارية|تصميم|خطة|مقارنة|بحث|دراسة|هيكل|نهج|اقتراح|توصية|تقييم)\b/i,Xm=/\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,Qm=/\b(بدون\s*اسئلة|مباشرة|فورا|دفعة\s*واحدة|كامل|بس\s*اعمل|عطني\s*النتيجة)\b/i,Zm=/^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|sure|got it|great|nice|cool|perfect|awesome)[.!?\s]*$/i,eg=/^(اه|تمام|شكرا|شكراً|مرحبا|اهلا|هلا|يلا|ماشي|حسنا|طيب|كيفك|صح)[.!?\s]*$/i,Tl=/\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,tg=/\b(واجهة|خلفية|قاعدة\s*بيانات|مكون|صفحة|مسار|تسجيل|لوحة\s*تحكم|تصميم|موبايل|اختبار|نشر|بناء)\b/i,rg=/\b(full|entire|complete|whole|all|comprehensive|production|enterprise|scalable|real-time|multi|complex|advanced|sophisticated|from\s*scratch|ground\s*up)\b/i,ng=/\b(كامل|شامل|متكامل|احترافي|متقدم|من\s*الصفر|كل\s*شيء)\b/i,sg=/\b(files?|components?|modules?|pages?|screens?|services?|controllers?|models?|views?|routes?|handlers?|hooks?|utils?|helpers?|types?|interfaces?)\b/i;function ig(t){let e=(t.match(/[\u0600-\u06FF]/g)||[]).length,r=(t.match(/[a-zA-Z]/g)||[]).length,n=e+r;if(n===0)return"english";let s=e/n;return s>.7?"arabic":s<.2?"english":"mixed"}function Lt(t,e){let r=t.trim().replace(/\s+/g," ");if(r.length<=80)return r;let n=r.match(/^[^.!?\n]{10,80}/)?.[0];return n?n.trim()+"\u2026":r.slice(0,80)+"\u2026"}function Dt(t,e){if(e==="casual")return{complexity:"trivial",estimatedSteps:0};if(e==="read")return{complexity:"simple",estimatedSteps:2};let r=0;(rg.test(t)||ng.test(t))&&(r+=3),sg.test(t)&&(r+=2);let n=t.split(/\s+/).length;return n>50&&(r+=1),n>100&&(r+=2),t.includes(`
|
|
179
|
+
`)&&(r+=1),Tl.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 bs(t){let e=t.trim(),r=ig(e),n=[],s=Hm.test(e),i=Wm.test(e),o=s||i;s&&n.push("impl:en"),i&&n.push("impl:ar");let a=Vm.test(e)||zm.test(e);a&&n.push("continuity");let l=Xm.test(e)||Qm.test(e);l&&n.push("one-step");let c=Km.test(e)||Gm.test(e);c&&n.push("read");let f=Jm.test(e)||Ym.test(e);f&&n.push("analysis");let d=Tl.test(e)||tg.test(e);d&&n.push("eng-context");let h=/\b(project|repo|repository|codebase|workspace|file|src|package\.json|config)\b/i.test(e)||d;if(h&&n.push("project-ref"),(Zm.test(e)||eg.test(e))&&!d&&!o&&!f){let{complexity:g,estimatedSteps:m}=Dt(e,"casual");return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Social turn detected.",complexity:g,estimatedSteps:m,intent:Lt(e,r),language:r,confidence:.95,signals:n}}if(o||a||l||d&&e.length>20&&!c&&!f){let{complexity:g,estimatedSteps:m}=Dt(e,"implementation");return{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:a,oneStepDelivery:l,requiresProjectContext:!0,reason:a?"Continuation of previous work.":"Implementation task detected.",complexity:g,estimatedSteps:m,intent:Lt(e,r),language:r,confidence:.9,signals:n}}if(f&&!o){let{complexity:g,estimatedSteps:m}=Dt(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:Lt(e,r),language:r,confidence:.85,signals:n}}if(c||h){let{complexity:g,estimatedSteps:m}=Dt(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:Lt(e,r),language:r,confidence:.8,signals:n}}let{complexity:p,estimatedSteps:u}=Dt(e,"analysis");return{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Default: analytical response.",complexity:p,estimatedSteps:u,intent:Lt(e,r),language:r,confidence:.6,signals:n}}function og(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 Cl(t){let e=bs(t);return{input:t,profile:e,plan:og(e)}}var Hl=$(require("readline")),de=$(require("fs")),re=$(require("path")),Wl=$(require("os"));var Le=$(require("process")),El=Le.stdout.isTTY===!0,ag=Le.env.NO_COLOR!==void 0||Le.env.TERM==="dumb",Al=Le.stdout.columns||100;El&&Le.stdout.on("resize",()=>{Al=Le.stdout.columns||100});var ue=()=>Math.min(Math.max(Al-4,60),110);function q(t,e){return!El||ag?t:`${e}${t}\x1B[0m`}var y={strong:t=>q(t,"\x1B[1;38;5;255m"),muted:t=>q(t,"\x1B[38;5;242m"),accent:t=>q(t,"\x1B[38;5;111m"),accentAlt:t=>q(t,"\x1B[38;5;147m"),info:t=>q(t,"\x1B[38;5;117m"),success:t=>q(t,"\x1B[38;5;114m"),warning:t=>q(t,"\x1B[38;5;179m"),error:t=>q(t,"\x1B[38;5;203m"),primary:t=>q(t,"\x1B[38;5;253m"),secondary:t=>q(t,"\x1B[38;5;247m"),border:t=>q(t,"\x1B[38;5;238m"),borderHi:t=>q(t,"\x1B[38;5;244m"),code:t=>q(t,"\x1B[38;5;222m"),lineNum:t=>q(t,"\x1B[38;5;241m"),dim:t=>q(t,"\x1B[2m"),bold:t=>q(t,"\x1B[1m"),green:t=>q(t,"\x1B[38;5;114m"),red:t=>q(t,"\x1B[38;5;203m"),yellow:t=>q(t,"\x1B[38;5;221m"),blue:t=>q(t,"\x1B[38;5;111m"),purple:t=>q(t,"\x1B[38;5;147m"),cyan:t=>q(t,"\x1B[38;5;152m"),orange:t=>q(t,"\x1B[38;5;209m"),white:t=>q(t,"\x1B[38;5;255m")};function ye(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}function xs(t,e,r=" "){let n=ye(t);return n<e?t+r.repeat(e-n):t}var L={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",ml:"\u251C",mr:"\u2524",mt:"\u252C",mb:"\u2534",mc:"\u253C"};var Ss=$(require("os")),Or=$(require("fs")),Ar=$(require("path"));function lg(){let t=[Ar.resolve(__dirname,"..","package.json"),Ar.resolve(__dirname,"..","..","package.json"),Ar.resolve(process.cwd(),"package.json")];for(let e of t)try{if(Or.existsSync(e)){let r=JSON.parse(Or.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var vs=lg(),Ol=process.stdout.isTTY===!0;function K(t,e=L.h){return e.repeat(t)}function cg(t,e,r){let n=Math.max(1,r-ye(t)-ye(e));return t+" ".repeat(n)+e}function Pl(t,e){let r=Math.min(ue(),86),n=e.replace(Ss.homedir(),"~"),s=r-2,i=y.border(L.tl+K(s)+L.tr),o=y.border(L.ml+K(s)+L.mr),a=y.border(L.bl+K(s)+L.br),l=m=>{let b=Math.max(0,s-2-ye(m));return y.border(L.v)+" "+m+" ".repeat(b)+" "+y.border(L.v)},c=(m,b)=>y.border(L.v)+" "+cg(m,b,s-2)+" "+y.border(L.v),f=" H A B L A S ",d=Math.max(0,Math.floor((s-ye(f))/2)),h=y.border(L.v)+" ".repeat(d)+y.strong(f)+" ".repeat(s-d-ye(f))+y.border(L.v),p="single-agent engineering runtime",u=Math.max(0,Math.floor((s-p.length)/2)),g=y.border(L.v)+" ".repeat(u)+y.muted(p)+" ".repeat(s-u-p.length)+y.border(L.v);return["",i,h,g,o,c(y.muted("v"+vs),y.muted(t)),l(y.muted("workspace ")+y.secondary(n)),o,l(y.secondary("Type your task \xB7 /help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C twice to exit")),a,""].join(`
|
|
180
|
+
`)}function Ml(t){let e=ue(),r=` Turn ${t} `,n=Math.floor((e-ye(r)-2)/2);return`
|
|
181
|
+
`+y.border(K(n))+y.borderHi(r)+y.border(K(e-n-ye(r)))+`
|
|
182
|
+
`}function xt(){return`
|
|
183
|
+
${y.accent("\u25C6")} ${y.strong("Hablas")}`}function jl(t){return`
|
|
184
|
+
${y.accent("\xB7")} ${y.secondary(t)}`}function Ll(t,e){let r=ug[t]??"\u2699";return` ${y.muted(r+" ")}${y.muted(t)} ${y.dim(e)}`}function Dl(t,e,r){let n=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`,s=t?y.success("\u2713"):y.error("\u2717"),i=e.slice(0,60).replace(/\n/g," "),o=e.length>60?"\u2026":"";return` ${s} ${y.dim(n+" ")}${y.muted(i+o)}`}var ug={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 Rl(t,e=2){let r=ue()-e-2,n=t.split(" "),s=[],i="";for(let o of n){let a=i.replace(/\x1b\[[0-9;]*m/g,""),l=o.replace(/\x1b\[[0-9;]*m/g,"");(a+" "+l).trim().length>r&&i?(s.push(" ".repeat(e)+i.trim()),i=o):i+=(i?" ":"")+o}return i.trim()&&s.push(" ".repeat(e)+i.trim()),s}function fg(t,e){let r=[],n=Math.max(28,ue()-6),s=e?` ${y.yellow(e)}`:"";r.push(` ${y.border(L.tl+K(n)+" ")}${s}`);let i=String(t.length).length;for(let o=0;o<t.length;o++){let a=y.lineNum(String(o+1).padStart(i));r.push(` ${y.border(L.v)} ${a} ${y.border("\u2502")} ${y.code(t[o])}`)}return r.push(` ${y.border(L.bl+K(n))}`),r}function dg(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 n=[];for(let c of r)c.forEach((f,d)=>{n[d]=Math.max(n[d]??0,ye(f))});let s=` ${y.border(L.tl+n.map(c=>K(c+2)).join(L.mt)+L.tr)}`,i=` ${y.border(L.ml+n.map(c=>K(c+2)).join(L.mc)+L.mr)}`,o=` ${y.border(L.bl+n.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" "+xs(u,n[p])+" "});return` ${y.border(L.v)}${d.join(y.border(L.v))}${y.border(L.v)}`},l=[s,a(r[0],!0)];r.length>1&&l.push(i);for(let c of r.slice(1))l.push(a(c));return l.push(o),l}function Ft(t){let e=t.split(`
|
|
185
|
+
`),r=[],n=!1,s="",i=[],o=[],a=()=>{i.length&&(r.push(...fg(i,s)),i=[],s="")},l=()=>{o.length&&(r.push(...dg(o)),o=[])};for(let c of e){if(c.trimStart().startsWith("```")){l(),n?(a(),n=!1):(n=!0,s=c.trimStart().slice(3).trim());continue}if(n){i.push(c);continue}if(/^\s*\|.*\|\s*$/.test(c)){o.push(c);continue}else l();if(!c.trim()){r.push("");continue}if(/^---+$/.test(c.trim())){r.push(` ${y.border(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,b=/\d+\./.test(u[2])?y.accent(u[2]):y.accent("\u25B8"),x=De(u[3]),w=Rl(x,g+5);r.push(" ".repeat(g+2)+b+" "+(w[0]?.trimStart()??""));for(let v=1;v<w.length;v++)r.push(" ".repeat(g+5)+w[v].trimStart());continue}r.push(...Rl(De(c),2))}return l(),n&&a(),`
|
|
181
186
|
`+r.join(`
|
|
182
187
|
`)+`
|
|
183
|
-
`}function
|
|
184
|
-
`)}
|
|
185
|
-
`)}function
|
|
186
|
-
`)}function
|
|
187
|
-
|
|
188
|
-
`)
|
|
189
|
-
`)}var
|
|
188
|
+
`}function Te(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 W(t){return` ${y.accent("\xB7")} ${y.secondary(t)}`}function Fl(){let t=Math.min(ue(),72),e=(r,n)=>` ${y.accent(xs(r,20))}${y.muted(n)}`;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("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")}`,""].join(`
|
|
189
|
+
`)}var Il=["\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(){!Ol||this.active||(this.active=!0,this.timer=setInterval(()=>{let e=Il[this.frame%Il.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),Ol&&process.stdout.write("\r\x1B[2K"))}};function _s(t){if(!t.toolsUsed.length)return"";let e=[""],r=Math.min(ue(),72);e.push(` ${y.border(K(r-4))}`);let n=t.durationMs<1e3?`${t.durationMs}ms`:`${(t.durationMs/1e3).toFixed(1)}s`,s=[];if(s.push(y.muted(`${t.toolsUsed.length} ops`)),t.filesChanged.length&&s.push(y.success(`${t.filesChanged.length} files`)),t.commandsRun.length&&s.push(y.accent(`${t.commandsRun.length} cmds`)),t.errors.length&&s.push(y.error(`${t.errors.length} errors`)),s.push(y.muted(n)),e.push(` ${s.join(y.muted(" \xB7 "))}`),t.filesChanged.length){for(let i of t.filesChanged.slice(0,6))e.push(` ${y.muted(" ")}${y.success("~")} ${y.secondary(i)}`);t.filesChanged.length>6&&e.push(` ${y.muted(" \u2026 and "+(t.filesChanged.length-6)+" more")}`)}return e.push(` ${y.border(K(r-4))}`),e.join(`
|
|
190
|
+
`)}function Nl(t){let e=Math.min(ue(),72),r=(i,o)=>` ${y.secondary(i.padEnd(18))}${y.primary(o)}`,n=t.workingDir.replace(Ss.homedir(),"~"),s=["",` ${y.strong("Runtime status")}`,` ${y.border(K(e-4))}`,r("model",t.model),r("provider",t.provider),r("workspace",n),r("connection",t.connected?y.success("online"):y.warning("offline"))];return t.messageCount!==void 0&&s.push(r("messages",String(t.messageCount))),t.totalTokens!==void 0&&s.push(r("tokens used",String(t.totalTokens))),t.toolCount!==void 0&&s.push(r("tools",String(t.toolCount)+" registered")),t.autoMode!==void 0&&s.push(r("auto mode",t.autoMode?y.warning("on"):y.success("off"))),s.push(""),s.join(`
|
|
191
|
+
`)}function Ul(){return`
|
|
192
|
+
${y.accent("Hablas")} ${y.muted("v"+vs)} ${y.secondary("\u2014 single-agent engineering runtime")}
|
|
193
|
+
`}function ql(){let t=Math.min(ue(),72);return["",` ${y.strong("Hablas")} ${y.muted("v"+vs)}`,` ${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(`
|
|
194
|
+
`)}var Rr=re.join(Wl.homedir(),".hablas","history"),Ir=500,pg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),hg=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],mg=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"]),Bl=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Pr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Hl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Ir,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-Ir),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${y.warning("?")} ${e} ${y.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
190
195
|
${y.error("\u26A0")} ${e}`),console.log(` ${y.muted("Type yes to confirm this dangerous action.")}
|
|
191
|
-
`),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=
|
|
192
|
-
`).filter(Boolean).slice(-
|
|
193
|
-
`),"utf-8")}catch{}}};var
|
|
196
|
+
`),(await this.prompt(` ${y.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Bl.filter(s=>s.startsWith(e));return[n.length?n:Bl,e]}for(let n of hg)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=re.dirname(s)||".",o=re.basename(s),a=re.resolve(this.workingDir,i),l=de.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(s))+re.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=de.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||pg.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(re.join(e,a.name),l,n,s,i+1);else{let c=re.extname(a.name).toLowerCase();(mg.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(l)}}}catch{}}loadHistory(){try{de.existsSync(Rr)&&(this.history=de.readFileSync(Rr,"utf-8").split(`
|
|
197
|
+
`).filter(Boolean).slice(-Ir))}catch{}}saveHistory(){try{let e=re.dirname(Rr);de.existsSync(e)||de.mkdirSync(e,{recursive:!0}),de.writeFileSync(Rr,this.history.slice(-Ir).join(`
|
|
198
|
+
`),"utf-8")}catch{}}};var gg={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},yg=`
|
|
194
199
|
## Reasoning Protocol
|
|
195
200
|
|
|
196
201
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -219,15 +224,15 @@ After receiving a tool result, think again:
|
|
|
219
224
|
- One tool call per turn. Wait for the result before the next call.
|
|
220
225
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
221
226
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
222
|
-
`.trim(),
|
|
227
|
+
`.trim(),wg=`
|
|
223
228
|
## Reasoning
|
|
224
229
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
225
230
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
226
|
-
`.trim(),
|
|
231
|
+
`.trim(),ks=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...gg,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
|
|
227
232
|
|
|
228
|
-
${
|
|
233
|
+
${wg}`:`${e}
|
|
229
234
|
|
|
230
|
-
${
|
|
235
|
+
${yg}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],n=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(n);a&&(r.push(a[1].trim()),n=n.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(n);return l&&(r.push(l[1].trim()),n=n.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
|
|
231
236
|
|
|
232
237
|
`).trim(),visibleContent:n.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let n=this.turnSteps[this.turnSteps.length-1];n&&(n.observation=e,r&&(n.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,n){return`
|
|
233
238
|
<self_eval>
|
|
@@ -250,18 +255,45 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
250
255
|
}
|
|
251
256
|
</self_eval>
|
|
252
257
|
`.trim()}parseSelfEval(e){let r=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let n of r){let s=e.match(n);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,n=typeof e.completed=="boolean"?e.completed:r>=7,s=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:n,rationale:s,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,r,n){return r?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${n.slice(0,300)}`,"</thinking>"].join(`
|
|
253
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function
|
|
254
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function
|
|
258
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function Nt(t){return new ks(t)}var bg=[{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}],$s=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,n){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of bg)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
|
|
259
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Ut(t=3){return new $s(t)}var Ce=$(require("fs")),jr=$(require("path")),Vl=$(require("os")),Mr=jr.join(Vl.homedir(),".hablas","model-formats.json");function xg(){try{if(Ce.existsSync(Mr))return JSON.parse(Ce.readFileSync(Mr,"utf-8"))}catch{}return{}}function Sg(t){try{let e=jr.dirname(Mr);Ce.existsSync(e)||Ce.mkdirSync(e,{recursive:!0}),Ce.writeFileSync(Mr,JSON.stringify(t,null,2),"utf-8")}catch{}}function zl(t,e){let r=0,n=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&n){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function qt(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function vg(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function _g(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=qt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function kg(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim());if(s.parameters||s.name){let i=qt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function $g(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=Kl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Kl(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,f;for(;(f=c.exec(o))!==null;){let h=f[1].toLowerCase(),p=f[2]??f[3]??f[4];l[h]=vg(p)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=d:n==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Tg(t){return Kl(t)}function Cg(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=qt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function Eg(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=zl(t,n.index);if(s)try{let i=JSON.parse(s),o=qt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function Ag(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=zl(t,n.index);if(s)try{let i=JSON.parse(s),o=qt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Og(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,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:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(t))!==null;){let 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 Ts=[{format:"xml_tool_call_wrapper",parse:$g},{format:"xml_prompt",parse:Tg},{format:"xml_tags",parse:_g},{format:"xml_parameters",parse:Og},{format:"hermes",parse:kg},{format:"markdown_json",parse:Cg},{format:"function_call",parse:Eg},{format:"json_object",parse:Ag}],Es=class{registry;constructor(){this.registry=xg()}parse(e,r,n){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return n&&this.learnFormat(n,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(n){let i=this.registry[n];if(i&&i.format!=="native"){let o=Ts.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(n,i.format),this.buildResult(a,s)}}}for(let{parse:i}of Ts){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of Ts)if(n(e).length>0)return r;return"unknown"}learnFormat(e,r){let n=this.registry[e];n&&n.format===r?(n.successCount++,n.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},Sg(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
|
|
255
260
|
|
|
256
261
|
`),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
|
|
257
262
|
|
|
258
|
-
`)}},_s=null;function ql(){return _s||(_s=new ks),_s}var vg=600,_g=2e3,kg=12e3,Ul=2;function $g(t,e,r){let s=ql().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function Tg(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:["edit_file","patch_file","search_and_replace"].includes(t)&&typeof e.path=="string"?`modify ${e.path}`:t==="read_file"&&typeof e.path=="string"?`read ${e.path}`:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):t==="remember"&&typeof e.key=="string"?`remember: ${String(e.key).slice(0,60)}`:t==="recall"&&typeof e.key=="string"?`recall: ${String(e.key).slice(0,60)}`:t==="search_memory"&&typeof e.query=="string"?`search memory: "${String(e.query).slice(0,50)}"`:t==="forget"&&typeof e.key=="string"?`forget: ${String(e.key).slice(0,60)}`:t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?`diff ${e.path}`:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?`log ${e.path}`:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Cg(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function Bl(t,e,r,n){let s=0,i=Date.now();for(;s<=Ul;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Ul)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,n.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function $s(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Pt(),m=t.errorRecovery??Lt(),p=u?[]:n.getOllamaTools(),f=r.getModel(),h=t.maxIterations??vg,g=[],S=[],b=[],x=new Map,v="",E=0,_=!1;for(;E<h;){if(E++,c?.aborted)return{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:"Aborted",completedNaturally:_};let T=d.buildBudgetWarningPrompt();T&&s.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let A;try{a.onModelStart?.(S.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),A=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(X){a.onModelStop?.();let te=X;if(te.name==="AbortError"||c?.aborted)return{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:"Aborted",completedNaturally:_};if(E<=1){a.onNotice?.(`Transient model error: ${te.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(P=>setTimeout(P,1e3)),E--;continue}return a.onError?.(te.message??"Model request failed"),{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!1,error:te.message,completedNaturally:_}}let k=A.message?.content||"",M=A.message?.tool_calls,q=d.parseThinking(k);q.hasThinking&&(d.recordStep({thought:q.thinking}),o.debug({thinking:q.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:D,displayContent:H}=$g(M,k,f);if(H&&H.trim()&&(v=H,await a.onAssistantText?.(H,e)),D.length===0){s.addAssistantMessage(k,void 0,e.role),_=!0;break}s.addAssistantMessage(k,D,e.role);let z=D.length;for(let X=0;X<D.length;X++){let te=D[X];if(!te?.function?.name)continue;let P=te.function.name,L=te.function.arguments||{},qt=n.getSafetyLevel(P)??"confirm";if(!n.get(P)){a.onNotice?.(`Unknown tool: ${P} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${P}". Available: ${n.getAll().map(G=>G.name).join(", ")}`);continue}if(await l(P,qt,L)==="skip"){s.addToolMessage(`Tool ${P} was skipped by policy/user.`);break}let dc=Tg(P,L),wt=P==="read_file"?JSON.stringify({path:L.path||"",start:L.start_line||"",end:L.end_line||""}):"";if(P==="read_file"&&wt&&x.has(wt)){let G=x.get(wt)||"";s.addToolMessage(G),d.recordObservation(G.slice(0,300),"Reused cached file read");continue}g.push(P),typeof L.path=="string"&&b.push(L.path),typeof L.from=="string"&&b.push(L.from),typeof L.to=="string"&&b.push(L.to),a.onToolStart?.(P,dc,L),a.onToolCall?.(),d.recordStep({thought:q.hasThinking?`Executing: ${P}`:"",action:P,actionInput:L});let K=await Bl(n,P,L,o);a.onToolEnd?.(P,K.success,K.error||K.output,K.duration,L);let Le;if(K.success)Le=Hl(P,K.output),d.recordObservation(Le.slice(0,300)),S.push({tool:P,success:!0,summary:K.output.slice(0,150)});else{let G=K.error||"Unknown error",Ge=m.analyze(P,G,L);if(Le=m.buildRecoveryMessage(Ge,G),d.recordObservation(`FAILED: ${G}`,`Recovery: ${Ge.strategy} \u2014 ${Ge.suggestion}`),o.info({tool:P,errorClass:Ge.errorClass,strategy:Ge.strategy},"Error recovery analysis"),S.push({tool:P,success:!1,summary:G.slice(0,150)}),Ge.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Je=await Bl(n,P,L,o);a.onToolEnd?.(P,Je.success,Je.output,Je.duration,L),Je.success&&(Le=Hl(P,Je.output),d.recordObservation(Le.slice(0,300),"Auto-retry succeeded"),S[S.length-1]={tool:P,success:!0,summary:Je.output.slice(0,150)})}}if(s.addToolMessage(Le),K.success&&P==="read_file"&&typeof L.path=="string"&&(i?.addFile(L.path,K.output),wt&&x.set(wt,Le)),K.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(P)&&typeof L.path=="string")for(let G of[...x.keys()])G.includes(`"path":"${String(L.path).replace(/\"/g,'\\"')}"`)&&x.delete(G);if(K.success&&P==="move_file")for(let G of[...x.keys()])(L.from&&G.includes(`"path":"${String(L.from).replace(/\"/g,'\\"')}"`)||L.to&&G.includes(`"path":"${String(L.to).replace(/\"/g,'\\"')}"`))&&x.delete(G);if(o.info({tool:P,success:K.success,durationMs:K.duration,retries:K.retries},"Tool executed"),!K.success&&Cg(K.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}z>1&&X<z-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return E>=h&&!_&&a.onNotice?.(`Reached max iterations (${h}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Pe(g),toolResults:S,touchedFiles:Pe(b),iterations:E,success:!0,completedNaturally:_}}function Pe(t){return[...new Set(t)]}function Hl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?Ot(e,kg):Ot(e,_g)}function Wl(t){return async(e,r)=>{let n=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm(`Proceed with ${n}?`)?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous(`Dangerous: ${n}`)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function Vl(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",s?.();for await(let u of e.streamChat(r.getMessages(),n))a+=u,i?.(u);return r.addAssistantMessage(a||""),o?.(),a}catch(u){if(l=u,u?.name==="AbortError"||n?.aborted)throw u;if(c===1)break}throw l||new Error("Text turn failed")}async function Ir(t,e){let r=vl(t),n=await pt(e.workingDir,e.config);if(e.session.updateSystemPrompt(mt(n,r.profile,e.workingDir)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let p=new ze("Hablas is thinking"),f=!1;p.start();try{let h=await Vl({client:e.client,session:e.session,onStart:()=>{p.start()},onChunk:g=>{f||(p.stop(),console.log(gt()),process.stdout.write(" "),f=!0),process.stdout.write(g)},onComplete:()=>{f&&process.stdout.write(`
|
|
259
|
-
`)}
|
|
260
|
-
`)}async function Gl(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(El());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Il());return;case"/version":console.log(Ol());return;case"/clear":e.session.clear(),console.log(ve("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(o.length===0){console.log(U("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(Al({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(U(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),Ze(e.config),console.log(ve(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=20,a=1,l="";if(s.length>0){let f=s[s.length-1],h=parseInt(f,10);!Number.isNaN(h)&&h>0?(a=h,l=s.slice(0,-1).join(" ").toLowerCase().trim()):l=s.join(" ").toLowerCase().trim()}let c=l?i.filter(f=>f.toLowerCase().includes(l)):i;if(c.length===0){console.log(le("No matching models found."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),m=(d-1)*o,p=c.slice(m,m+o);console.log(""),console.log(U(`Models${l?` \xB7 search: ${l}`:""} \xB7 page ${d}/${u}`)),console.log(""),p.forEach((f,h)=>{let g=f===e.client.getModel();console.log(` ${String(m+h+1).padStart(2," ")}. ${f}${g?" * active":""}`)}),console.log(""),u>1&&console.log(U(`Use /models ${l?l+" ":""}${d<u?d+1:u} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(U(`Provider: ${He(e.config)}`)),console.log(U(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ve("Connection OK"):je("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ne.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ne.defaultModel);else if(i==="custom"){if(!s[1]){console.log(le("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(le("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=nt(e.config);e.setClient(o),Ze(e.config),console.log(ve(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await Rr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Mr(i));return}case"/workspace":{console.log(""),console.log(_r(ft(e.workingDir))),console.log("");return}case"/memory":{let i=W().getStats(),o=W().getRecent(5);console.log(""),console.log(U(`Persistent memory \u2014 ${i.total??0} total entries`));let a=Object.entries(i).filter(([l])=>l!=="total");if(a.length>0)for(let[l,c]of a)console.log(U(` ${l}: ${c}`));if(o.length>0){console.log(U("Recent:"));for(let l of o)console.log(U(` \xB7 [${l.kind}] ${l.key.slice(0,60)}`))}console.log("");return}case"/remember":{if(s.length<2){console.log(le("Usage: /remember <key> <value>"));return}let i=s[0],o=s.slice(1).join(" ");W().remember({kind:"preference",key:`manual:${i}`,value:o,tags:["manual"],priority:"high"}),W().flush(),console.log(ve(`Remembered: ${i} = ${o.slice(0,60)}`));return}case"/forget":{if(s.length===0){console.log(le("Usage: /forget <key>"));return}let i=s.join(" "),o=W().forget(i)||W().forget(`manual:${i}`);W().flush(),console.log(o?ve(`Forgotten: ${i}`):le(`No memory found for: ${i}`));return}case"/memory-search":{if(s.length===0){console.log(le("Usage: /memory-search <query>"));return}let i=s.join(" "),o=W().search(i,{limit:8});if(o.length===0){console.log(U("No memories found."));return}console.log(U(`Found ${o.length} memories for "${i}":`));for(let a of o)console.log(U(` [${a.entry.kind}] ${a.entry.key.slice(0,55)} (${a.score.toFixed(2)})`)),console.log(U(` ${a.entry.value.replace(/\n/g," \u2014 ").slice(0,120)}`));return}default:console.log(le(`Unknown command: ${n}`))}}var ke=C(require("fs")),Cs=C(require("path"));function Es(t){let e=Cs.join(t,".hablas");return ke.existsSync(e)||ke.mkdirSync(e,{recursive:!0}),e}function Jl(t){return Cs.join(Es(t),"session.json")}function jr(t,e){let r=Jl(t);try{return ke.existsSync(r)?(e.fromJSON(ke.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Ft(t,e){let r=Jl(t);try{ke.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function Ql(t,e){Ks();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=nt(t);Es(r);let s=new at(r,t),i=new lt(t),o=await pt(r,t),a=new ut(mt(o,gs("hello"),r),t.historySize,t.contextBudget);jr(r,a);let l=new Er(r);console.log($l(t.model,r));let c=new ze("Connecting");c.start();let u=await n.checkConnection();if(c.stop(),u){let g=await n.listModels();console.log(ve(`online \xB7 ${He(t)} \xB7 ${g.length} models available`))}else console.log(le(`offline \xB7 ${He(t)} \xB7 you can still inspect local files and switch provider with /provider`));Yl.existsSync(Xl.join(r,".git"))||console.log(U("workspace mode: standalone (no git repository detected)")),console.log(U("Hablas is ready.")),console.log("");let d=0,m=0,p=Date.now(),f=new AbortController,h=0;for(process.on("SIGINT",()=>{let g=Date.now();g-h<1500&&(console.log(""),console.log(U(`Session summary \xB7 turns=${d} \xB7 toolCalls=${m} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),h=g,f.abort(),f=new AbortController,console.log(""),console.log(le("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let S=(await l.prompt(" \u203A ")).trim();if(S){if(S.startsWith("/")){let b=await Gl(S,{config:t,client:n,setClient:x=>{n=x},session:a,workingDir:r});if(Ft(r,a),b==="quit")break;continue}d+=1,console.log(Tl(d)),f=new AbortController;try{await Ir(S,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{m+=1}}),Ft(r,a)}catch(b){if(b?.name==="AbortError")continue;console.log(je(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}hl(),l.close()}var Eg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Ag=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Og=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Ig=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,Rg=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Mg=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app|image|images|photo|photos|wallpaper|background|hero)\b/i,jg=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Pg=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,Zl=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function ec(t){let e=t.trim(),r=e.toLowerCase(),n=Ag.test(r),s=Og.test(r),i=Ig.test(r)||Rg.test(r),o=Mg.test(r),a=jg.test(r),l=i||n||s||o&&e.length>18&&!Zl.test(r)&&!a,c=a&&!i&&!n&&!s,u=Pg.test(r)||o,d=!l&&!c&&(Zl.test(r)||e.endsWith("?"));return Eg.test(e)&&!u&&!l&&!c?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function tc(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=nt(e),i=new at(n,e),o=new lt(e),a=await pt(n,e),l=new ut(mt(a,ec(t)),e.historySize,e.contextBudget);jr(n,l),await Ir(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Ft(n,l)}var Pr=C(require("fs")),Ke=C(require("path")),Lg=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],Dg=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Fg=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Ng(t,e){let r=[],n=e.split(`
|
|
261
|
-
`)
|
|
262
|
-
`)
|
|
263
|
-
`)
|
|
263
|
+
`)}},Cs=null;function Gl(){return Cs||(Cs=new Es),Cs}var Rg=600,Ig=2e3,Pg=12e3,Jl=2;function Mg(t,e,r){let s=Gl().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function jg(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 Lg(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 Yl(t,e,r,n){let s=0,i=Date.now();for(;s<=Jl;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Jl)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 As(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:f}=t,d=t.reactEngine??Nt(),h=t.errorRecovery??Ut(),p=f?[]:n.getOllamaTools(),u=r.getModel(),g=t.maxIterations??Rg,m=[],b=[],x=[],w=new Map,v="",_=0,C=!1;for(;_<g;){if(_++,c?.aborted)return{output:v,toolsUsed:Ne(m),toolResults:b,touchedFiles:Ne(x),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let E=d.buildBudgetWarningPrompt();E&&s.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let R;try{a.onModelStart?.(b.length>0?"Hablas is deciding the next step":"Hablas is thinking",e),R=await r.chatWithTools(s.getMessages(),p,c),a.onModelStop?.()}catch(ee){a.onModelStop?.();let se=ee;if(se.name==="AbortError"||c?.aborted)return{output:v,toolsUsed:Ne(m),toolResults:b,touchedFiles:Ne(x),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){a.onNotice?.(`Transient model error: ${se.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(M=>setTimeout(M,1e3)),_--;continue}return a.onError?.(se.message??"Model request failed"),{output:v,toolsUsed:Ne(m),toolResults:b,touchedFiles:Ne(x),iterations:_,success:!1,error:se.message,completedNaturally:C}}let T=R.message?.content||"",j=R.message?.tool_calls,B=d.parseThinking(T);B.hasThinking&&(d.recordStep({thought:B.thinking}),o.debug({thinking:B.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:F,displayContent:z}=Mg(j,T,u);if(z&&z.trim()&&(v=z,await a.onAssistantText?.(z,e)),F.length===0){s.addAssistantMessage(T,void 0,e.role),C=!0;break}s.addAssistantMessage(T,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 M=se.function.name,D=se.function.arguments||{},Wt=n.getSafetyLevel(M)??"confirm";if(!n.get(M)){a.onNotice?.(`Unknown tool: ${M} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${M}". Available: ${n.getAll().map(X=>X.name).join(", ")}`);continue}if(await l(M,Wt,D)==="skip"){s.addToolMessage(`Tool ${M} was skipped by policy/user.`);break}let Ec=jg(M,D),vt=M==="read_file"?JSON.stringify({path:D.path||"",start:D.start_line||"",end:D.end_line||""}):"";if(M==="read_file"&&vt&&w.has(vt)){let X=w.get(vt)||"";s.addToolMessage(X),d.recordObservation(X.slice(0,300),"Reused cached file read");continue}m.push(M),typeof D.path=="string"&&x.push(D.path),typeof D.from=="string"&&x.push(D.from),typeof D.to=="string"&&x.push(D.to),a.onToolStart?.(M,Ec,D),a.onToolCall?.(),d.recordStep({thought:B.hasThinking?`Executing: ${M}`:"",action:M,actionInput:D});let Y=await Yl(n,M,D,o);a.onToolEnd?.(M,Y.success,Y.error||Y.output,Y.duration,D);let Ue;if(Y.success)Ue=Xl(M,Y.output),d.recordObservation(Ue.slice(0,300)),b.push({tool:M,success:!0,summary:Y.output.slice(0,150)});else{let X=Y.error||"Unknown error",Qe=h.analyze(M,X,D);if(Ue=h.buildRecoveryMessage(Qe,X),d.recordObservation(`FAILED: ${X}`,`Recovery: ${Qe.strategy} \u2014 ${Qe.suggestion}`),o.info({tool:M,errorClass:Qe.errorClass,strategy:Qe.strategy},"Error recovery analysis"),b.push({tool:M,success:!1,summary:X.slice(0,150)}),Qe.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Ze=await Yl(n,M,D,o);a.onToolEnd?.(M,Ze.success,Ze.output,Ze.duration,D),Ze.success&&(Ue=Xl(M,Ze.output),d.recordObservation(Ue.slice(0,300),"Auto-retry succeeded"),b[b.length-1]={tool:M,success:!0,summary:Ze.output.slice(0,150)})}}if(s.addToolMessage(Ue),Y.success&&M==="read_file"&&typeof D.path=="string"&&(i?.addFile(D.path,Y.output),vt&&w.set(vt,Ue)),Y.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(M)&&typeof D.path=="string")for(let X of[...w.keys()])X.includes(`"path":"${String(D.path).replace(/\"/g,'\\"')}"`)&&w.delete(X);if(Y.success&&M==="move_file")for(let X of[...w.keys()])(D.from&&X.includes(`"path":"${String(D.from).replace(/\"/g,'\\"')}"`)||D.to&&X.includes(`"path":"${String(D.to).replace(/\"/g,'\\"')}"`))&&w.delete(X);if(o.info({tool:M,success:Y.success,durationMs:Y.duration,retries:Y.retries},"Tool executed"),!Y.success&&Lg(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:b,touchedFiles:Ne(x),iterations:_,success:!0,completedNaturally:C}}function Ne(t){return[...new Set(t)]}function Xl(t,e){return t==="read_file"?e:t==="web_search"||t==="scrape_url"||t==="extract_links"||t==="read_pdf"?Mt(e,Pg):Mt(e,Ig)}function Ql(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 Zl={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"},Dg={kind:"research",goal:"Research APIs, patterns, or documentation needed for this task",toolHints:["web_search","scrape_url"],successCriteria:"Needed documentation found, approach confirmed"},Fg={kind:"verify",goal:"Build, test, and lint the changes to confirm correctness",toolHints:["run_command","detect_bugs"],successCriteria:"Build passes, no new errors introduced"},Ng={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"},Ug=0;function qg(){return`step_${Date.now()}_${++Ug}`}function Ee(t,e,r={}){return{id:qg(),stepNum:t,status:"pending",...e,...r}}function ec(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++,Zl)):c&&r.push(Ee(n++,Zl,{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++,Dg)),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 f=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: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(n++,Fg)),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++,Ng)),{id:`plan_${Date.now()}`,intent:t.intent,complexity:t.complexity,steps:r,createdAt:Date.now(),activeStepIndex:0,totalSteps:r.length}}function tc(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(`
|
|
264
|
+
`)}function rc(t,e){let r=new Set(e);for(let s of t.steps){if(s.status!=="pending"&&s.status!=="active")continue;let i=new Set(s.toolHints);e.filter(a=>i.has(a)).length>0&&(s.status="active",(s.kind==="understand"&&(r.has("list_dir")||r.has("read_file")||r.has("git_status"))||s.kind==="research"&&r.has("web_search")||s.kind==="implement"&&(r.has("write_file")||r.has("edit_file")||r.has("patch_file")||r.has("search_and_replace"))||s.kind==="verify"&&r.has("run_command")||s.kind==="commit"&&r.has("remember")||s.kind==="plan_detail"&&(r.has("read_file")||r.has("list_dir"))||s.kind==="report")&&(s.status="done"))}let n=t.steps.findIndex(s=>s.status==="pending");t.activeStepIndex=n===-1?t.steps.length:n,t.steps.every(s=>s.status==="done"||s.status==="skipped")&&(t.completedAt=Date.now())}function Os(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 Rs(t){return t.split(`
|
|
265
|
+
`).length}function nc(t,e){return t.split(`
|
|
266
|
+
`).slice(-e).join(`
|
|
267
|
+
`)}function sc(t,e){return t.split(`
|
|
268
|
+
`).slice(0,e).join(`
|
|
269
|
+
`)}function Bg(t,e){let r=Rs(t);if(r<=30)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.path??""),i=(t.match(/^export\s+(const|function|class|interface|type|enum)\s+(\w+)/gm)??[]).map(l=>l.split(/\s+/).pop()).filter(Boolean).slice(0,8),o=i.length?` \u2014 exports: ${i.join(", ")}`:"",a=`[file read: ${n} (${r} lines)${o}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"file_read"}}function Hg(t,e){let r=t.split(`
|
|
270
|
+
`).filter(Boolean);if(r.length<=20)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.path??"."),s=r.filter(l=>!l.endsWith("/")).length,i=r.filter(l=>l.endsWith("/")).length,o=r.slice(0,5).join(", "),a=`[list_dir: ${n} \u2014 ${s} files, ${i} dirs. Sample: ${o}${r.length>5?", \u2026":""}]`;return{original:t,compressed:a,savedChars:t.length-a.length,strategy:"list_dir"}}function Wg(t,e){let r=t.split(`
|
|
271
|
+
`);if(r.length<=15)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let n=String(e.command??"").slice(0,60),s=nc(t,8),i=`[run_command: ${n}
|
|
272
|
+
\u2026 (${r.length} lines total, showing last 8):
|
|
273
|
+
${s}]`;return{original:t,compressed:i,savedChars:t.length-i.length,strategy:"run_command"}}function Vg(t){if(t.length<=1e3)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=t.match(/https?:\/\/[^\s"')>]+/g)??[],r=[...new Set(e)].slice(0,5),s=`[web_search results:
|
|
274
|
+
Titles: ${t.split(`
|
|
275
|
+
`).filter(i=>i.trim().length>10&&i.trim().length<100&&!i.startsWith("http")).slice(0,5).join(" | ")}
|
|
276
|
+
URLs: ${r.join(`
|
|
277
|
+
`)}]`;return{original:t,compressed:s,savedChars:t.length-s.length,strategy:"web_search"}}function zg(t){let e=t.split(`
|
|
278
|
+
`);if(e.length<=40)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let r=e.filter(a=>a.startsWith("+++")||a.startsWith("---")||a.startsWith("diff --git")),n=[...new Set(r.map(a=>a.split(" ").pop()).filter(Boolean))].slice(0,8),s=e.filter(a=>a.startsWith("+")&&!a.startsWith("+++")).length,i=e.filter(a=>a.startsWith("-")&&!a.startsWith("---")).length,o=`[git_diff: ${n.join(", ")} \u2014 +${s} -${i} lines (${e.length} total diff lines)]`;return{original:t,compressed:o,savedChars:t.length-o.length,strategy:"git_diff"}}function Kg(t){if(t.length<=500)return{original:t,compressed:t,savedChars:0,strategy:"passthrough"};let e=sc(t,10)+(Rs(t)>10?`
|
|
279
|
+
\u2026`:"");return{original:t,compressed:e,savedChars:t.length-e.length,strategy:"git_log"}}function ic(t,e,r={}){if(e.length<400)return{original:e,compressed:e,savedChars:0,strategy:"passthrough"};switch(t){case"read_file":return Bg(e,r);case"list_dir":return Hg(e,r);case"run_command":return Wg(e,r);case"web_search":return Vg(e);case"git_diff":return zg(e);case"git_log":return Kg(e);default:if(e.length>2e3){let n=sc(e,10),s=nc(e,5),i=`${n}
|
|
280
|
+
\u2026 (compressed \u2014 ${Rs(e)} lines) \u2026
|
|
281
|
+
${s}`;return{original:e,compressed:i,savedChars:e.length-i.length,strategy:"generic_trim"}}return{original:e,compressed:e,savedChars:0,strategy:"passthrough"}}}async function oc(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",s?.();for await(let f of e.streamChat(r.getMessages(),n))a+=f,i?.(f);return r.addAssistantMessage(a||""),o?.(),a}catch(f){if(l=f,f?.name==="AbortError"||n?.aborted)throw f;if(c===1)break}throw l||new Error("Text turn failed")}function Gg(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 ac(t,e){let r=[],n=[],s=[];for(let i of t){if(["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file","move_file"].includes(i.tool)){let o=i.summary.replace(/^(create|modify|delete|move)\s+/,"");r.includes(o)||r.push(o)}["run_command","execute_code"].includes(i.tool)&&n.push(i.summary.slice(0,60)),i.success||s.push(`${i.tool}: ${i.summary.slice(0,80)}`)}return{toolsUsed:[...new Set(t.map(i=>i.tool))],filesChanged:r,commandsRun:n,durationMs:e,errors:s}}async function Lr(t,e){let n=Cl(t).profile,s=Date.now(),i=await wt(e.workingDir,e.config),o=bt(i,n,e.workingDir);if((n.complexity==="complex"||n.complexity==="epic")&&n.needsTools)try{let b=V().search(n.intent,{limit:5});if(b.length>0){let x=b.map(w=>` - [${w.entry.key}] ${w.entry.value}`).join(`
|
|
282
|
+
`);o+=`
|
|
283
|
+
|
|
284
|
+
\u2550\u2550\u2550 RELEVANT MEMORY \u2550\u2550\u2550
|
|
285
|
+
Past decisions and preferences:
|
|
286
|
+
${x}
|
|
287
|
+
\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`}}catch{}let a=null;if(n.needsTools&&(n.complexity==="complex"||n.complexity==="epic")&&n.kind==="implementation"){a=ec(n,t);let m=tc(a);o+=`
|
|
288
|
+
|
|
289
|
+
${m}`;let b=Os(a);console.log(` ${y.accent("\u25C9")} ${y.secondary("Execution plan ready")} ${y.muted(`\xB7 ${b.total} steps \xB7 complexity: ${n.complexity}`)}`)}if(e.session.updateSystemPrompt(o),n.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),n.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${n.kind}`]}),!n.needsTools){let m=new Ye("Thinking"),b=!1;m.start();try{let x=await oc({client:e.client,session:e.session,onStart:()=>m.start(),onChunk:w=>{b||(m.stop(),console.log(xt()),process.stdout.write(" "),b=!0),process.stdout.write(w)},onComplete:()=>{b&&process.stdout.write(`
|
|
290
|
+
`)}});b||(m.stop(),console.log(xt()),console.log(Ft(x)))}catch(x){m.stop(),console.log(Fe(x?.message||"Text turn failed"))}return}let l=Nt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),c=Ut(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),n.kind!=="implementation"&&(console.log(xt()),console.log(Ft(m)))},onToolStart:(m,b)=>{d.stop();let x=Gg(m);x!==h&&(console.log(jl(x)),h=x),console.log(Ll(m,b))},onToolEnd:(m,b,x,w)=>{let v=ic(m,x),_=v.savedChars>200?v.compressed:x;console.log(Dl(b,_,w))},onNotice:(m,b)=>{console.log(b==="retry"?W(`Retrying: ${m}`):W(m))},onError:m=>console.log(Fe(m)),onToolCall:()=>e.onToolCall?.()},u=Ql({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 As({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){rc(a,g.toolsUsed);let m=Os(a);m.done>0&&console.log(`
|
|
291
|
+
${y.success("\u2713")} ${y.muted(`Plan: ${m.done}/${m.total} steps complete`)}`)}if(n.kind==="implementation"&&g.toolsUsed.length>0&&f.length>0&&(console.log(xt()),console.log(Ft(f[f.length-1]))),g.toolsUsed.length>0){let m=Date.now()-s,b=ac(g.toolResults,m),x=_s(b);x&&console.log(x)}try{V().flush()}catch{}if(n.kind==="implementation"&&g.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools and modify actual files. Retry now.",{priority:"critical",tags:["system-correction","force-tools"]});let m=[],b=await As({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 x=>{m.push(x)}},safetyPolicy:u,reactEngine:Nt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Ut(3),skipTools:!1});if(b.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(Ft(m[m.length-1]));let x=ac(b.toolResults,Date.now()-s),w=_s(x);w&&console.log(w)}}}var Is=$(require("fs")),lc=$(require("path")),we=$(require("os")),cc=require("child_process");async function Dr(t){let e=[],r=process.version,n=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:n>=20?"ok":n>=18?"warn":"error",message:n>=20?`${r} (recommended)`:n>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let s=lc.join(we.homedir(),".hablas");if(e.push({name:"Config directory",status:Is.existsSync(s)?"ok":"warn",message:Is.existsSync(s)?s:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=we.homedir();if(process.platform!=="win32"){let a=(0,cc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${we.platform()} ${we.arch()} \u2014 ${we.cpus().length} cores, ${Math.round(we.totalmem()/1024/1024/1024)}GB RAM`}),e}function Fr(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let c=`${r[l.status]}${e[l.status]}${n}`,f=l.name.padEnd(18);i.push(` ${c} ${f}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
|
|
292
|
+
`)}async function uc(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Fl());return;case"/exit":case"/quit":return"quit";case"/about":console.log(ql());return;case"/version":console.log(Ul());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(Nl({model:e.client.getModel(),provider:Ke(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(W(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),nt(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 u=s[s.length-1],g=parseInt(u,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(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(W(`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(W(`Use /models ${l?l+" ":""}${d<f?d+1:f} for next page.`)),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(W(`Provider: ${Ke(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"):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,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=at(e.config);e.setClient(o),nt(e.config),console.log(Te(`Provider switched to ${Ke(e.config)}`));return}case"/doctor":{let i=await Dr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Fr(i));return}case"/workspace":{console.log(""),console.log(Er(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=$(require("fs")),Ps=$(require("path"));function Ms(t){let e=Ps.join(t,".hablas");return Ae.existsSync(e)||Ae.mkdirSync(e,{recursive:!0}),e}function fc(t){return Ps.join(Ms(t),"session.json")}function Nr(t,e){let r=fc(t);try{return Ae.existsSync(r)?(e.fromJSON(Ae.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function Bt(t,e){let r=fc(t);try{Ae.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function hc(t,e){Zs();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=at(t);Ms(r);let s=new dt(r,t),i=new pt(t),o=await wt(r,t),a=new mt(bt(o,bs("hello"),r),t.historySize,t.contextBudget);Nr(r,a);let l=new Pr(r);console.log(Pl(t.model,r));let c=new Ye("Connecting");c.start();let f=await n.checkConnection();if(c.stop(),f){let m=await n.listModels();console.log(Te(`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`));dc.existsSync(pc.join(r,".git"))||console.log(W("workspace mode: standalone (no git repository detected)")),console.log(W("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(W(`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 b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){let x=await uc(b,{config:t,client:n,setClient:w=>{n=w},session:a,workingDir:r});if(Bt(r,a),x==="quit")break;continue}d+=1,console.log(Ml(d)),u=new AbortController;try{await Lr(b,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}}),Bt(r,a)}catch(x){if(x?.name==="AbortError")continue;console.log(Fe(x?.message||"Turn failed")),e.error(x,"interactive turn failed")}}}xl(),l.close()}var Jg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Yg=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Xg=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Qg=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,Zg=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,ey=/\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,ty=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,ry=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,mc=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function gc(t){let e=t.trim(),r=e.toLowerCase(),n=Yg.test(r),s=Xg.test(r),i=Qg.test(r)||Zg.test(r),o=ey.test(r),a=ty.test(r),l=i||n||s||o&&e.length>18&&!mc.test(r)&&!a,c=a&&!i&&!n&&!s,f=ry.test(r)||o,d=!l&&!c&&(mc.test(r)||e.endsWith("?"));return Jg.test(e)&&!f&&!l&&!c?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:c?{kind:"analysis",needsTools:f,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||f?{kind:"read",needsTools:f,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:f,reason:f?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}async function yc(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=at(e),i=new dt(n,e),o=new pt(e),a=await wt(n,e),l=new mt(bt(a,gc(t)),e.historySize,e.contextBudget);Nr(n,l),await Lr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1}),Bt(n,l)}var Ur=$(require("fs")),Xe=$(require("path")),ny=[{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"}],sy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),iy=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function oy(t,e){let r=[],n=e.split(`
|
|
293
|
+
`);for(let{pattern:s,name:i,severity:o}of ny){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let c=e.substring(0,a.index).split(`
|
|
294
|
+
`).length,f=n[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 ay(t,e){let r=[],n=e.split(`
|
|
295
|
+
`),s=Xe.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function wc(t,e=[]){try{let r=Ur.readdirSync(t,{withFileTypes:!0});for(let n of r){if(sy.has(n.name))continue;let s=Xe.join(t,n.name);if(n.isDirectory())wc(s,e);else if(n.isFile()){let i=Xe.extname(n.name);iy.has(i)||e.push(s)}}}catch{}return e}function bc(t){let e=Date.now(),r=wc(t),n=[];for(let o of r)try{let a=Ur.readFileSync(o,"utf-8"),l=Xe.relative(t,o),c=oy(l,a);n.push(...c);let f=ay(l,a);n.push(...f)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function xc(t){let e=[];if(e.push(`
|
|
264
296
|
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((n,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[n.severity]-i[s.severity]}).slice(0,10);for(let n of r){let s=n.severity==="critical"?"\u{1F534}":n.severity==="high"?"\u{1F7E0}":n.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${n.severity.toUpperCase()}] ${n.message}`),e.push(` File: ${n.file}${n.line?`:${n.line}`:""}`),e.push(` Fix: ${n.suggestion}`),e.push("")}}return e.join(`
|
|
265
|
-
`)}var
|
|
297
|
+
`)}var St=$(require("fs")),js=$(require("path")),vc=$(require("os")),ly=js.join(vc.homedir(),".hablas"),Sc=js.join(ly,"analytics.json");function _c(){try{if(St.existsSync(Sc))return JSON.parse(St.readFileSync(Sc,"utf-8"))}catch{}return cy()}function cy(){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 kc(t){let e=[];e.push(`
|
|
266
298
|
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[s,i]of r)e.push(` @${s}: ${i} uses`);e.push("")}let n=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Commands:");for(let[s,i]of n)e.push(` ${s}: ${i} calls`)}return e.join(`
|
|
267
|
-
`)}var
|
|
299
|
+
`)}var $c=$(require("readline"));var Z="\x1B[36m",qr="\x1B[32m",Oe="\x1B[33m",P="\x1B[2m",Re="\x1B[1m",k="\x1B[0m",uy="\x1B[35m";function G(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function fy(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var Ht={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function Tc(t){let e=$c.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${k}`),console.log(`${Re}${Z} hablas \u2014 Setup Wizard${k}`),console.log(`${P} Configure your AI provider and model${k}`),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${k}`),console.log(),console.log(`${Re} Choose your setup:${k}`),console.log(),console.log(` ${uy}${Re}1${k}. ${Re}Hablas Integrated Engine${k} ${qr}(instant \u2014 no setup needed)${k}`),console.log(` ${P}Pre-configured cloud AI, ready to use immediately${k}`),console.log(),console.log(` ${Z}${Re}2${k}. ${Re}Custom Provider${k} ${P}(bring your own API key)${k}`),console.log(` ${P}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${k}`),console.log(),(await G(e,` ${P}Your choice (1-2):${k} `)).trim()){case"1":{t.provider=Ht.provider,t.apiUrl=Ht.apiUrl,t.apiKey=fy(),t.model=Ht.model,nt(t),console.log(),console.log(`${qr} \u2713 Hablas Integrated Engine activated!${k}`),console.log(`${P} Model: ${Ht.model}${k}`),console.log(`${P} API: ${Ht.apiUrl}${k}`),console.log(`${P} No API key needed \u2014 everything is pre-configured.${k}`);break}case"2":{switch(console.log(),console.log(`${P} Select your provider:${k}`),console.log(` ${Z}a${k}. Ollama (local, free, private)`),console.log(` ${Z}b${k}. OpenAI API`),console.log(` ${Z}c${k}. Groq (fast, free tier)`),console.log(` ${Z}d${k}. OpenRouter (many models)`),console.log(` ${Z}e${k}. Together AI`),console.log(` ${Z}f${k}. DeepSeek`),console.log(` ${Z}g${k}. Custom OpenAI-compatible API`),console.log(` ${Z}h${k}. NVIDIA NIM (powerful cloud models)`),console.log(),(await G(e,` ${P}Your choice (a-h):${k} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await G(e,` ${P}Ollama host [http://localhost:11434]:${k} `)).trim(),i=(await G(e,` ${P}Model [qwen2.5-coder:7b]:${k} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await G(e,` ${P}OpenAI API Key (sk-...):${k} `)).trim(),i=(await G(e,` ${P}Model [gpt-4o]:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await G(e,` ${P}Groq API Key (gsk_...):${k} `)).trim(),i=(await G(e,` ${P}Model [llama-3.3-70b-versatile]:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await G(e,` ${P}OpenRouter API Key (sk-or-...):${k} `)).trim(),i=(await G(e,` ${P}Model [anthropic/claude-3.5-sonnet]:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await G(e,` ${P}Together API Key:${k} `)).trim(),i=(await G(e,` ${P}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await G(e,` ${P}DeepSeek API Key:${k} `)).trim(),i=(await G(e,` ${P}Model [deepseek-chat]:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await G(e,` ${P}API base URL:${k} `)).trim(),i=(await G(e,` ${P}API key (optional):${k} `)).trim(),o=(await G(e,` ${P}Model ID:${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 URL is required \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await G(e,` ${P}NVIDIA API Key (nvapi-...):${k} `)).trim();if(!s){console.log(`${Oe} \u26A0 No key provided \u2014 cancelled${k}`),console.log(`${P} Get your key at: https://build.nvidia.com/${k}`),e.close();return}console.log(),console.log(`${P} Available NVIDIA models:${k}`),oe.models.forEach((a,l)=>{console.log(` ${Z}${l+1}${k}. ${a}`)}),console.log();let i=(await G(e,` ${P}Model number [1]:${k} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=oe.apiUrl,t.apiKey=s,t.model=oe.models[o]||oe.defaultModel;break}default:console.log(`${Oe} \u26A0 Invalid choice${k}`),e.close();return}nt(t),console.log(),console.log(`${qr} \u2713 Custom provider configured successfully${k}`),console.log(`${P} Provider: ${t.provider}${k}`),console.log(`${P} Model: ${t.model}${k}`);break}default:console.log(`${Oe} \u26A0 Invalid choice \u2014 please select 1 or 2${k}`),e.close();return}console.log(),console.log(`${Re}${qr} \u2713 Setup complete!${k}`),console.log(`${P} Use ${Z}hablas${k}${P} for interactive mode or ${Z}hablas run "..."${k}${P} for one-shot execution.${k}`),console.log(),e.close()}var Cc=da(),ne=new Xs;ne.name("hablas").description(`Hablas CLI v${Cc} \u2014 single-agent engineering runtime for the terminal.`).version(Cc).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");ne.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ne.opts(),r=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 n=es(r);await yc(t,r,n)});ne.command("doctor").description("Run system diagnostics").action(async()=>{let t=ne.opts(),e=rt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Dr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Fr(r))});ne.command("info").description("Show workspace information").action(async()=>{let t=ne.opts(),e=rt({project:t.project});console.log(""),console.log(Er(gt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ne.command("security").description("Run a security scan on the current project").action(async()=>{let t=ne.opts(),e=rt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(xc(bc(r)))});ne.command("stats").description("Show local usage statistics").action(async()=>{console.log(kc(_c()))});ne.action(async()=>{let t=ne.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 Tc(e);return}let r=es(e);await hc(e,r)});ne.parse();
|