hablas-ai 2.5.3 → 2.5.4
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 +159 -159
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,149 +1,149 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var su=Object.create;var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(l=l.concat([n.wrap(u,
|
|
4
|
-
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,s
|
|
2
|
+
"use strict";var su=Object.create;var ni=Object.defineProperty;var iu=Object.getOwnPropertyDescriptor;var ou=Object.getOwnPropertyNames;var au=Object.getPrototypeOf,cu=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var lu=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ou(e))!cu.call(t,s)&&s!==n&&ni(t,s,{get:()=>e[s],enumerable:!(r=iu(e,s))||r.enumerable});return t};var k=(t,e,n)=>(n=t!=null?su(au(t)):{},lu(e||!t||!t.__esModule?ni(n,"default",{value:t,enumerable:!0}):n,t));var Pt=j(ir=>{var on=class extends Error{constructor(e,n,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=n,this.exitCode=e,this.nestedError=void 0}},sr=class extends on{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ir.CommanderError=on;ir.InvalidArgumentError=sr});var an=j(ar=>{var{InvalidArgumentError:wu}=Pt(),or=class{constructor(e,n){switch(this.description=n||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new wu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function bu(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}ar.Argument=or;ar.humanReadableArgName=bu});var lr=j(Si=>{var{humanReadableArgName:xu}=an(),cr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let n=e.commands.filter(s=>!s._hidden),r=e._getHelpCommand();return r&&!r._hidden&&n.push(r),this.sortSubcommands&&n.sort((s,i)=>s.name().localeCompare(i.name())),n}compareOptions(e,n){let r=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return r(e).localeCompare(r(n))}visibleOptions(e){let n=e.options.filter(s=>!s.hidden),r=e._getHelpOption();if(r&&!r.hidden){let s=r.short&&e._findOption(r.short),i=r.long&&e._findOption(r.long);!s&&!i?n.push(r):r.long&&!i?n.push(e.createOption(r.long,r.description)):r.short&&!s&&n.push(e.createOption(r.short,r.description))}return this.sortOptions&&n.sort(this.compareOptions),n}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let n=[];for(let r=e.parent;r;r=r.parent){let s=r.options.filter(i=>!i.hidden);n.push(...s)}return this.sortOptions&&n.sort(this.compareOptions),n}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(n=>{n.description=n.description||e._argsDescription[n.name()]||""}),e.registeredArguments.find(n=>n.description)?e.registeredArguments:[]}subcommandTerm(e){let n=e.registeredArguments.map(r=>xu(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(n?" "+n:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,n){return n.visibleCommands(e).reduce((r,s)=>Math.max(r,n.subcommandTerm(s).length),0)}longestOptionTermLength(e,n){return n.visibleOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,n){return n.visibleGlobalOptions(e).reduce((r,s)=>Math.max(r,n.optionTerm(s).length),0)}longestArgumentTermLength(e,n){return n.visibleArguments(e).reduce((r,s)=>Math.max(r,n.argumentTerm(s).length),0)}commandUsage(e){let n=e._name;e._aliases[0]&&(n=n+"|"+e._aliases[0]);let r="";for(let s=e.parent;s;s=s.parent)r=s.name()+" "+r;return r+n+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let n=[];return e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&n.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&n.push(`env: ${e.envVar}`),n.length>0?`${e.description} (${n.join(", ")})`:e.description}argumentDescription(e){let n=[];if(e.argChoices&&n.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&n.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),n.length>0){let r=`(${n.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,n){let r=n.padWidth(e,n),s=n.helpWidth||80,i=2,o=2;function a(d,m){if(m){let g=`${d.padEnd(r+o)}${m}`;return n.wrap(g,s-i,r+o)}return d}function c(d){return d.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${n.commandUsage(e)}`,""],u=n.commandDescription(e);u.length>0&&(l=l.concat([n.wrap(u,s,0),""]));let f=n.visibleArguments(e).map(d=>a(n.argumentTerm(d),n.argumentDescription(d)));f.length>0&&(l=l.concat(["Arguments:",c(f),""]));let p=n.visibleOptions(e).map(d=>a(n.optionTerm(d),n.optionDescription(d)));if(p.length>0&&(l=l.concat(["Options:",c(p),""])),this.showGlobalOptions){let d=n.visibleGlobalOptions(e).map(m=>a(n.optionTerm(m),n.optionDescription(m)));d.length>0&&(l=l.concat(["Global Options:",c(d),""]))}let h=n.visibleCommands(e).map(d=>a(n.subcommandTerm(d),n.subcommandDescription(d)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,n){return Math.max(n.longestOptionTermLength(e,n),n.longestGlobalOptionTermLength(e,n),n.longestSubcommandTermLength(e,n),n.longestArgumentTermLength(e,n))}wrap(e,n,r,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=n-r;if(a<s)return e;let c=e.slice(0,r),l=e.slice(r).replace(`\r
|
|
5
5
|
`,`
|
|
6
|
-
`),u=" ".repeat(
|
|
6
|
+
`),u=" ".repeat(r),p="\\s\u200B",h=new RegExp(`
|
|
7
7
|
|.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),d=l.match(h)||[];return c+d.map((m,g)=>m===`
|
|
8
8
|
`?"":(g>0?u:"")+m.trimEnd()).join(`
|
|
9
|
-
`)}};
|
|
10
|
-
(Did you mean one of ${
|
|
11
|
-
(Did you mean ${
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new
|
|
13
|
-
Expecting one of '${
|
|
14
|
-
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=
|
|
9
|
+
`)}};Si.Help=cr});var pr=j(dr=>{var{InvalidArgumentError:Su}=Pt(),ur=class{constructor(e,n){this.flags=e,this.description=n||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=_u(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,n){return this.defaultValue=e,this.defaultValueDescription=n,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let n=e;return typeof e=="string"&&(n={[e]:!0}),this.implied=Object.assign(this.implied||{},n),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,n){return n===this.defaultValue||!Array.isArray(n)?[e]:n.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(n,r)=>{if(!this.argChoices.includes(n))throw new Su(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(n,r):n},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return vu(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},fr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(n=>{n.negate?this.negativeOptions.set(n.attributeName(),n):this.positiveOptions.set(n.attributeName(),n)}),this.negativeOptions.forEach((n,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,n){let r=n.attributeName();if(!this.dualOptions.has(r))return!0;let s=this.negativeOptions.get(r).presetArg,i=s!==void 0?s:!1;return n.negate===(i===e)}};function vu(t){return t.split("-").reduce((e,n)=>e+n[0].toUpperCase()+n.slice(1))}function _u(t){let e,n,r=t.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),n=r.shift(),!e&&/^-[^-]$/.test(n)&&(e=n,n=void 0),{shortFlag:e,longFlag:n}}dr.Option=ur;dr.DualOptions=fr});var _i=j(vi=>{function ku(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let n=[];for(let r=0;r<=t.length;r++)n[r]=[r];for(let r=0;r<=e.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[r-1]?i=0:i=1,n[s][r]=Math.min(n[s-1][r]+1,n[s][r-1]+1,n[s-1][r-1]+i),s>1&&r>1&&t[s-1]===e[r-2]&&t[s-2]===e[r-1]&&(n[s][r]=Math.min(n[s][r],n[s-2][r-2]+1))}return n[t.length][e.length]}function Tu(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let n=t.startsWith("--");n&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let r=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=ku(t,o),c=Math.max(t.length,o.length);(c-a)/c>i&&(a<s?(s=a,r=[o]):a===s&&r.push(o))}),r.sort((o,a)=>o.localeCompare(a)),n&&(r=r.map(o=>`--${o}`)),r.length>1?`
|
|
10
|
+
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
11
|
+
(Did you mean ${r[0]}?)`:""}vi.suggestSimilar=Tu});var Ei=j($i=>{var Cu=require("node:events").EventEmitter,hr=require("node:child_process"),Oe=require("node:path"),mr=require("node:fs"),W=require("node:process"),{Argument:$u,humanReadableArgName:Eu}=an(),{CommanderError:gr}=Pt(),{Help:Au}=lr(),{Option:ki,DualOptions:Ou}=pr(),{suggestSimilar:Ti}=_i(),yr=class t extends Cu{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:n=>W.stdout.write(n),writeErr:n=>W.stderr.write(n),getOutHelpWidth:()=>W.stdout.isTTY?W.stdout.columns:void 0,getErrHelpWidth:()=>W.stderr.isTTY?W.stderr.columns:void 0,outputError:(n,r)=>r(n)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let n=this;n;n=n.parent)e.push(n);return e}command(e,n,r){let s=n,i=r;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Au,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,n){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return n=n||{},n.isDefault&&(this._defaultCommandName=e._name),(n.noHelp||n.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,n){return new $u(e,n)}argument(e,n,r,s){let i=this.createArgument(e,n);return typeof r=="function"?i.default(s).argParser(r):i.default(r),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(n=>{this.argument(n)}),this}addArgument(e){let n=this.registeredArguments.slice(-1)[0];if(n&&n.variadic)throw new Error(`only the last argument can be variadic '${n.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,n){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,s]=e.match(/([^ ]+) *(.*)/),i=n??"display help for command",o=this.createCommand(r);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,n){return typeof e!="object"?(this.helpCommand(e,n),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,n){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(n):this._lifeCycleHooks[e]=[n],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=n=>{if(n.code!=="commander.executeSubCommandAsync")throw n},this}_exit(e,n,r){this._exitCallback&&this._exitCallback(new gr(e,n,r)),W.exit(e)}action(e){let n=r=>{let s=this.registeredArguments.length,i=r.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=n,this}createOption(e,n){return new ki(e,n)}_callParseArg(e,n,r,s){try{return e.parseArg(n,r)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let n=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(n){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
14
|
+
- already used by option '${n.flags}'`)}this.options.push(e)}_registerCommand(e){let n=s=>[s.name()].concat(s.aliases()),r=n(e).find(s=>this._findCommand(s));if(r){let s=n(this._findCommand(r)).join("|"),i=n(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let n=e.name(),r=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(r);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(r,i,a)};return this.on("option:"+n,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+n,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,n,r,s,i){if(typeof n=="object"&&n instanceof ki)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(n,r);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,n,r,s){return this._optionEx({},e,n,r,s)}requiredOption(e,n,r,s){return this._optionEx({mandatory:!0},e,n,r,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,n){return this.setOptionValueWithSource(e,n,void 0)}setOptionValueWithSource(e,n,r){return this._storeOptionsAsProperties?this[e]=n:this._optionValues[e]=n,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let n;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(n=r.getOptionValueSource(e))}),n}_prepareUserArgs(e,n){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(n=n||{},e===void 0&&n.from===void 0){W.versions?.electron&&(n.from="electron");let s=W.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(n.from="eval")}e===void 0&&(e=W.argv),this.rawArgs=e.slice();let r;switch(n.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":W.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${n.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,n){let r=this._prepareUserArgs(e,n);return this._parseCommand([],r),this}async parseAsync(e,n){let r=this._prepareUserArgs(e,n);return await this._parseCommand([],r),this}_executeSubCommand(e,n){n=n.slice();let r=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,f){let p=Oe.resolve(u,f);if(mr.existsSync(p))return p;if(s.includes(Oe.extname(f)))return;let h=s.find(d=>mr.existsSync(`${p}${d}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=mr.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Oe.resolve(Oe.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let f=Oe.basename(this._scriptPath,Oe.extname(this._scriptPath));f!==this._name&&(u=i(a,`${f}-${e._name}`))}o=u||o}r=s.includes(Oe.extname(o));let c;W.platform!=="win32"?r?(n.unshift(o),n=Ci(W.execArgv).concat(n),c=hr.spawn(W.argv[0],n,{stdio:"inherit"})):c=hr.spawn(o,n,{stdio:"inherit"}):(n.unshift(o),n=Ci(W.execArgv).concat(n),c=hr.spawn(W.execPath,n,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{W.on(f,()=>{c.killed===!1&&c.exitCode===null&&c.kill(f)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new gr(u,"commander.executeSubCommandAsync","(close)")):W.exit(u)}),c.on("error",u=>{if(u.code==="ENOENT"){let f=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${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
|
-
- ${f}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)W.exit(1);else{let f=new
|
|
17
|
+
- ${f}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)W.exit(1);else{let f=new gr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=u,l(f)}}),this.runningCommand=c}_dispatchSubcommand(e,n,r){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,n.concat(r));else return s._parseCommand(n,r)}),i}_dispatchHelpCommand(e){e||this.help();let n=this._findCommand(e);return n&&!n._executableHandler&&n.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,n)=>{e.required&&this.args[n]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,s,i)=>{let o=s;if(s!==null&&r.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${r.name()}'.`;o=this._callParseArg(r,s,i,a)}return o};this._checkNumberOfArguments();let n=[];this.registeredArguments.forEach((r,s)=>{let i=r.defaultValue;r.variadic?s<this.args.length?(i=this.args.slice(s),r.parseArg&&(i=i.reduce((o,a)=>e(r,a,o),r.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],r.parseArg&&(i=e(r,i,r.defaultValue))),n[s]=i}),this.processedArgs=n}_chainOrCall(e,n){return e&&e.then&&typeof e.then=="function"?e.then(()=>n()):n()}_chainOrCallHooks(e,n){let r=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[n]!==void 0).forEach(i=>{i._lifeCycleHooks[n].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),n==="postAction"&&s.reverse(),s.forEach(i=>{r=this._chainOrCall(r,()=>i.callback(i.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,n,r){let s=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(i=>{s=this._chainOrCall(s,()=>i(this,n))}),s}_parseCommand(e,n){let r=this.parseOptions(n);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),n=r.unknown,this.args=e.concat(n),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),n);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(n),this._dispatchSubcommand(this._defaultCommandName,e,n);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,n)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,n);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,n);this.listenerCount("command:*")?this.emit("command:*",e,n):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(n=>n._name===e||n._aliases.includes(e))}_findOption(e){return this.options.find(n=>n.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(n=>{n.mandatory&&e.getOptionValue(n.attributeName())===void 0&&e.missingMandatoryOptionValue(n)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let s=r.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let s=e.find(i=>r.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(r,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let n=[],r=[],s=n,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;i.length;){let c=i.shift();if(c==="--"){s===r&&s.push(c),s.push(...i);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let l=this._findOption(c);if(l){if(l.required){let u=i.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(o(c)&&(s=r),(this._enablePositionalOptions||this._passThroughOptions)&&n.length===0&&r.length===0){if(this._findCommand(c)){n.push(c),i.length>0&&r.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){n.push(c),i.length>0&&n.push(...i);break}else if(this._defaultCommandName){r.push(c),i.length>0&&r.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:n,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},n=this.options.length;for(let r=0;r<n;r++){let s=this.options[r].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,n)=>Object.assign(e,n.opts()),{})}error(e,n){this._outputConfiguration.outputError(`${e}
|
|
18
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
19
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0}));let
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let
|
|
22
|
-
Expecting one of '${
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(
|
|
24
|
-
causes have become circular...`;let
|
|
25
|
-
caused by: `+Fi(s,e)):n},Iu=t=>Fi(t,new Set),Li=(t,e,n)=>{if(!Mt(t))return"";let s=n?"":t.message||"";if(e.has(t))return s+": ...";let r=bs(t);if(r){e.add(t);let i=typeof t.cause=="function";return s+(i?"":": ")+Li(r,e,i)}else return s},ju=t=>Li(t,new Set);Di.exports={isErrorLike:Mt,getErrorCause:bs,stackWithCauses:Iu,messageWithCauses:ju}});var Ss=j((Sw,Ui)=>{"use strict";var Pu=Symbol("circular-ref-tag"),cn=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[cn]},set:function(t){this[cn]=t}}});Object.defineProperty(Ni,cn,{writable:!0,value:{}});Ui.exports={pinoErrProto:Ni,pinoErrorSymbols:{seen:Pu,rawSymbol:cn}}});var Hi=j((vw,Bi)=>{"use strict";Bi.exports=_s;var{messageWithCauses:Mu,stackWithCauses:Fu,isErrorLike:qi}=xs(),{pinoErrProto:Lu,pinoErrorSymbols:Du}=Ss(),{seen:vs}=Du,{toString:Nu}=Object.prototype;function _s(t){if(!qi(t))return t;t[vs]=void 0;let e=Object.create(Lu);e.type=Nu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Mu(t),e.stack=Fu(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(n=>_s(n)));for(let n in t)if(e[n]===void 0){let s=t[n];qi(s)?n!=="cause"&&!Object.prototype.hasOwnProperty.call(s,vs)&&(e[n]=_s(s)):e[n]=s}return delete t[vs],e.raw=t,e}});var Vi=j((_w,Wi)=>{"use strict";Wi.exports=un;var{isErrorLike:ks}=xs(),{pinoErrProto:Uu,pinoErrorSymbols:qu}=Ss(),{seen:ln}=qu,{toString:Bu}=Object.prototype;function un(t){if(!ks(t))return t;t[ln]=void 0;let e=Object.create(Uu);e.type=Bu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(n=>un(n))),ks(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,ln)&&(e.cause=un(t.cause));for(let n in t)if(e[n]===void 0){let s=t[n];ks(s)?Object.prototype.hasOwnProperty.call(s,ln)||(e[n]=un(s)):e[n]=s}return delete t[ln],e.raw=t,e}});var Ji=j((kw,Gi)=>{"use strict";Gi.exports={mapHttpRequest:Hu,reqSerializer:Ki};var Ts=Symbol("pino-raw-req-ref"),zi=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[Ts]},set:function(t){this[Ts]=t}}});Object.defineProperty(zi,Ts,{writable:!0,value:{}});function Ki(t){let e=t.info||t.socket,n=Object.create(zi);if(n.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),n.method=t.method,t.originalUrl)n.url=t.originalUrl;else{let s=t.path;n.url=typeof s=="string"?s:t.url?t.url.path||t.url:void 0}return t.query&&(n.query=t.query),t.params&&(n.params=t.params),n.headers=t.headers,n.remoteAddress=e&&e.remoteAddress,n.remotePort=e&&e.remotePort,n.raw=t.raw||t,n}function Hu(t){return{req:Ki(t)}}});var Zi=j((Tw,Qi)=>{"use strict";Qi.exports={mapHttpResponse:Wu,resSerializer:Xi};var Cs=Symbol("pino-raw-res-ref"),Yi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Cs]},set:function(t){this[Cs]=t}}});Object.defineProperty(Yi,Cs,{writable:!0,value:{}});function Xi(t){let e=Object.create(Yi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Wu(t){return{res:Xi(t)}}});var Es=j((Cw,eo)=>{"use strict";var $s=Hi(),Vu=Vi(),fn=Ji(),dn=Zi();eo.exports={err:$s,errWithCause:Vu,mapHttpRequest:fn.mapHttpRequest,mapHttpResponse:dn.mapHttpResponse,req:fn.reqSerializer,res:dn.resSerializer,wrapErrorSerializer:function(e){return e===$s?e:function(s){return e($s(s))}},wrapRequestSerializer:function(e){return e===fn.reqSerializer?e:function(s){return e(fn.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===dn.resSerializer?e:function(s){return e(dn.resSerializer(s))}}}});var As=j(($w,to)=>{"use strict";function zu(t,e){return e}to.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=zu;let n=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(n))return;let s=n.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var ao=j((Ew,oo)=>{"use strict";function Os(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let n=0;n<t.length;n++)e[n]=Os(t[n]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=Os(t[n]));return e}return t}function no(t){let e=[],n="",s=!1,r=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!s&&a==="."?n&&(e.push(n),n=""):a==="["?(n&&(e.push(n),n=""),s=!0):a==="]"&&s?(e.push(n),n="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):n+=a:(r=!0,i=a):n+=a}return n&&e.push(n),e}function so(t,e,n){let s=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=n;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=n)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=n);return!0}function ro(t,e){let n=t;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof n!="object"||n===null||!(i in n)||typeof n[i]!="object"||n[i]===null)return!1;n=n[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let r=0;r<n.length;r++)n[r]=void 0;else if(typeof n=="object"&&n!==null)for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&delete n[r]}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&delete n[s];return!0}var pn=Symbol("PATH_NOT_FOUND");function Ku(t,e){let n=t;for(let s of e){if(n==null||typeof n!="object"||n===null||!(s in n))return pn;n=n[s]}return n}function Gu(t,e){let n=t;for(let s of e){if(n==null||typeof n!="object"||n===null)return;n=n[s]}return n}function Ju(t,e,n,s=!1){for(let r of e){let i=no(r);if(i.includes("*"))io(t,i,n,r,s);else if(s)ro(t,i);else{let o=Ku(t,i);if(o===pn)continue;let a=typeof n=="function"?n(o,i):n;so(t,i,a)}}}function io(t,e,n,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let c of o){if(a==null||typeof a!="object"||a===null)return;a=a[c]}if(Array.isArray(a))if(r)for(let c=0;c<a.length;c++)a[c]=void 0;else for(let c=0;c<a.length;c++){let l=[...o,c.toString()],u=typeof n=="function"?n(a[c],l):n;a[c]=u}else if(typeof a=="object"&&a!==null)if(r){let c=[];for(let l in a)Object.prototype.hasOwnProperty.call(a,l)&&c.push(l);for(let l of c)delete a[l]}else for(let c in a){let l=[...o,c],u=typeof n=="function"?n(a[c],l):n;a[c]=u}}else Yu(t,e,n,i,s,r)}function Yu(t,e,n,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),c=[];function l(u,f){if(f===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)c[f]=p.toString(),l(u[p],f+1);else if(typeof u=="object"&&u!==null)for(let p in u)c[f]=p,l(u[p],f+1)}else if(f<o.length){let p=o[f];u&&typeof u=="object"&&u!==null&&p in u&&(c[f]=p,l(u[p],f+1))}else if(a.includes("*"))io(u,a,typeof n=="function"?(h,d)=>{let m=[...c.slice(0,f),...d];return n(h,m)}:n,r,i);else if(i)ro(u,a);else{let p=typeof n=="function"?n(Gu(u,a),[...c.slice(0,f),...a]):n;so(u,a,p)}}if(o.length===0)l(t,0);else{let u=t;for(let f=0;f<o.length;f++){let p=o[f];if(u==null||typeof u!="object"||u===null)return;u=u[p],c[f]=p}u!=null&&l(u,o.length)}}function Xu(t){if(t.length===0)return null;let e=new Map;for(let n of t){let s=no(n),r=e;for(let i=0;i<s.length;i++){let o=s[i];r.has(o)||r.set(o,new Map),r=r.get(o)}}return e}function Qu(t,e){if(!e)return t;function n(s,r,i=0){if(!r||r.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let c=0;c<s.length;c++){let l=c.toString();r.has(l)||r.has("*")?a[c]=n(s[c],r.get(l)||r.get("*")):a[c]=s[c]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=n(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return n(t,e)}function Zu(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,n=!1,s="";for(let r=0;r<t.length;r++){let i=t[r];if((i==='"'||i==="'")&&e>0)n?i===s&&(n=!1,s=""):(n=!0,s=i);else if(i==="["&&!n)e++;else if(i==="]"&&!n&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function ef(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Zu(e)}function tf(t={}){let{paths:e=[],censor:n="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=t;ef(e);let o=Xu(e);return function(c){if(r&&(c===null||typeof c!="object")&&(c==null||typeof c!="object"))return s?s(c):c;let l=Qu(c,o),u=c,f=n;return typeof n=="function"&&(f=n),Ju(l,e,f,i),s===!1?(l.restore=function(){return Os(u)},l):typeof s=="function"?s(l):JSON.stringify(l)}}oo.exports=tf});var dt=j((Aw,co)=>{"use strict";var nf=Symbol("pino.setLevel"),sf=Symbol("pino.getLevel"),rf=Symbol("pino.levelVal"),of=Symbol("pino.levelComp"),af=Symbol("pino.useLevelLabels"),cf=Symbol("pino.useOnlyCustomLevels"),lf=Symbol("pino.mixin"),uf=Symbol("pino.lsCache"),ff=Symbol("pino.chindings"),df=Symbol("pino.asJson"),pf=Symbol("pino.write"),hf=Symbol("pino.redactFmt"),mf=Symbol("pino.time"),gf=Symbol("pino.timeSliceIndex"),yf=Symbol("pino.stream"),wf=Symbol("pino.stringify"),bf=Symbol("pino.stringifySafe"),xf=Symbol("pino.stringifiers"),Sf=Symbol("pino.end"),vf=Symbol("pino.formatOpts"),_f=Symbol("pino.messageKey"),kf=Symbol("pino.errorKey"),Tf=Symbol("pino.nestedKey"),Cf=Symbol("pino.nestedKeyStr"),$f=Symbol("pino.mixinMergeStrategy"),Ef=Symbol("pino.msgPrefix"),Af=Symbol("pino.wildcardFirst"),Of=Symbol.for("pino.serializers"),Rf=Symbol.for("pino.formatters"),If=Symbol.for("pino.hooks"),jf=Symbol.for("pino.metadata");co.exports={setLevelSym:nf,getLevelSym:sf,levelValSym:rf,levelCompSym:of,useLevelLabelsSym:af,mixinSym:lf,lsCacheSym:uf,chindingsSym:ff,asJsonSym:df,writeSym:pf,serializersSym:Of,redactFmtSym:hf,timeSym:mf,timeSliceIndexSym:gf,streamSym:yf,stringifySym:wf,stringifySafeSym:bf,stringifiersSym:xf,endSym:Sf,formatOptsSym:vf,messageKeySym:_f,errorKeySym:kf,nestedKeySym:Tf,wildcardFirstSym:Af,needsMetadataGsym:jf,useOnlyCustomLevelsSym:cf,formattersSym:Rf,hooksSym:If,nestedKeyStrSym:Cf,mixinMergeStrategySym:$f,msgPrefixSym:Ef}});var Is=j((Ow,po)=>{"use strict";var lo=ao(),{redactFmtSym:Pf,wildcardFirstSym:hn}=dt(),Rs=/[^.[\]]+|\[([^[\]]*?)\]/g,uo="[Redacted]",fo=!1;function Mf(t,e){let{paths:n,censor:s,remove:r}=Ff(t),i=n.reduce((c,l)=>{Rs.lastIndex=0;let u=Rs.exec(l),f=Rs.exec(l),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=hn),f===null)return c[p]=null,c;if(c[p]===null)return c;let{index:h}=f,d=`${l.substr(h,l.length-1)}`;return c[p]=c[p]||[],p!==hn&&c[p].length===0&&c[p].push(...c[hn]||[]),p===hn&&Object.keys(c).forEach(function(m){c[m]&&c[m].push(d)}),c[p].push(d),c},{}),o={[Pf]:lo({paths:n,censor:s,serialize:e,strict:fo,remove:r})},a=(...c)=>e(typeof s=="function"?s(...c):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((c,l)=>{if(i[l]===null)c[l]=u=>a(u,[l]);else{let u=typeof s=="function"?(f,p)=>s(f,[l,...p]):s;c[l]=lo({paths:i[l],censor:u,serialize:e,strict:fo,remove:r})}return c},o)}function Ff(t){if(Array.isArray(t))return t={paths:t,censor:uo},t;let{paths:e,censor:n=uo,remove:s}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(n=void 0),{paths:e,censor:n,remove:s}}po.exports=Mf});var go=j((Rw,mo)=>{"use strict";var Lf=()=>"",Df=()=>`,"time":${Date.now()}`,Nf=()=>`,"time":${Math.round(Date.now()/1e3)}`,Uf=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,qf=1000000n,ho=1000000000n,Bf=BigInt(Date.now())*qf,Hf=process.hrtime.bigint(),Wf=()=>{let t=process.hrtime.bigint()-Hf,e=Bf+t,n=e/ho,s=e%ho,r=Number(n*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${c}T${l}:${u}:${f}.${s.toString().padStart(9,"0")}Z"`};mo.exports={nullTime:Lf,epochTime:Df,unixTime:Nf,isoTime:Uf,isoTimeNano:Wf}});var wo=j((Iw,yo)=>{"use strict";function Vf(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}yo.exports=zf;function zf(t,e,n){var s=n&&n.stringify||Vf,r=1;if(typeof t=="object"&&t!==null){var i=e.length+r;if(i===1)return t;var o=new Array(i);o[0]=s(t);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-r,f=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(u>=c||e[u]==null)break;f<h&&(l+=t.slice(f,h)),l+=Number(e[u]),f=h+2,h++;break;case 105:if(u>=c||e[u]==null)break;f<h&&(l+=t.slice(f,h)),l+=Math.floor(Number(e[u])),f=h+2,h++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;f<h&&(l+=t.slice(f,h));var d=typeof e[u];if(d==="string"){l+="'"+e[u]+"'",f=h+2,h++;break}if(d==="function"){l+=e[u].name||"<anonymous>",f=h+2,h++;break}l+=s(e[u]),f=h+2,h++;break;case 115:if(u>=c)break;f<h&&(l+=t.slice(f,h)),l+=String(e[u]),f=h+2,h++;break;case 37:f<h&&(l+=t.slice(f,h)),l+="%",f=h+2,h++,u--;break}++u}++h}return f===-1?t:(f<p&&(l+=t.slice(f)),l)}});var Ps=j((jw,js)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(n){if((n>0&&n<1/0)===!1)throw typeof n!="number"&&typeof n!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(n))},t=new Int32Array(new SharedArrayBuffer(4));js.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let s=Date.now()+Number(e);for(;s>Date.now(););};js.exports=t}});var Co=j((Pw,To)=>{"use strict";var q=require("fs"),Kf=require("events"),Gf=require("util").inherits,bo=require("path"),Fs=Ps(),Jf=require("assert"),mn=100,gn=Buffer.allocUnsafe(0),Yf=16*1024,xo="buffer",So="utf8",[Xf,Qf]=(process.versions.node||"0.0").split(".").map(Number),Zf=Xf>=22&&Qf>=7;function vo(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function n(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",r=e.mode;if(e.sync)try{e.mkdir&&q.mkdirSync(bo.dirname(t),{recursive:!0});let i=q.openSync(t,s,r);n(null,i)}catch(i){throw n(i),i}else e.mkdir?q.mkdir(bo.dirname(t),{recursive:!0},i=>{if(i)return n(i);q.open(t,s,r,n)}):q.open(t,s,r,n)}function be(t){if(!(this instanceof be))return new be(t);let{fd:e,dest:n,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:c=!0,mkdir:l,retryEAGAIN:u,fsync:f,contentMode:p,mode:h}=t||{};e=e||n,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=r||0,this.maxWrite=i||Yf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=c||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=l||!1;let d,m;if(p===xo)this._writingBuf=gn,this.write=nd,this.flush=rd,this.flushSync=od,this._actualWrite=cd,d=()=>q.writeSync(this.fd,this._writingBuf),m=()=>q.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===So)this._writingBuf="",this.write=td,this.flush=sd,this.flushSync=id,this._actualWrite=ad,d=()=>Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?q.write(this.fd,this._writingBuf,this.release):q.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${So}" and "${xo}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")vo(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,y)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Fs(mn),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(m,mn);else this._writing=!1,this.emit("error",g);return}this.emit("write",y);let b=Ms(this._writingBuf,this._len,y);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let v=d(),_=Ms(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&q.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,yn(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(ed,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 Ms(t,e,n){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-n,0),t=t.subarray(n),{writingBuf:t,len:e}}function ed(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Gf(be,Kf);function _o(t,e){return t.length===0?gn:t.length===1?t[0]:Buffer.concat(t,e)}function td(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),n=this._len+e,s=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(t):s[s.length-1]+=t,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function nd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,n=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||s[s.length-1]+t.length>this.maxWrite?(n.push([t]),s.push(t.length)):(n[n.length-1].push(t),s[s.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function ko(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{q.fsync(this.fd,s=>{this._flushPending=!1,t(s)})}catch(s){t(s)}this.off("error",n)},n=s=>{this._flushPending=!1,t(s),this.off("drain",e)};this.once("drain",e),this.once("error",n)}function sd(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&&ko.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function rd(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&&ko.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}be.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&q.close(e,n=>{if(n)return this.emit("error",n)})}),vo(this.file,this)};be.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():yn(this)))};function id(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?q.writeSync(this.fd,t):q.writeSync(this.fd,t,"utf8"),n=Ms(t,this._len,e);t=n.writingBuf,this._len=n.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Fs(mn)}}try{q.fsyncSync(this.fd)}catch{}}function od(){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=gn);let t=gn;for(;this._bufs.length||t.length;){t.length<=0&&(t=_o(this._bufs[0],this._lens[0]));try{let e=q.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Fs(mn)}}}be.prototype.destroy=function(){this.destroyed||yn(this)};function ad(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else q.write(this.fd,this._writingBuf,t)}function cd(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:_o(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=q.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Zf&&(this._writingBuf=Buffer.from(this._writingBuf)),q.write(this.fd,this._writingBuf,t)}function yn(t){if(t.fd===-1){t.once("ready",yn.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Jf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{q.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?q.close(t.fd,n):n()}function n(s){if(s){t.emit("error",s);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}be.SonicBoom=be;be.default=be;To.exports=be});var Ls=j((Mw,Ro)=>{"use strict";var xe={exit:[],beforeExit:[]},$o={exit:fd,beforeExit:dd},pt;function ld(){pt===void 0&&(pt=new FinalizationRegistry(pd))}function ud(t){xe[t].length>0||process.on(t,$o[t])}function Eo(t){xe[t].length>0||(process.removeListener(t,$o[t]),xe.exit.length===0&&xe.beforeExit.length===0&&(pt=void 0))}function fd(){Ao("exit")}function dd(){Ao("beforeExit")}function Ao(t){for(let e of xe[t]){let n=e.deref(),s=e.fn;n!==void 0&&s(n,t)}xe[t]=[]}function pd(t){for(let e of["exit","beforeExit"]){let n=xe[e].indexOf(t);xe[e].splice(n,n+1),Eo(e)}}function Oo(t,e,n){if(e===void 0)throw new Error("the object can't be undefined");ud(t);let s=new WeakRef(e);s.fn=n,ld(),pt.register(e,s),xe[t].push(s)}function hd(t,e){Oo("exit",t,e)}function md(t,e){Oo("beforeExit",t,e)}function gd(t){if(pt!==void 0){pt.unregister(t);for(let e of["exit","beforeExit"])xe[e]=xe[e].filter(n=>{let s=n.deref();return s&&s!==t}),Eo(e)}}Ro.exports={register:hd,registerBeforeExit:md,unregister:gd}});var Io=j((Fw,yd)=>{yd.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 Po=j((Lw,jo)=>{"use strict";function wd(t,e,n,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(t,e);if(a===n){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,a,c);l.async?l.value.then(o):setImmediate(o)};o()}function bd(t,e,n,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(t,e)!==n){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,n,c);l.async?l.value.then(u=>{if(u==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}jo.exports={wait:wd,waitDiff:bd}});var Fo=j((Dw,Mo)=>{"use strict";Mo.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Go=j((Nw,Ko)=>{"use strict";var{version:xd}=Io(),{EventEmitter:Sd}=require("events"),{Worker:vd}=require("worker_threads"),{join:_d}=require("path"),{pathToFileURL:kd}=require("url"),{wait:Td}=Po(),{WRITE_INDEX:Re,READ_INDEX:Xe,SEQ_INDEX:Ds}=Fo(),Cd=require("buffer"),$d=require("assert"),S=Symbol("kImpl"),Ed=Cd.constants.MAX_STRING_LENGTH;function Lo(){}function Bs(t,e){Atomics.add(t[S].state,Ds,1),e(),Atomics.add(t[S].state,Ds,1),Atomics.notify(t[S].state,Ds)}function Do(t){Bs(t,()=>{Atomics.store(t[S].state,Xe,0),Atomics.store(t[S].state,Re,0)})}var Ft=class{constructor(e){this._value=e}deref(){return this._value}},wn=class{register(){}unregister(){}},Ad=process.env.NODE_V8_COVERAGE?wn:global.FinalizationRegistry||wn,Od=process.env.NODE_V8_COVERAGE?Ft:global.WeakRef||Ft,No=new Ad(t=>{t.exited||t.terminate()});function Rd(t,e){let{filename:n,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||_d(__dirname,"lib","worker.js"),o=new vd(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:n.indexOf("file://")===0?n:kd(n).href,dataBuf:t[S].dataBuf,stateBuf:t[S].stateBuf,workerData:{$context:{threadStreamVersion:xd},...s}}});return o.stream=new Ft(t),o.on("message",Id),o.on("exit",Bo),No.register(t,o),o}function Uo(t){$d(!t[S].sync),t[S].needDrain&&(t[S].needDrain=!1,t.emit("drain"))}function qo(t){for(;;){let e=Atomics.load(t[S].state,Re),n=t[S].data.length-e;if(n>0){if(t[S].bufLen===0){t[S].flushing=!1,t[S].ending?Hs(t):t[S].needDrain&&process.nextTick(Uo,t);return}Vo(t,n,Lo);continue}if(n===0){if(e===0&&t[S].bufLen===0)return;bn(t,()=>{t.destroyed||(Do(t),qo(t))});return}fe(t,new Error("overwritten"));return}}function Id(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 Od(e),bn(e,()=>{e[S].ready=!0,e.emit("ready")});break;case"ERROR":fe(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"){fe(e,new Error("this should not happen: "+t.code));break}let n=e[S].flushCallbacks.get(t.id);n&&(e[S].flushCallbacks.delete(t.id),process.nextTick(n));break}case"WARNING":process.emitWarning(t.err);break;default:fe(e,new Error("this should not happen: "+t.code))}}function Bo(t){let e=this.stream.deref();e!==void 0&&(No.unregister(e),e.worker.exited=!0,e.worker.off("exit",Bo),fe(e,t!==0?new Error("the worker thread exited"):null))}var Us=class extends Sd{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=Rd(this,e),this.on("message",(n,s)=>{this.worker.postMessage(n,s)})}write(e){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[S].destroyed)return qs(this,new Error("the worker has exited")),!1;if(this[S].ending)return qs(this,new Error("the worker is ending")),!1;if(this[S].flushing&&this[S].bufLen+n.length>=Ed)try{Ns(this),this[S].flushing=!0}catch(s){return fe(this,s),!1}if(this[S].buf.push(n),this[S].bufLen+=n.length,this[S].sync)try{return Ns(this),!0}catch(s){return fe(this,s),!1}return this[S].flushing||(this[S].flushing=!0,setImmediate(qo,this)),this[S].needDrain=this[S].data.length-this[S].bufLen-Atomics.load(this[S].state,Re)<=0,!this[S].needDrain}end(){this[S].destroyed||(this[S].ending=!0,Hs(this))}flush(e){e=typeof e=="function"?e:Lo,Ho(this,n=>{if(n){process.nextTick(e,n);return}Wo(this,e)})}flushSync(){this[S].destroyed||(Ns(this),zo(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 Ho(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(Ho,t,e);return}bn(t,e)}function bn(t,e){let n=Atomics.load(t[S].state,Re);Td(t[S].state,Xe,n,1/0,(s,r)=>{if(s){fe(t,s),e(s);return}if(r!=="ok"){bn(t,e);return}e()})}function Wo(t,e){if(t[S].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[S].ready){let s=()=>{i(),Wo(t,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",s),t.off("close",r)};t.once("ready",s),t.once("close",r);return}let n=++t[S].nextFlushId;t[S].flushCallbacks.set(n,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:n})}catch(s){t[S].flushCallbacks.delete(n),fe(t,s),process.nextTick(e,s)}}function jd(t,e){let n=t[S].flushCallbacks;if(n.size===0)return;let s=e||new Error("the worker has exited");for(let r of n.values())process.nextTick(r,s);n.clear()}function qs(t,e){setImmediate(()=>{t.emit("error",e)})}function fe(t,e){t[S].destroyed||(t[S].destroyed=!0,jd(t,e),e&&(t[S].errored=e,qs(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 Vo(t,e,n){let r=Atomics.load(t[S].state,Re),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,r),r+=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,r,0,i),t[S].buf[o]=a.subarray(i),t[S].bufLen-=i,r+=i,i=0}return Bs(t,()=>{Atomics.store(t[S].state,Re,r)}),n(),!0}function Hs(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,Xe);Bs(t,()=>{Atomics.store(t[S].state,Re,-1)});let n=0;for(;e!==-1;){if(Atomics.wait(t[S].state,Xe,e,1e3),e=Atomics.load(t[S].state,Xe),e===-2){fe(t,new Error("end() failed"));return}if(++n===10){fe(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[S].finished=!0,t.emit("finish")})}catch(e){fe(t,e)}}}function Ns(t){let e=()=>{t[S].ending?Hs(t):t[S].needDrain&&process.nextTick(Uo,t)};for(t[S].flushing=!1;t[S].bufLen!==0;){let n=Atomics.load(t[S].state,Re),s=t[S].data.length-n;if(s===0){zo(t),Do(t);continue}else if(s<0)throw new Error("overwritten");Vo(t,s,e)}}function zo(t){if(t[S].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[S].state,Re),n=0;for(;;){let s=Atomics.load(t[S].state,Xe);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(t[S].state,Xe,s,1e3);else break;if(++n===10)throw new Error("_flushSync took too long (10s)")}}Ko.exports=Us});var zs=j((Uw,Xo)=>{"use strict";var{createRequire:Pd}=require("module"),{existsSync:Md}=require("node:fs"),Fd=As(),{join:Ws,isAbsolute:Yo,sep:Ld}=require("node:path"),{fileURLToPath:Dd}=require("node:url"),Nd=Ps(),Vs=Ls(),Ud=Go();function qd(t){Vs.register(t,zd),Vs.registerBeforeExit(t,Kd),t.on("close",function(){Vs.unregister(t)})}function Bd(){let t=process.execArgv;for(let e=0;e<t.length;e++){let n=t[e];if(n==="--import"||n==="--require"||n==="-r"||n.startsWith("--import=")||n.startsWith("--require=")||n.startsWith("-r="))return!0}return!1}function Hd(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let n=[],s=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--require"||i==="-r"||i==="--import"){let o=e[r+1];if(o&&Jo(o)){s=!0,r++;continue}n.push(i),o&&(n.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Jo(o)){s=!0;continue}}n.push(i)}return s?n.join(" "):t}function Jo(t){let e=Wd(t);if(!e)return!1;let n=e;if(n.startsWith("file://"))try{n=Dd(n)}catch{return!1}return Yo(n)&&!Md(n)}function Wd(t){let e=t[0],n=t[t.length-1];return e==='"'&&n==='"'||e==="'"&&n==="'"?t.slice(1,-1):t}function Vd(t,e,n,s,r){if(!n.execArgv&&Bd()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let c=Hd(process.env.NODE_OPTIONS);c!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:c}})}n={...n,name:r};let i=new Ud({filename:t,workerData:e,workerOpts:n,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),n.autoEnd!==!1&&qd(i)}function a(){i.closed||(i.flushSync(),Nd(100),i.end())}return i}function zd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Kd(t){t.flushSync()}function Gd(t){let{pipeline:e,targets:n,levels:s,dedupe:r,worker:i={},caller:o=Fd(),sync:a=!1}=t,c={...t.options},l=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),f=t.target;if(f&&n)throw new Error("only one of target or targets can be specified");n?(f=u["pino-worker"]||Ws(__dirname,"worker.js"),c.targets=n.filter(d=>d.target).map(d=>({...d,target:h(d.target)})),c.pipelines=n.filter(d=>d.pipeline).map(d=>d.pipeline.map(m=>({...m,level:d.level,target:h(m.target)})))):e&&(f=u["pino-worker"]||Ws(__dirname,"worker.js"),c.pipelines=[e.map(d=>({...d,target:h(d.target)}))]),s&&(c.levels=s),r&&(c.dedupe=r),c.pinoWillSendConfig=!0;let p=n||e?"pino.transport":f;return Vd(h(f),c,i,a,p);function h(d){if(d=u[d]||d,Yo(d)||d.indexOf("file://")===0)return d;if(d==="pino/file")return Ws(__dirname,"..","file.js");let m;for(let g of l)try{let y=g==="node:repl"?process.cwd()+Ld:g;m=Pd(y).resolve(d);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${d}"`);return m}}Xo.exports=Gd});var vn=j((qw,ua)=>{"use strict";var Jd=require("node:diagnostics_channel"),Qo=wo(),{mapHttpRequest:Yd,mapHttpResponse:Xd}=Es(),Gs=Co(),Zo=Ls(),{lsCacheSym:Qd,chindingsSym:ra,writeSym:ea,serializersSym:ia,formatOptsSym:ta,endSym:Zd,stringifiersSym:oa,stringifySym:aa,stringifySafeSym:Js,wildcardFirstSym:ca,nestedKeySym:ep,formattersSym:la,messageKeySym:tp,errorKeySym:np,nestedKeyStrSym:sp,msgPrefixSym:xn}=dt(),{isMainThread:rp}=require("worker_threads"),ip=zs(),[op]=process.versions.node.split(".").map(t=>Number(t)),na=Jd.tracingChannel("pino_asJson"),Ks=op>=25?t=>JSON.stringify(t):cp;function ht(){}function ap(t,e){if(!e)return n;return function(...r){e.call(this,r,n,t)};function n(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=Yd(s):typeof s.setHeader=="function"&&(s=Xd(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[xn]=="string"&&i!==void 0&&i!==null&&(i=this[xn]+i),this[ea](s,Qo(i,o,this[ta]),t)}else{let i=s===void 0?r.shift():s;typeof this[xn]=="string"&&i!==void 0&&i!==null&&(i=this[xn]+i),this[ea](null,Qo(i,r,this[ta]),t)}}}function cp(t){let e="",n=0,s=!1,r=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&r>=32;o++)r=t.charCodeAt(o),(r===34||r===92)&&(e+=t.slice(n,o)+"\\",n=o,s=!0);return s?e+=t.slice(n):e=t,r<32?JSON.stringify(t):'"'+e+'"'}function lp(t,e,n,s){if(na.hasSubscribers===!1)return sa.call(this,t,e,n,s);let r={instance:this,arguments};return na.traceSync(sa,r,this,t,e,n,s)}function sa(t,e,n,s){let r=this[aa],i=this[Js],o=this[oa],a=this[Zd],c=this[ra],l=this[ia],u=this[la],f=this[tp],p=this[np],h=this[Qd][n]+s;h=h+c;let d;u.log&&(t=u.log(t));let m=o[ca],g="";for(let b in t)if(d=t[b],Object.prototype.hasOwnProperty.call(t,b)&&d!==void 0){l[b]?d=l[b](d):b===p&&l.err&&(d=l.err(d));let w=o[b]||m;switch(typeof d){case"undefined":case"function":continue;case"number":Number.isFinite(d)===!1&&(d=null);case"boolean":w&&(d=w(d));break;case"string":d=(w||Ks)(d);break;default:d=(w||r)(d,i)}if(d===void 0)continue;let v=Ks(b);g+=","+v+":"+d}let y="";if(e!==void 0){d=l[f]?l[f](e):e;let b=o[f]||m;switch(typeof d){case"function":break;case"number":Number.isFinite(d)===!1&&(d=null);case"boolean":b&&(d=b(d)),y=',"'+f+'":'+d;break;case"string":d=(b||Ks)(d),y=',"'+f+'":'+d;break;default:d=(b||r)(d,i),y=',"'+f+'":'+d}}return this[ep]&&g?h+this[sp]+g.slice(1)+"}"+y+a:h+g+y+a}function up(t,e){let n,s=t[ra],r=t[aa],i=t[Js],o=t[oa],a=o[ca],c=t[ia],l=t[la].bindings;e=l(e);for(let u in e)if(n=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&n!==void 0)===!0){if(n=c[u]?c[u](n):n,n=(o[u]||a||r)(n,i),n===void 0)continue;s+=',"'+u+'":'+n}return s}function fp(t){return t.write!==t.constructor.prototype.write}function Sn(t){let e=new Gs(t);return e.on("error",n),!t.sync&&rp&&(Zo.register(e,dp),e.on("close",function(){Zo.unregister(e)})),e;function n(s){if(s.code==="EPIPE"){e.write=ht,e.end=ht,e.flushSync=ht,e.destroy=ht;return}e.removeListener("error",n),e.emit("error",s)}}function dp(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function pp(t){return function(n,s,r={},i){if(typeof r=="string")i=Sn({dest:r}),r={};else if(typeof i=="string"){if(r&&r.transport)throw Error("only one of option.transport or stream can be specified");i=Sn({dest:i})}else if(r instanceof Gs||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof Gs||r.transport.writable||r.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let c;r.customLevels&&(c=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=ip({caller:s,...r.transport,levels:c})}if(r=Object.assign({},t,r),r.serializers=Object.assign({},t.serializers,r.serializers),r.formatters=Object.assign({},t.formatters,r.formatters),r.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}=r;return o===!1&&(r.level="silent"),a||(r.onChild=ht),i||(fp(process.stdout)?i=process.stdout:i=Sn({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function hp(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Js])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function mp(t,e,n){return{level:t,bindings:e,log:n}}function gp(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}ua.exports={noop:ht,buildSafeSonicBoom:Sn,asChindings:up,asJson:lp,genLog:ap,createArgsNormalizer:pp,stringify:hp,buildFormatters:mp,normalizeDestFileDescriptor:gp}});var _n=j((Bw,fa)=>{var yp={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},wp={ASC:"ASC",DESC:"DESC"};fa.exports={DEFAULT_LEVELS:yp,SORTING_ORDER:wp}});var Qs=j((Hw,ma)=>{"use strict";var{lsCacheSym:bp,levelValSym:Ys,useOnlyCustomLevelsSym:xp,streamSym:Sp,formattersSym:vp,hooksSym:_p,levelCompSym:da}=dt(),{noop:kp,genLog:Qe}=vn(),{DEFAULT_LEVELS:Te,SORTING_ORDER:pa}=_n(),ha={fatal:t=>{let e=Qe(Te.fatal,t);return function(...n){let s=this[Sp];if(e.call(this,...n),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:t=>Qe(Te.error,t),warn:t=>Qe(Te.warn,t),info:t=>Qe(Te.info,t),debug:t=>Qe(Te.debug,t),trace:t=>Qe(Te.trace,t)},Xs=Object.keys(Te).reduce((t,e)=>(t[Te[e]]=e,t),{}),Tp=Object.keys(Xs).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Cp(t){let e=t[vp].level,{labels:n}=t.levels,s={};for(let r in n){let i=e(n[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return t[bp]=s,t}function $p(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 Ep(t){let{labels:e,values:n}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(n[t]===void 0)throw Error("unknown level "+t);let s=this[Ys],r=this[Ys]=n[t],i=this[xp],o=this[da],a=this[_p].logMethod;for(let c in n){if(o(n[c],r)===!1){this[c]=kp;continue}this[c]=$p(c,i)?ha[c](a):Qe(n[c],a)}this.emit("level-change",t,r,e[s],s,this)}function Ap(t){let{levels:e,levelVal:n}=this;return e&&e.labels?e.labels[n]:""}function Op(t){let{values:e}=this.levels,n=e[t];return n!==void 0&&this[da](n,this[Ys])}function Rp(t,e,n){return t===pa.DESC?e<=n:e>=n}function Ip(t){return typeof t=="string"?Rp.bind(null,t):t}function jp(t=null,e=!1){let n=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Xs,n),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:Te,t);return{labels:s,values:r}}function Pp(t,e,n){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),n?[]:Object.keys(Xs).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:Te,e);if(!(t in s))throw Error(`default level:${t} must be included in custom levels`)}function Mp(t,e){let{labels:n,values:s}=t;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in n)throw Error("pre-existing level values cannot be used for new levels")}}function Fp(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(pa).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ma.exports={initialLsCache:Tp,genLsCache:Cp,levelMethods:ha,getLevel:Ap,setLevel:Ep,isLevelEnabled:Op,mappings:jp,assertNoLevelCollisions:Mp,assertDefaultLevelFound:Pp,genLevelComparison:Ip,assertLevelComparison:Fp}});var Zs=j((Ww,ga)=>{"use strict";ga.exports={version:"10.3.1"}});var ka=j((zw,_a)=>{"use strict";var{EventEmitter:Lp}=require("node:events"),{lsCacheSym:Dp,levelValSym:Np,setLevelSym:tr,getLevelSym:ya,chindingsSym:Tn,mixinSym:Up,asJsonSym:ba,writeSym:qp,mixinMergeStrategySym:Bp,timeSym:Hp,timeSliceIndexSym:Wp,streamSym:xa,serializersSym:Ze,formattersSym:Lt,errorKeySym:Vp,messageKeySym:zp,useOnlyCustomLevelsSym:Kp,needsMetadataGsym:Gp,redactFmtSym:Jp,stringifySym:Yp,formatOptsSym:Xp,stringifiersSym:Qp,msgPrefixSym:nr,hooksSym:Zp}=dt(),{getLevel:eh,setLevel:th,isLevelEnabled:nh,mappings:sh,initialLsCache:rh,genLsCache:ih,assertNoLevelCollisions:oh}=Qs(),{asChindings:sr,asJson:ah,buildFormatters:er,stringify:wa,noop:Sa}=vn(),{version:ch}=Zs(),lh=Is(),uh=class{},va={constructor:uh,child:fh,bindings:dh,setBindings:ph,flush:gh,isLevelEnabled:nh,version:ch,get level(){return this[ya]()},set level(t){this[tr](t)},get levelVal(){return this[Np]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[nr]},get[Symbol.toStringTag](){return"Pino"},[Dp]:rh,[qp]:mh,[ba]:ah,[ya]:eh,[tr]:th};Object.setPrototypeOf(va,Lp.prototype);_a.exports=function(){return Object.create(va)};var kn=t=>t;function fh(t,e){if(!t)throw Error("missing bindings for child Pino");let n=this[Ze],s=this[Lt],r=Object.create(this);if(e==null)return r[Lt].bindings!==kn&&(r[Lt]=er(s.level,kn,s.log)),r[Tn]=sr(r,t),this.onChild!==Sa&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[Ze]=Object.create(null);for(let l in n)r[Ze][l]=n[l];let a=Object.getOwnPropertySymbols(n);for(var i=0;i<a.length;i++){let l=a[i];r[Ze][l]=n[l]}for(let l in e.serializers)r[Ze][l]=e.serializers[l];let c=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<c.length;o++){let l=c[o];r[Ze][l]=e.serializers[l]}}else r[Ze]=n;if(e.hasOwnProperty("formatters")){let{level:a,bindings:c,log:l}=e.formatters;r[Lt]=er(a||s.level,c||kn,l||s.log)}else r[Lt]=er(s.level,kn,s.log);if(e.hasOwnProperty("customLevels")===!0&&(oh(this.levels,e.customLevels),r.levels=sh(e.customLevels,r[Kp]),ih(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=lh(r.redact,wa),c={stringify:a[Jp]};r[Yp]=wa,r[Qp]=a,r[Xp]=c}if(typeof e.msgPrefix=="string"&&(r[nr]=(this[nr]||"")+e.msgPrefix),r[Tn]=sr(r,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[tr](a)}return this.onChild(r),r}function dh(){let e=`{${this[Tn].substr(1)}}`,n=JSON.parse(e);return delete n.pid,delete n.hostname,n}function ph(t){let e=sr(this,t);this[Tn]=e}function hh(t,e){return Object.assign(e,t)}function mh(t,e,n){let s=this[Hp](),r=this[Up],i=this[Vp],o=this[zp],a=this[Bp]||hh,c,l=this[Zp].streamWrite;t==null?c={}:t instanceof Error?(c={[i]:t},e===void 0&&(e=t.message)):(c=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),r&&(c=a(c,r(c,n,this)));let u=this[ba](c,e,n,s),f=this[xa];f[Gp]===!0&&(f.lastLevel=n,f.lastObj=c,f.lastMsg=e,f.lastTime=s.slice(this[Wp]),f.lastLogger=this),f.write(l?l(u):u)}function gh(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[xa];typeof e.flush=="function"?e.flush(t||Sa):t&&t()}});var Ea=j((ar,$a)=>{"use strict";var{hasOwnProperty:Dt}=Object.prototype,tt=or();tt.configure=or;tt.stringify=tt;tt.default=tt;ar.stringify=tt;ar.configure=or;$a.exports=tt;var yh=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qe(t){return t.length<5e3&&!yh.test(t)?`"${t}"`:JSON.stringify(t)}function rr(t,e){if(t.length>200||e)return t.sort(e);for(let n=1;n<t.length;n++){let s=t[n],r=n;for(;r!==0&&t[r-1]>s;)t[r]=t[r-1],r--;t[r]=s}return t}var wh=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ir(t){return wh.call(t)!==void 0&&t.length!==0}function Ta(t,e,n){t.length<n&&(n=t.length);let s=e===","?"":" ",r=`"0":${s}${t[0]}`;for(let i=1;i<n;i++)r+=`${e}"${i}":${s}${t[i]}`;return r}function bh(t){if(Dt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function xh(t){let e;if(Dt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function Sh(t,e){let n;if(Dt.call(t,e)&&(n=t[e],typeof n!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return n===void 0?!0:n}function Ca(t,e){let n;if(Dt.call(t,e)){if(n=t[e],typeof n!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(n))throw new TypeError(`The "${e}" argument must be an integer`);if(n<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return n===void 0?1/0:n}function et(t){return t===1?"1 item":`${t} items`}function vh(t){let e=new Set;for(let n of t)(typeof n=="string"||typeof n=="number")&&e.add(String(n));return e}function _h(t){if(Dt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return n=>{let s=`Object can not safely be stringified. Received type ${typeof n}`;throw typeof n!="function"&&(s+=` (${n.toString()})`),new Error(s)}}}function or(t){t={...t};let e=_h(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let n=bh(t),s=Sh(t,"bigint"),r=xh(t),i=typeof r=="function"?r:void 0,o=Ca(t,"maximumDepth"),a=Ca(t,"maximumBreadth");function c(h,d,m,g,y,b){let w=d[h];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(h)),w=g.call(d,h,w),typeof w){case"string":return qe(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return n;let v="",_=",",T=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(w),y!==""&&(b+=y,v+=`
|
|
20
|
+
`),this.outputHelp({error:!0}));let r=n||{},s=r.exitCode||1,i=r.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in W.env){let n=e.attributeName();(this.getOptionValue(n)===void 0||["default","config","env"].includes(this.getOptionValueSource(n)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,W.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ou(this.options),n=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&n(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(s=>!n(s)).forEach(s=>{this.setOptionValueWithSource(s,r.implied[s],"implied")})})}missingArgument(e){let n=`error: missing required argument '${e}'`;this.error(n,{code:"commander.missingArgument"})}optionMissingArgument(e){let n=`error: option '${e.flags}' argument missing`;this.error(n,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let n=`error: required option '${e.flags}' not specified`;this.error(n,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,n){let r=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(f=>f.negate&&a===f.attributeName()),u=this.options.find(f=>!f.negate&&a===f.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},s=o=>{let a=r(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(n)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let n="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);n=Ti(e,s)}let r=`error: unknown option '${e}'${n}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let n=this.registeredArguments.length,r=n===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${n} argument${r} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],n="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),n=Ti(e,s)}let r=`error: unknown command '${e}'${n}`;this.error(r,{code:"commander.unknownCommand"})}version(e,n,r){if(e===void 0)return this._version;this._version=e,n=n||"-V, --version",r=r||"output the version number";let s=this.createOption(n,r);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,n){return e===void 0&&n===void 0?this._description:(this._description=e,n&&(this._argsDescription=n),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let n=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(n=this.commands[this.commands.length-1]),e===n._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let s=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return n._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(n=>this.alias(n)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let n=this.registeredArguments.map(r=>Eu(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?n:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Oe.basename(e,Oe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let n=this.createHelp();return n.helpWidth===void 0&&(n.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),n.formatHelp(this,n)}_getHelpContext(e){e=e||{};let n={error:!!e.error},r;return n.error?r=s=>this._outputConfiguration.writeErr(s):r=s=>this._outputConfiguration.writeOut(s),n.write=e.write||r,n.command=this,n}outputHelp(e){let n;typeof e=="function"&&(n=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let s=this.helpInformation(r);if(n&&(s=n(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",r))}helpOption(e,n){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",n=n??"display help for command",this._helpOption=this.createOption(e,n),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let n=W.exitCode||0;n===0&&e&&typeof e!="function"&&e.error&&(n=1),this._exit(n,"commander.help","(outputHelp)")}addHelpText(e,n){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${r.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof n=="function"?o=n({error:i.error,command:i.command}):o=n,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let n=this._getHelpOption();n&&e.find(s=>n.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ci(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let n,r="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?n=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(n=i[1],/^\d+$/.test(i[3])?s=i[3]:r=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(n=i[1],r=i[3],s=i[4]),n&&s!=="0"?`${n}=${r}:${parseInt(s)+1}`:e})}$i.Command=yr});var Ii=j(le=>{var{Argument:Ai}=an(),{Command:wr}=Ei(),{CommanderError:Ru,InvalidArgumentError:Oi}=Pt(),{Help:Iu}=lr(),{Option:Ri}=pr();le.program=new wr;le.createCommand=t=>new wr(t);le.createOption=(t,e)=>new Ri(t,e);le.createArgument=(t,e)=>new Ai(t,e);le.Command=wr;le.Option=Ri;le.Argument=Ai;le.Help=Iu;le.CommanderError=Ru;le.InvalidArgumentError=Oi;le.InvalidOptionArgumentError=Oi});var Sr=j((Sw,Ni)=>{"use strict";var Mt=t=>t&&typeof t.message=="string",xr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let n=t.cause();return Mt(n)?n:void 0}else return Mt(e)?e:void 0},Li=(t,e)=>{if(!Mt(t))return"";let n=t.stack||"";if(e.has(t))return n+`
|
|
24
|
+
causes have become circular...`;let r=xr(t);return r?(e.add(t),n+`
|
|
25
|
+
caused by: `+Li(r,e)):n},ju=t=>Li(t,new Set),Di=(t,e,n)=>{if(!Mt(t))return"";let r=n?"":t.message||"";if(e.has(t))return r+": ...";let s=xr(t);if(s){e.add(t);let i=typeof t.cause=="function";return r+(i?"":": ")+Di(s,e,i)}else return r},Pu=t=>Di(t,new Set);Ni.exports={isErrorLike:Mt,getErrorCause:xr,stackWithCauses:ju,messageWithCauses:Pu}});var vr=j((vw,qi)=>{"use strict";var Mu=Symbol("circular-ref-tag"),cn=Symbol("pino-raw-err-ref"),Ui=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[cn]},set:function(t){this[cn]=t}}});Object.defineProperty(Ui,cn,{writable:!0,value:{}});qi.exports={pinoErrProto:Ui,pinoErrorSymbols:{seen:Mu,rawSymbol:cn}}});var Wi=j((_w,Hi)=>{"use strict";Hi.exports=kr;var{messageWithCauses:Fu,stackWithCauses:Lu,isErrorLike:Bi}=Sr(),{pinoErrProto:Du,pinoErrorSymbols:Nu}=vr(),{seen:_r}=Nu,{toString:Uu}=Object.prototype;function kr(t){if(!Bi(t))return t;t[_r]=void 0;let e=Object.create(Du);e.type=Uu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Fu(t),e.stack=Lu(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(n=>kr(n)));for(let n in t)if(e[n]===void 0){let r=t[n];Bi(r)?n!=="cause"&&!Object.prototype.hasOwnProperty.call(r,_r)&&(e[n]=kr(r)):e[n]=r}return delete t[_r],e.raw=t,e}});var zi=j((kw,Vi)=>{"use strict";Vi.exports=un;var{isErrorLike:Tr}=Sr(),{pinoErrProto:qu,pinoErrorSymbols:Bu}=vr(),{seen:ln}=Bu,{toString:Hu}=Object.prototype;function un(t){if(!Tr(t))return t;t[ln]=void 0;let e=Object.create(qu);e.type=Hu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(n=>un(n))),Tr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,ln)&&(e.cause=un(t.cause));for(let n in t)if(e[n]===void 0){let r=t[n];Tr(r)?Object.prototype.hasOwnProperty.call(r,ln)||(e[n]=un(r)):e[n]=r}return delete t[ln],e.raw=t,e}});var Yi=j((Tw,Ji)=>{"use strict";Ji.exports={mapHttpRequest:Wu,reqSerializer:Gi};var Cr=Symbol("pino-raw-req-ref"),Ki=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[Cr]},set:function(t){this[Cr]=t}}});Object.defineProperty(Ki,Cr,{writable:!0,value:{}});function Gi(t){let e=t.info||t.socket,n=Object.create(Ki);if(n.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),n.method=t.method,t.originalUrl)n.url=t.originalUrl;else{let r=t.path;n.url=typeof r=="string"?r:t.url?t.url.path||t.url:void 0}return t.query&&(n.query=t.query),t.params&&(n.params=t.params),n.headers=t.headers,n.remoteAddress=e&&e.remoteAddress,n.remotePort=e&&e.remotePort,n.raw=t.raw||t,n}function Wu(t){return{req:Gi(t)}}});var eo=j((Cw,Zi)=>{"use strict";Zi.exports={mapHttpResponse:Vu,resSerializer:Qi};var $r=Symbol("pino-raw-res-ref"),Xi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[$r]},set:function(t){this[$r]=t}}});Object.defineProperty(Xi,$r,{writable:!0,value:{}});function Qi(t){let e=Object.create(Xi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Vu(t){return{res:Qi(t)}}});var Ar=j(($w,to)=>{"use strict";var Er=Wi(),zu=zi(),fn=Yi(),dn=eo();to.exports={err:Er,errWithCause:zu,mapHttpRequest:fn.mapHttpRequest,mapHttpResponse:dn.mapHttpResponse,req:fn.reqSerializer,res:dn.resSerializer,wrapErrorSerializer:function(e){return e===Er?e:function(r){return e(Er(r))}},wrapRequestSerializer:function(e){return e===fn.reqSerializer?e:function(r){return e(fn.reqSerializer(r))}},wrapResponseSerializer:function(e){return e===dn.resSerializer?e:function(r){return e(dn.resSerializer(r))}}}});var Or=j((Ew,no)=>{"use strict";function Ku(t,e){return e}no.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Ku;let n=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(n))return;let r=n.slice(2),s=[];for(let i of r)i&&s.push(i.getFileName());return s}});var co=j((Aw,ao)=>{"use strict";function Rr(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let n=0;n<t.length;n++)e[n]=Rr(t[n]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=Rr(t[n]));return e}return t}function ro(t){let e=[],n="",r=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!r&&a==="."?n&&(e.push(n),n=""):a==="["?(n&&(e.push(n),n=""),r=!0):a==="]"&&r?(e.push(n),n="",r=!1,s=!1):(a==='"'||a==="'")&&r?s?a===i?(s=!1,i=""):n+=a:(s=!0,i=a):n+=a}return n&&e.push(n),e}function so(t,e,n){let r=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof r!="object"||r===null||!(o in r)||typeof r[o]!="object"||r[o]===null)return!1;r=r[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let i=0;i<r.length;i++)r[i]=n;else if(typeof r=="object"&&r!==null)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n)}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&(r[s]=n);return!0}function io(t,e){let n=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof n!="object"||n===null||!(i in n)||typeof n[i]!="object"||n[i]===null)return!1;n=n[i]}let r=e[e.length-1];if(r==="*"){if(Array.isArray(n))for(let s=0;s<n.length;s++)n[s]=void 0;else if(typeof n=="object"&&n!==null)for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}else typeof n=="object"&&n!==null&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}var pn=Symbol("PATH_NOT_FOUND");function Gu(t,e){let n=t;for(let r of e){if(n==null||typeof n!="object"||n===null||!(r in n))return pn;n=n[r]}return n}function Ju(t,e){let n=t;for(let r of e){if(n==null||typeof n!="object"||n===null)return;n=n[r]}return n}function Yu(t,e,n,r=!1){for(let s of e){let i=ro(s);if(i.includes("*"))oo(t,i,n,s,r);else if(r)io(t,i);else{let o=Gu(t,i);if(o===pn)continue;let a=typeof n=="function"?n(o,i):n;so(t,i,a)}}}function oo(t,e,n,r,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let c of o){if(a==null||typeof a!="object"||a===null)return;a=a[c]}if(Array.isArray(a))if(s)for(let c=0;c<a.length;c++)a[c]=void 0;else for(let c=0;c<a.length;c++){let l=[...o,c.toString()],u=typeof n=="function"?n(a[c],l):n;a[c]=u}else if(typeof a=="object"&&a!==null)if(s){let c=[];for(let l in a)Object.prototype.hasOwnProperty.call(a,l)&&c.push(l);for(let l of c)delete a[l]}else for(let c in a){let l=[...o,c],u=typeof n=="function"?n(a[c],l):n;a[c]=u}}else Xu(t,e,n,i,r,s)}function Xu(t,e,n,r,s,i=!1){let o=e.slice(0,r),a=e.slice(r+1),c=[];function l(u,f){if(f===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)c[f]=p.toString(),l(u[p],f+1);else if(typeof u=="object"&&u!==null)for(let p in u)c[f]=p,l(u[p],f+1)}else if(f<o.length){let p=o[f];u&&typeof u=="object"&&u!==null&&p in u&&(c[f]=p,l(u[p],f+1))}else if(a.includes("*"))oo(u,a,typeof n=="function"?(h,d)=>{let m=[...c.slice(0,f),...d];return n(h,m)}:n,s,i);else if(i)io(u,a);else{let p=typeof n=="function"?n(Ju(u,a),[...c.slice(0,f),...a]):n;so(u,a,p)}}if(o.length===0)l(t,0);else{let u=t;for(let f=0;f<o.length;f++){let p=o[f];if(u==null||typeof u!="object"||u===null)return;u=u[p],c[f]=p}u!=null&&l(u,o.length)}}function Qu(t){if(t.length===0)return null;let e=new Map;for(let n of t){let r=ro(n),s=e;for(let i=0;i<r.length;i++){let o=r[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function Zu(t,e){if(!e)return t;function n(r,s,i=0){if(!s||s.size===0||r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(Array.isArray(r)){let a=[];for(let c=0;c<r.length;c++){let l=c.toString();s.has(l)||s.has("*")?a[c]=n(r[c],s.get(l)||s.get("*")):a[c]=r[c]}return a}let o=Object.create(Object.getPrototypeOf(r));for(let a in r)Object.prototype.hasOwnProperty.call(r,a)&&(s.has(a)||s.has("*")?o[a]=n(r[a],s.get(a)||s.get("*")):o[a]=r[a]);return o}return n(t,e)}function ef(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,n=!1,r="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)n?i===r&&(n=!1,r=""):(n=!0,r=i);else if(i==="["&&!n)e++;else if(i==="]"&&!n&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function tf(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)ef(e)}function nf(t={}){let{paths:e=[],censor:n="[REDACTED]",serialize:r=JSON.stringify,strict:s=!0,remove:i=!1}=t;tf(e);let o=Qu(e);return function(c){if(s&&(c===null||typeof c!="object")&&(c==null||typeof c!="object"))return r?r(c):c;let l=Zu(c,o),u=c,f=n;return typeof n=="function"&&(f=n),Yu(l,e,f,i),r===!1?(l.restore=function(){return Rr(u)},l):typeof r=="function"?r(l):JSON.stringify(l)}}ao.exports=nf});var dt=j((Ow,lo)=>{"use strict";var rf=Symbol("pino.setLevel"),sf=Symbol("pino.getLevel"),of=Symbol("pino.levelVal"),af=Symbol("pino.levelComp"),cf=Symbol("pino.useLevelLabels"),lf=Symbol("pino.useOnlyCustomLevels"),uf=Symbol("pino.mixin"),ff=Symbol("pino.lsCache"),df=Symbol("pino.chindings"),pf=Symbol("pino.asJson"),hf=Symbol("pino.write"),mf=Symbol("pino.redactFmt"),gf=Symbol("pino.time"),yf=Symbol("pino.timeSliceIndex"),wf=Symbol("pino.stream"),bf=Symbol("pino.stringify"),xf=Symbol("pino.stringifySafe"),Sf=Symbol("pino.stringifiers"),vf=Symbol("pino.end"),_f=Symbol("pino.formatOpts"),kf=Symbol("pino.messageKey"),Tf=Symbol("pino.errorKey"),Cf=Symbol("pino.nestedKey"),$f=Symbol("pino.nestedKeyStr"),Ef=Symbol("pino.mixinMergeStrategy"),Af=Symbol("pino.msgPrefix"),Of=Symbol("pino.wildcardFirst"),Rf=Symbol.for("pino.serializers"),If=Symbol.for("pino.formatters"),jf=Symbol.for("pino.hooks"),Pf=Symbol.for("pino.metadata");lo.exports={setLevelSym:rf,getLevelSym:sf,levelValSym:of,levelCompSym:af,useLevelLabelsSym:cf,mixinSym:uf,lsCacheSym:ff,chindingsSym:df,asJsonSym:pf,writeSym:hf,serializersSym:Rf,redactFmtSym:mf,timeSym:gf,timeSliceIndexSym:yf,streamSym:wf,stringifySym:bf,stringifySafeSym:xf,stringifiersSym:Sf,endSym:vf,formatOptsSym:_f,messageKeySym:kf,errorKeySym:Tf,nestedKeySym:Cf,wildcardFirstSym:Of,needsMetadataGsym:Pf,useOnlyCustomLevelsSym:lf,formattersSym:If,hooksSym:jf,nestedKeyStrSym:$f,mixinMergeStrategySym:Ef,msgPrefixSym:Af}});var jr=j((Rw,ho)=>{"use strict";var uo=co(),{redactFmtSym:Mf,wildcardFirstSym:hn}=dt(),Ir=/[^.[\]]+|\[([^[\]]*?)\]/g,fo="[Redacted]",po=!1;function Ff(t,e){let{paths:n,censor:r,remove:s}=Lf(t),i=n.reduce((c,l)=>{Ir.lastIndex=0;let u=Ir.exec(l),f=Ir.exec(l),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=hn),f===null)return c[p]=null,c;if(c[p]===null)return c;let{index:h}=f,d=`${l.substr(h,l.length-1)}`;return c[p]=c[p]||[],p!==hn&&c[p].length===0&&c[p].push(...c[hn]||[]),p===hn&&Object.keys(c).forEach(function(m){c[m]&&c[m].push(d)}),c[p].push(d),c},{}),o={[Mf]:uo({paths:n,censor:r,serialize:e,strict:po,remove:s})},a=(...c)=>e(typeof r=="function"?r(...c):r);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((c,l)=>{if(i[l]===null)c[l]=u=>a(u,[l]);else{let u=typeof r=="function"?(f,p)=>r(f,[l,...p]):r;c[l]=uo({paths:i[l],censor:u,serialize:e,strict:po,remove:s})}return c},o)}function Lf(t){if(Array.isArray(t))return t={paths:t,censor:fo},t;let{paths:e,censor:n=fo,remove:r}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return r===!0&&(n=void 0),{paths:e,censor:n,remove:r}}ho.exports=Ff});var yo=j((Iw,go)=>{"use strict";var Df=()=>"",Nf=()=>`,"time":${Date.now()}`,Uf=()=>`,"time":${Math.round(Date.now()/1e3)}`,qf=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Bf=1000000n,mo=1000000000n,Hf=BigInt(Date.now())*Bf,Wf=process.hrtime.bigint(),Vf=()=>{let t=process.hrtime.bigint()-Wf,e=Hf+t,n=e/mo,r=e%mo,s=Number(n*1000n+r/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${c}T${l}:${u}:${f}.${r.toString().padStart(9,"0")}Z"`};go.exports={nullTime:Df,epochTime:Nf,unixTime:Uf,isoTime:qf,isoTimeNano:Vf}});var bo=j((jw,wo)=>{"use strict";function zf(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}wo.exports=Kf;function Kf(t,e,n){var r=n&&n.stringify||zf,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=r(t);for(var a=1;a<i;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-s,f=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(u>=c||e[u]==null)break;f<h&&(l+=t.slice(f,h)),l+=Number(e[u]),f=h+2,h++;break;case 105:if(u>=c||e[u]==null)break;f<h&&(l+=t.slice(f,h)),l+=Math.floor(Number(e[u])),f=h+2,h++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;f<h&&(l+=t.slice(f,h));var d=typeof e[u];if(d==="string"){l+="'"+e[u]+"'",f=h+2,h++;break}if(d==="function"){l+=e[u].name||"<anonymous>",f=h+2,h++;break}l+=r(e[u]),f=h+2,h++;break;case 115:if(u>=c)break;f<h&&(l+=t.slice(f,h)),l+=String(e[u]),f=h+2,h++;break;case 37:f<h&&(l+=t.slice(f,h)),l+="%",f=h+2,h++,u--;break}++u}++h}return f===-1?t:(f<p&&(l+=t.slice(f)),l)}});var Mr=j((Pw,Pr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(n){if((n>0&&n<1/0)===!1)throw typeof n!="number"&&typeof n!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(n))},t=new Int32Array(new SharedArrayBuffer(4));Pr.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let r=Date.now()+Number(e);for(;r>Date.now(););};Pr.exports=t}});var $o=j((Mw,Co)=>{"use strict";var q=require("fs"),Gf=require("events"),Jf=require("util").inherits,xo=require("path"),Lr=Mr(),Yf=require("assert"),mn=100,gn=Buffer.allocUnsafe(0),Xf=16*1024,So="buffer",vo="utf8",[Qf,Zf]=(process.versions.node||"0.0").split(".").map(Number),ed=Qf>=22&&Zf>=7;function _o(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function n(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let r=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&q.mkdirSync(xo.dirname(t),{recursive:!0});let i=q.openSync(t,r,s);n(null,i)}catch(i){throw n(i),i}else e.mkdir?q.mkdir(xo.dirname(t),{recursive:!0},i=>{if(i)return n(i);q.open(t,r,s,n)}):q.open(t,r,s,n)}function be(t){if(!(this instanceof be))return new be(t);let{fd:e,dest:n,minLength:r,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:c=!0,mkdir:l,retryEAGAIN:u,fsync:f,contentMode:p,mode:h}=t||{};e=e||n,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(r||0,16387),this.file=null,this.destroyed=!1,this.minLength=r||0,this.maxLength=s||0,this.maxWrite=i||Xf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=c||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=l||!1;let d,m;if(p===So)this._writingBuf=gn,this.write=rd,this.flush=id,this.flushSync=ad,this._actualWrite=ld,d=()=>q.writeSync(this.fd,this._writingBuf),m=()=>q.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===vo)this._writingBuf="",this.write=nd,this.flush=sd,this.flushSync=od,this._actualWrite=cd,d=()=>Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?q.write(this.fd,this._writingBuf,this.release):q.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${vo}" and "${So}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")_o(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,y)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Lr(mn),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(m,mn);else this._writing=!1,this.emit("error",g);return}this.emit("write",y);let b=Fr(this._writingBuf,this._len,y);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let v=d(),_=Fr(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&q.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,yn(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(td,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 Fr(t,e,n){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-n,0),t=t.subarray(n),{writingBuf:t,len:e}}function td(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Jf(be,Gf);function ko(t,e){return t.length===0?gn:t.length===1?t[0]:Buffer.concat(t,e)}function nd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),n=this._len+e,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+e>this.maxWrite?r.push(t):r[r.length-1]+=t,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function rd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,n=this._bufs,r=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||r[r.length-1]+t.length>this.maxWrite?(n.push([t]),r.push(t.length)):(n[n.length-1].push(t),r[r.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function To(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{q.fsync(this.fd,r=>{this._flushPending=!1,t(r)})}catch(r){t(r)}this.off("error",n)},n=r=>{this._flushPending=!1,t(r),this.off("drain",e)};this.once("drain",e),this.once("error",n)}function sd(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&&To.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function id(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&&To.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}be.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&q.close(e,n=>{if(n)return this.emit("error",n)})}),_o(this.file,this)};be.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():yn(this)))};function od(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?q.writeSync(this.fd,t):q.writeSync(this.fd,t,"utf8"),n=Fr(t,this._len,e);t=n.writingBuf,this._len=n.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Lr(mn)}}try{q.fsyncSync(this.fd)}catch{}}function ad(){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=gn);let t=gn;for(;this._bufs.length||t.length;){t.length<=0&&(t=ko(this._bufs[0],this._lens[0]));try{let e=q.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Lr(mn)}}}be.prototype.destroy=function(){this.destroyed||yn(this)};function cd(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else q.write(this.fd,this._writingBuf,t)}function ld(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:ko(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=q.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else ed&&(this._writingBuf=Buffer.from(this._writingBuf)),q.write(this.fd,this._writingBuf,t)}function yn(t){if(t.fd===-1){t.once("ready",yn.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Yf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{q.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?q.close(t.fd,n):n()}function n(r){if(r){t.emit("error",r);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}be.SonicBoom=be;be.default=be;Co.exports=be});var Dr=j((Fw,Io)=>{"use strict";var xe={exit:[],beforeExit:[]},Eo={exit:dd,beforeExit:pd},pt;function ud(){pt===void 0&&(pt=new FinalizationRegistry(hd))}function fd(t){xe[t].length>0||process.on(t,Eo[t])}function Ao(t){xe[t].length>0||(process.removeListener(t,Eo[t]),xe.exit.length===0&&xe.beforeExit.length===0&&(pt=void 0))}function dd(){Oo("exit")}function pd(){Oo("beforeExit")}function Oo(t){for(let e of xe[t]){let n=e.deref(),r=e.fn;n!==void 0&&r(n,t)}xe[t]=[]}function hd(t){for(let e of["exit","beforeExit"]){let n=xe[e].indexOf(t);xe[e].splice(n,n+1),Ao(e)}}function Ro(t,e,n){if(e===void 0)throw new Error("the object can't be undefined");fd(t);let r=new WeakRef(e);r.fn=n,ud(),pt.register(e,r),xe[t].push(r)}function md(t,e){Ro("exit",t,e)}function gd(t,e){Ro("beforeExit",t,e)}function yd(t){if(pt!==void 0){pt.unregister(t);for(let e of["exit","beforeExit"])xe[e]=xe[e].filter(n=>{let r=n.deref();return r&&r!==t}),Ao(e)}}Io.exports={register:md,registerBeforeExit:gd,unregister:yd}});var jo=j((Lw,wd)=>{wd.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 Mo=j((Dw,Po)=>{"use strict";function bd(t,e,n,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{let a=Atomics.load(t,e);if(a===n){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,a,c);l.async?l.value.then(o):setImmediate(o)};o()}function xd(t,e,n,r,s){let i=r===1/0?1/0:Date.now()+r,o=()=>{if(Atomics.load(t,e)!==n){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,n,c);l.async?l.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Po.exports={wait:bd,waitDiff:xd}});var Lo=j((Nw,Fo)=>{"use strict";Fo.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Jo=j((Uw,Go)=>{"use strict";var{version:Sd}=jo(),{EventEmitter:vd}=require("events"),{Worker:_d}=require("worker_threads"),{join:kd}=require("path"),{pathToFileURL:Td}=require("url"),{wait:Cd}=Mo(),{WRITE_INDEX:Re,READ_INDEX:Xe,SEQ_INDEX:Nr}=Lo(),$d=require("buffer"),Ed=require("assert"),S=Symbol("kImpl"),Ad=$d.constants.MAX_STRING_LENGTH;function Do(){}function Hr(t,e){Atomics.add(t[S].state,Nr,1),e(),Atomics.add(t[S].state,Nr,1),Atomics.notify(t[S].state,Nr)}function No(t){Hr(t,()=>{Atomics.store(t[S].state,Xe,0),Atomics.store(t[S].state,Re,0)})}var Ft=class{constructor(e){this._value=e}deref(){return this._value}},wn=class{register(){}unregister(){}},Od=process.env.NODE_V8_COVERAGE?wn:global.FinalizationRegistry||wn,Rd=process.env.NODE_V8_COVERAGE?Ft:global.WeakRef||Ft,Uo=new Od(t=>{t.exited||t.terminate()});function Id(t,e){let{filename:n,workerData:r}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||kd(__dirname,"lib","worker.js"),o=new _d(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:n.indexOf("file://")===0?n:Td(n).href,dataBuf:t[S].dataBuf,stateBuf:t[S].stateBuf,workerData:{$context:{threadStreamVersion:Sd},...r}}});return o.stream=new Ft(t),o.on("message",jd),o.on("exit",Ho),Uo.register(t,o),o}function qo(t){Ed(!t[S].sync),t[S].needDrain&&(t[S].needDrain=!1,t.emit("drain"))}function Bo(t){for(;;){let e=Atomics.load(t[S].state,Re),n=t[S].data.length-e;if(n>0){if(t[S].bufLen===0){t[S].flushing=!1,t[S].ending?Wr(t):t[S].needDrain&&process.nextTick(qo,t);return}zo(t,n,Do);continue}if(n===0){if(e===0&&t[S].bufLen===0)return;bn(t,()=>{t.destroyed||(No(t),Bo(t))});return}fe(t,new Error("overwritten"));return}}function jd(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 Rd(e),bn(e,()=>{e[S].ready=!0,e.emit("ready")});break;case"ERROR":fe(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"){fe(e,new Error("this should not happen: "+t.code));break}let n=e[S].flushCallbacks.get(t.id);n&&(e[S].flushCallbacks.delete(t.id),process.nextTick(n));break}case"WARNING":process.emitWarning(t.err);break;default:fe(e,new Error("this should not happen: "+t.code))}}function Ho(t){let e=this.stream.deref();e!==void 0&&(Uo.unregister(e),e.worker.exited=!0,e.worker.off("exit",Ho),fe(e,t!==0?new Error("the worker thread exited"):null))}var qr=class extends vd{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=Id(this,e),this.on("message",(n,r)=>{this.worker.postMessage(n,r)})}write(e){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[S].destroyed)return Br(this,new Error("the worker has exited")),!1;if(this[S].ending)return Br(this,new Error("the worker is ending")),!1;if(this[S].flushing&&this[S].bufLen+n.length>=Ad)try{Ur(this),this[S].flushing=!0}catch(r){return fe(this,r),!1}if(this[S].buf.push(n),this[S].bufLen+=n.length,this[S].sync)try{return Ur(this),!0}catch(r){return fe(this,r),!1}return this[S].flushing||(this[S].flushing=!0,setImmediate(Bo,this)),this[S].needDrain=this[S].data.length-this[S].bufLen-Atomics.load(this[S].state,Re)<=0,!this[S].needDrain}end(){this[S].destroyed||(this[S].ending=!0,Wr(this))}flush(e){e=typeof e=="function"?e:Do,Wo(this,n=>{if(n){process.nextTick(e,n);return}Vo(this,e)})}flushSync(){this[S].destroyed||(Ur(this),Ko(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 Wo(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(Wo,t,e);return}bn(t,e)}function bn(t,e){let n=Atomics.load(t[S].state,Re);Cd(t[S].state,Xe,n,1/0,(r,s)=>{if(r){fe(t,r),e(r);return}if(s!=="ok"){bn(t,e);return}e()})}function Vo(t,e){if(t[S].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[S].ready){let r=()=>{i(),Vo(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",r),t.off("close",s)};t.once("ready",r),t.once("close",s);return}let n=++t[S].nextFlushId;t[S].flushCallbacks.set(n,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:n})}catch(r){t[S].flushCallbacks.delete(n),fe(t,r),process.nextTick(e,r)}}function Pd(t,e){let n=t[S].flushCallbacks;if(n.size===0)return;let r=e||new Error("the worker has exited");for(let s of n.values())process.nextTick(s,r);n.clear()}function Br(t,e){setImmediate(()=>{t.emit("error",e)})}function fe(t,e){t[S].destroyed||(t[S].destroyed=!0,Pd(t,e),e&&(t[S].errored=e,Br(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 zo(t,e,n){let s=Atomics.load(t[S].state,Re),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 Hr(t,()=>{Atomics.store(t[S].state,Re,s)}),n(),!0}function Wr(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,Xe);Hr(t,()=>{Atomics.store(t[S].state,Re,-1)});let n=0;for(;e!==-1;){if(Atomics.wait(t[S].state,Xe,e,1e3),e=Atomics.load(t[S].state,Xe),e===-2){fe(t,new Error("end() failed"));return}if(++n===10){fe(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[S].finished=!0,t.emit("finish")})}catch(e){fe(t,e)}}}function Ur(t){let e=()=>{t[S].ending?Wr(t):t[S].needDrain&&process.nextTick(qo,t)};for(t[S].flushing=!1;t[S].bufLen!==0;){let n=Atomics.load(t[S].state,Re),r=t[S].data.length-n;if(r===0){Ko(t),No(t);continue}else if(r<0)throw new Error("overwritten");zo(t,r,e)}}function Ko(t){if(t[S].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[S].state,Re),n=0;for(;;){let r=Atomics.load(t[S].state,Xe);if(r===-2)throw Error("_flushSync failed");if(r!==e)Atomics.wait(t[S].state,Xe,r,1e3);else break;if(++n===10)throw new Error("_flushSync took too long (10s)")}}Go.exports=qr});var Kr=j((qw,Qo)=>{"use strict";var{createRequire:Md}=require("module"),{existsSync:Fd}=require("node:fs"),Ld=Or(),{join:Vr,isAbsolute:Xo,sep:Dd}=require("node:path"),{fileURLToPath:Nd}=require("node:url"),Ud=Mr(),zr=Dr(),qd=Jo();function Bd(t){zr.register(t,Kd),zr.registerBeforeExit(t,Gd),t.on("close",function(){zr.unregister(t)})}function Hd(){let t=process.execArgv;for(let e=0;e<t.length;e++){let n=t[e];if(n==="--import"||n==="--require"||n==="-r"||n.startsWith("--import=")||n.startsWith("--require=")||n.startsWith("-r="))return!0}return!1}function Wd(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let n=[],r=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&Yo(o)){r=!0,s++;continue}n.push(i),o&&(n.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Yo(o)){r=!0;continue}}n.push(i)}return r?n.join(" "):t}function Yo(t){let e=Vd(t);if(!e)return!1;let n=e;if(n.startsWith("file://"))try{n=Nd(n)}catch{return!1}return Xo(n)&&!Fd(n)}function Vd(t){let e=t[0],n=t[t.length-1];return e==='"'&&n==='"'||e==="'"&&n==="'"?t.slice(1,-1):t}function zd(t,e,n,r,s){if(!n.execArgv&&Hd()&&require.main===void 0&&(n={...n,execArgv:[]}),!n.env&&process.env.NODE_OPTIONS){let c=Wd(process.env.NODE_OPTIONS);c!==process.env.NODE_OPTIONS&&(n={...n,env:{...process.env,NODE_OPTIONS:c}})}n={...n,name:s};let i=new qd({filename:t,workerData:e,workerOpts:n,sync:r});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),n.autoEnd!==!1&&Bd(i)}function a(){i.closed||(i.flushSync(),Ud(100),i.end())}return i}function Kd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Gd(t){t.flushSync()}function Jd(t){let{pipeline:e,targets:n,levels:r,dedupe:s,worker:i={},caller:o=Ld(),sync:a=!1}=t,c={...t.options},l=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),f=t.target;if(f&&n)throw new Error("only one of target or targets can be specified");n?(f=u["pino-worker"]||Vr(__dirname,"worker.js"),c.targets=n.filter(d=>d.target).map(d=>({...d,target:h(d.target)})),c.pipelines=n.filter(d=>d.pipeline).map(d=>d.pipeline.map(m=>({...m,level:d.level,target:h(m.target)})))):e&&(f=u["pino-worker"]||Vr(__dirname,"worker.js"),c.pipelines=[e.map(d=>({...d,target:h(d.target)}))]),r&&(c.levels=r),s&&(c.dedupe=s),c.pinoWillSendConfig=!0;let p=n||e?"pino.transport":f;return zd(h(f),c,i,a,p);function h(d){if(d=u[d]||d,Xo(d)||d.indexOf("file://")===0)return d;if(d==="pino/file")return Vr(__dirname,"..","file.js");let m;for(let g of l)try{let y=g==="node:repl"?process.cwd()+Dd:g;m=Md(y).resolve(d);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${d}"`);return m}}Qo.exports=Jd});var vn=j((Bw,fa)=>{"use strict";var Yd=require("node:diagnostics_channel"),Zo=bo(),{mapHttpRequest:Xd,mapHttpResponse:Qd}=Ar(),Jr=$o(),ea=Dr(),{lsCacheSym:Zd,chindingsSym:ia,writeSym:ta,serializersSym:oa,formatOptsSym:na,endSym:ep,stringifiersSym:aa,stringifySym:ca,stringifySafeSym:Yr,wildcardFirstSym:la,nestedKeySym:tp,formattersSym:ua,messageKeySym:np,errorKeySym:rp,nestedKeyStrSym:sp,msgPrefixSym:xn}=dt(),{isMainThread:ip}=require("worker_threads"),op=Kr(),[ap]=process.versions.node.split(".").map(t=>Number(t)),ra=Yd.tracingChannel("pino_asJson"),Gr=ap>=25?t=>JSON.stringify(t):lp;function ht(){}function cp(t,e){if(!e)return n;return function(...s){e.call(this,s,n,t)};function n(r,...s){if(typeof r=="object"){let i=r;r!==null&&(r.method&&r.headers&&r.socket?r=Xd(r):typeof r.setHeader=="function"&&(r=Qd(r)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[xn]=="string"&&i!==void 0&&i!==null&&(i=this[xn]+i),this[ta](r,Zo(i,o,this[na]),t)}else{let i=r===void 0?s.shift():r;typeof this[xn]=="string"&&i!==void 0&&i!==null&&(i=this[xn]+i),this[ta](null,Zo(i,s,this[na]),t)}}}function lp(t){let e="",n=0,r=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(n,o)+"\\",n=o,r=!0);return r?e+=t.slice(n):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function up(t,e,n,r){if(ra.hasSubscribers===!1)return sa.call(this,t,e,n,r);let s={instance:this,arguments};return ra.traceSync(sa,s,this,t,e,n,r)}function sa(t,e,n,r){let s=this[ca],i=this[Yr],o=this[aa],a=this[ep],c=this[ia],l=this[oa],u=this[ua],f=this[np],p=this[rp],h=this[Zd][n]+r;h=h+c;let d;u.log&&(t=u.log(t));let m=o[la],g="";for(let b in t)if(d=t[b],Object.prototype.hasOwnProperty.call(t,b)&&d!==void 0){l[b]?d=l[b](d):b===p&&l.err&&(d=l.err(d));let w=o[b]||m;switch(typeof d){case"undefined":case"function":continue;case"number":Number.isFinite(d)===!1&&(d=null);case"boolean":w&&(d=w(d));break;case"string":d=(w||Gr)(d);break;default:d=(w||s)(d,i)}if(d===void 0)continue;let v=Gr(b);g+=","+v+":"+d}let y="";if(e!==void 0){d=l[f]?l[f](e):e;let b=o[f]||m;switch(typeof d){case"function":break;case"number":Number.isFinite(d)===!1&&(d=null);case"boolean":b&&(d=b(d)),y=',"'+f+'":'+d;break;case"string":d=(b||Gr)(d),y=',"'+f+'":'+d;break;default:d=(b||s)(d,i),y=',"'+f+'":'+d}}return this[tp]&&g?h+this[sp]+g.slice(1)+"}"+y+a:h+g+y+a}function fp(t,e){let n,r=t[ia],s=t[ca],i=t[Yr],o=t[aa],a=o[la],c=t[oa],l=t[ua].bindings;e=l(e);for(let u in e)if(n=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&n!==void 0)===!0){if(n=c[u]?c[u](n):n,n=(o[u]||a||s)(n,i),n===void 0)continue;r+=',"'+u+'":'+n}return r}function dp(t){return t.write!==t.constructor.prototype.write}function Sn(t){let e=new Jr(t);return e.on("error",n),!t.sync&&ip&&(ea.register(e,pp),e.on("close",function(){ea.unregister(e)})),e;function n(r){if(r.code==="EPIPE"){e.write=ht,e.end=ht,e.flushSync=ht,e.destroy=ht;return}e.removeListener("error",n),e.emit("error",r)}}function pp(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function hp(t){return function(n,r,s={},i){if(typeof s=="string")i=Sn({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=Sn({dest:i})}else if(s instanceof Jr||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof Jr||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 c;s.customLevels&&(c=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=op({caller:r,...s.transport,levels:c})}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=ht),i||(dp(process.stdout)?i=process.stdout:i=Sn({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function mp(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Yr])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function gp(t,e,n){return{level:t,bindings:e,log:n}}function yp(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}fa.exports={noop:ht,buildSafeSonicBoom:Sn,asChindings:fp,asJson:up,genLog:cp,createArgsNormalizer:hp,stringify:mp,buildFormatters:gp,normalizeDestFileDescriptor:yp}});var _n=j((Hw,da)=>{var wp={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},bp={ASC:"ASC",DESC:"DESC"};da.exports={DEFAULT_LEVELS:wp,SORTING_ORDER:bp}});var Zr=j((Ww,ga)=>{"use strict";var{lsCacheSym:xp,levelValSym:Xr,useOnlyCustomLevelsSym:Sp,streamSym:vp,formattersSym:_p,hooksSym:kp,levelCompSym:pa}=dt(),{noop:Tp,genLog:Qe}=vn(),{DEFAULT_LEVELS:Te,SORTING_ORDER:ha}=_n(),ma={fatal:t=>{let e=Qe(Te.fatal,t);return function(...n){let r=this[vp];if(e.call(this,...n),typeof r.flushSync=="function")try{r.flushSync()}catch{}}},error:t=>Qe(Te.error,t),warn:t=>Qe(Te.warn,t),info:t=>Qe(Te.info,t),debug:t=>Qe(Te.debug,t),trace:t=>Qe(Te.trace,t)},Qr=Object.keys(Te).reduce((t,e)=>(t[Te[e]]=e,t),{}),Cp=Object.keys(Qr).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function $p(t){let e=t[_p].level,{labels:n}=t.levels,r={};for(let s in n){let i=e(n[s],Number(s));r[s]=JSON.stringify(i).slice(0,-1)}return t[xp]=r,t}function Ep(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 Ap(t){let{labels:e,values:n}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(n[t]===void 0)throw Error("unknown level "+t);let r=this[Xr],s=this[Xr]=n[t],i=this[Sp],o=this[pa],a=this[kp].logMethod;for(let c in n){if(o(n[c],s)===!1){this[c]=Tp;continue}this[c]=Ep(c,i)?ma[c](a):Qe(n[c],a)}this.emit("level-change",t,s,e[r],r,this)}function Op(t){let{levels:e,levelVal:n}=this;return e&&e.labels?e.labels[n]:""}function Rp(t){let{values:e}=this.levels,n=e[t];return n!==void 0&&this[pa](n,this[Xr])}function Ip(t,e,n){return t===ha.DESC?e<=n:e>=n}function jp(t){return typeof t=="string"?Ip.bind(null,t):t}function Pp(t=null,e=!1){let n=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,r=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Qr,n),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:Te,t);return{labels:r,values:s}}function Mp(t,e,n){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),n?[]:Object.keys(Qr).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:Te,e);if(!(t in r))throw Error(`default level:${t} must be included in custom levels`)}function Fp(t,e){let{labels:n,values:r}=t;for(let s in e){if(s in r)throw Error("levels cannot be overridden");if(e[s]in n)throw Error("pre-existing level values cannot be used for new levels")}}function Lp(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(ha).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ga.exports={initialLsCache:Cp,genLsCache:$p,levelMethods:ma,getLevel:Op,setLevel:Ap,isLevelEnabled:Rp,mappings:Pp,assertNoLevelCollisions:Fp,assertDefaultLevelFound:Mp,genLevelComparison:jp,assertLevelComparison:Lp}});var es=j((Vw,ya)=>{"use strict";ya.exports={version:"10.3.1"}});var Ta=j((Kw,ka)=>{"use strict";var{EventEmitter:Dp}=require("node:events"),{lsCacheSym:Np,levelValSym:Up,setLevelSym:ns,getLevelSym:wa,chindingsSym:Tn,mixinSym:qp,asJsonSym:xa,writeSym:Bp,mixinMergeStrategySym:Hp,timeSym:Wp,timeSliceIndexSym:Vp,streamSym:Sa,serializersSym:Ze,formattersSym:Lt,errorKeySym:zp,messageKeySym:Kp,useOnlyCustomLevelsSym:Gp,needsMetadataGsym:Jp,redactFmtSym:Yp,stringifySym:Xp,formatOptsSym:Qp,stringifiersSym:Zp,msgPrefixSym:rs,hooksSym:eh}=dt(),{getLevel:th,setLevel:nh,isLevelEnabled:rh,mappings:sh,initialLsCache:ih,genLsCache:oh,assertNoLevelCollisions:ah}=Zr(),{asChindings:ss,asJson:ch,buildFormatters:ts,stringify:ba,noop:va}=vn(),{version:lh}=es(),uh=jr(),fh=class{},_a={constructor:fh,child:dh,bindings:ph,setBindings:hh,flush:yh,isLevelEnabled:rh,version:lh,get level(){return this[wa]()},set level(t){this[ns](t)},get levelVal(){return this[Up]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[rs]},get[Symbol.toStringTag](){return"Pino"},[Np]:ih,[Bp]:gh,[xa]:ch,[wa]:th,[ns]:nh};Object.setPrototypeOf(_a,Dp.prototype);ka.exports=function(){return Object.create(_a)};var kn=t=>t;function dh(t,e){if(!t)throw Error("missing bindings for child Pino");let n=this[Ze],r=this[Lt],s=Object.create(this);if(e==null)return s[Lt].bindings!==kn&&(s[Lt]=ts(r.level,kn,r.log)),s[Tn]=ss(s,t),this.onChild!==va&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[Ze]=Object.create(null);for(let l in n)s[Ze][l]=n[l];let a=Object.getOwnPropertySymbols(n);for(var i=0;i<a.length;i++){let l=a[i];s[Ze][l]=n[l]}for(let l in e.serializers)s[Ze][l]=e.serializers[l];let c=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<c.length;o++){let l=c[o];s[Ze][l]=e.serializers[l]}}else s[Ze]=n;if(e.hasOwnProperty("formatters")){let{level:a,bindings:c,log:l}=e.formatters;s[Lt]=ts(a||r.level,c||kn,l||r.log)}else s[Lt]=ts(r.level,kn,r.log);if(e.hasOwnProperty("customLevels")===!0&&(ah(this.levels,e.customLevels),s.levels=sh(e.customLevels,s[Gp]),oh(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=uh(s.redact,ba),c={stringify:a[Yp]};s[Xp]=ba,s[Zp]=a,s[Qp]=c}if(typeof e.msgPrefix=="string"&&(s[rs]=(this[rs]||"")+e.msgPrefix),s[Tn]=ss(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[ns](a)}return this.onChild(s),s}function ph(){let e=`{${this[Tn].substr(1)}}`,n=JSON.parse(e);return delete n.pid,delete n.hostname,n}function hh(t){let e=ss(this,t);this[Tn]=e}function mh(t,e){return Object.assign(e,t)}function gh(t,e,n){let r=this[Wp](),s=this[qp],i=this[zp],o=this[Kp],a=this[Hp]||mh,c,l=this[eh].streamWrite;t==null?c={}:t instanceof Error?(c={[i]:t},e===void 0&&(e=t.message)):(c=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(c=a(c,s(c,n,this)));let u=this[xa](c,e,n,r),f=this[Sa];f[Jp]===!0&&(f.lastLevel=n,f.lastObj=c,f.lastMsg=e,f.lastTime=r.slice(this[Vp]),f.lastLogger=this),f.write(l?l(u):u)}function yh(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Sa];typeof e.flush=="function"?e.flush(t||va):t&&t()}});var Aa=j((cs,Ea)=>{"use strict";var{hasOwnProperty:Dt}=Object.prototype,tt=as();tt.configure=as;tt.stringify=tt;tt.default=tt;cs.stringify=tt;cs.configure=as;Ea.exports=tt;var wh=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function qe(t){return t.length<5e3&&!wh.test(t)?`"${t}"`:JSON.stringify(t)}function is(t,e){if(t.length>200||e)return t.sort(e);for(let n=1;n<t.length;n++){let r=t[n],s=n;for(;s!==0&&t[s-1]>r;)t[s]=t[s-1],s--;t[s]=r}return t}var bh=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function os(t){return bh.call(t)!==void 0&&t.length!==0}function Ca(t,e,n){t.length<n&&(n=t.length);let r=e===","?"":" ",s=`"0":${r}${t[0]}`;for(let i=1;i<n;i++)s+=`${e}"${i}":${r}${t[i]}`;return s}function xh(t){if(Dt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function Sh(t){let e;if(Dt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function vh(t,e){let n;if(Dt.call(t,e)&&(n=t[e],typeof n!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return n===void 0?!0:n}function $a(t,e){let n;if(Dt.call(t,e)){if(n=t[e],typeof n!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(n))throw new TypeError(`The "${e}" argument must be an integer`);if(n<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return n===void 0?1/0:n}function et(t){return t===1?"1 item":`${t} items`}function _h(t){let e=new Set;for(let n of t)(typeof n=="string"||typeof n=="number")&&e.add(String(n));return e}function kh(t){if(Dt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return n=>{let r=`Object can not safely be stringified. Received type ${typeof n}`;throw typeof n!="function"&&(r+=` (${n.toString()})`),new Error(r)}}}function as(t){t={...t};let e=kh(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let n=xh(t),r=vh(t,"bigint"),s=Sh(t),i=typeof s=="function"?s:void 0,o=$a(t,"maximumDepth"),a=$a(t,"maximumBreadth");function c(h,d,m,g,y,b){let w=d[h];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(h)),w=g.call(d,h,w),typeof w){case"string":return qe(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return n;let v="",_=",",T=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(w),y!==""&&(b+=y,v+=`
|
|
26
26
|
${b}`,_=`,
|
|
27
27
|
${b}`);let N=Math.min(w.length,a),H=0;for(;H<N-1;H++){let z=c(String(H),w,m,g,y,b);v+=z!==void 0?z:"null",v+=_}let X=c(String(H),w,m,g,y,b);if(v+=X!==void 0?X:"null",w.length-1>a){let z=w.length-a-1;v+=`${_}"... ${et(z)} not stringified"`}return y!==""&&(v+=`
|
|
28
28
|
${T}`),m.pop(),`[${v}]`}let A=Object.keys(w),E=A.length;if(E===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",P="";y!==""&&(b+=y,_=`,
|
|
29
|
-
${b}`,$=" ");let U=Math.min(E,a);
|
|
29
|
+
${b}`,$=" ");let U=Math.min(E,a);s&&!os(w)&&(A=is(A,i)),m.push(w);for(let N=0;N<U;N++){let H=A[N],X=c(H,w,m,g,y,b);X!==void 0&&(v+=`${P}${qe(H)}:${$}${X}`,P=_)}if(E>a){let N=E-a;v+=`${P}"...":${$}"${et(N)} not stringified"`,P=_}return y!==""&&P.length>1&&(v=`
|
|
30
30
|
${b}${v}
|
|
31
|
-
${T}`),m.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(
|
|
31
|
+
${T}`),m.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(r)return String(w);default:return e?e(w):void 0}}function l(h,d,m,g,y,b){switch(typeof d=="object"&&d!==null&&typeof d.toJSON=="function"&&(d=d.toJSON(h)),typeof d){case"string":return qe(d);case"object":{if(d===null)return"null";if(m.indexOf(d)!==-1)return n;let w=b,v="",_=",";if(Array.isArray(d)){if(d.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(d),y!==""&&(b+=y,v+=`
|
|
32
32
|
${b}`,_=`,
|
|
33
33
|
${b}`);let E=Math.min(d.length,a),$=0;for(;$<E-1;$++){let U=l(String($),d[$],m,g,y,b);v+=U!==void 0?U:"null",v+=_}let P=l(String($),d[$],m,g,y,b);if(v+=P!==void 0?P:"null",d.length-1>a){let U=d.length-a-1;v+=`${_}"... ${et(U)} not stringified"`}return y!==""&&(v+=`
|
|
34
34
|
${w}`),m.pop(),`[${v}]`}m.push(d);let T="";y!==""&&(b+=y,_=`,
|
|
35
35
|
${b}`,T=" ");let A="";for(let E of g){let $=l(E,d[E],m,g,y,b);$!==void 0&&(v+=`${A}${qe(E)}:${T}${$}`,A=_)}return y!==""&&A.length>1&&(v=`
|
|
36
36
|
${b}${v}
|
|
37
|
-
${w}`),m.pop(),`{${v}}`}case"number":return isFinite(d)?String(d):e?e(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(
|
|
37
|
+
${w}`),m.pop(),`{${v}}`}case"number":return isFinite(d)?String(d):e?e(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return e?e(d):void 0}}function u(h,d,m,g,y){switch(typeof d){case"string":return qe(d);case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(h),typeof d!="object")return u(h,d,m,g,y);if(d===null)return"null"}if(m.indexOf(d)!==-1)return n;let b=y;if(Array.isArray(d)){if(d.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(d),y+=g;let $=`
|
|
38
38
|
${y}`,P=`,
|
|
39
39
|
${y}`,U=Math.min(d.length,a),N=0;for(;N<U-1;N++){let X=u(String(N),d[N],m,g,y);$+=X!==void 0?X:"null",$+=P}let H=u(String(N),d[N],m,g,y);if($+=H!==void 0?H:"null",d.length-1>a){let X=d.length-a-1;$+=`${P}"... ${et(X)} not stringified"`}return $+=`
|
|
40
40
|
${b}`,m.pop(),`[${$}]`}let w=Object.keys(d),v=w.length;if(v===0)return"{}";if(o<m.length+1)return'"[Object]"';y+=g;let _=`,
|
|
41
|
-
${y}`,T="",A="",E=Math.min(v,a);
|
|
41
|
+
${y}`,T="",A="",E=Math.min(v,a);os(d)&&(T+=Ca(d,_,a),w=w.slice(d.length),E-=d.length,A=_),s&&(w=is(w,i)),m.push(d);for(let $=0;$<E;$++){let P=w[$],U=u(P,d[P],m,g,y);U!==void 0&&(T+=`${A}${qe(P)}: ${U}`,A=_)}if(v>a){let $=v-a;T+=`${A}"...": "${et($)} not stringified"`,A=_}return A!==""&&(T=`
|
|
42
42
|
${y}${T}
|
|
43
|
-
${b}`),m.pop(),`{${T}}`}case"number":return isFinite(d)?String(d):e?e(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(
|
|
43
|
+
${b}`),m.pop(),`{${T}}`}case"number":return isFinite(d)?String(d):e?e(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return e?e(d):void 0}}function f(h,d,m){switch(typeof d){case"string":return qe(d);case"object":{if(d===null)return"null";if(typeof d.toJSON=="function"){if(d=d.toJSON(h),typeof d!="object")return f(h,d,m);if(d===null)return"null"}if(m.indexOf(d)!==-1)return n;let g="",y=d.length!==void 0;if(y&&Array.isArray(d)){if(d.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(d);let T=Math.min(d.length,a),A=0;for(;A<T-1;A++){let $=f(String(A),d[A],m);g+=$!==void 0?$:"null",g+=","}let E=f(String(A),d[A],m);if(g+=E!==void 0?E:"null",d.length-1>a){let $=d.length-a-1;g+=`,"... ${et($)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(d),w=b.length;if(w===0)return"{}";if(o<m.length+1)return'"[Object]"';let v="",_=Math.min(w,a);y&&os(d)&&(g+=Ca(d,",",a),b=b.slice(d.length),_-=d.length,v=","),s&&(b=is(b,i)),m.push(d);for(let T=0;T<_;T++){let A=b[T],E=f(A,d[A],m);E!==void 0&&(g+=`${v}${qe(A)}:${E}`,v=",")}if(w>a){let T=w-a;g+=`${v}"...":"${et(T)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(d)?String(d):e?e(d):"null";case"boolean":return d===!0?"true":"false";case"undefined":return;case"bigint":if(r)return String(d);default:return e?e(d):void 0}}function p(h,d,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),d!=null){if(typeof d=="function")return c("",{"":h},[],d,g,"");if(Array.isArray(d))return l("",h,[],_h(d),g,"")}if(g.length!==0)return u("",h,[],g,"")}return f("",h,[])}return p}});var ja=j((Gw,Ia)=>{"use strict";var ls=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Ra}=_n(),Th=Ra.info;function Ch(t,e){t=t||[],e=e||{dedupe:!1};let n=Object.create(Ra);n.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{n[f]=e.levels[f]});let r={write:s,add:a,remove:c,emit:i,flushSync:o,end:l,minLevel:0,lastId:0,streams:[],clone:u,[ls]:!0,streamLevels:n};return Array.isArray(t)?t.forEach(a,r):a.call(r,t),t=null,r;function s(f){let p,h=this.lastLevel,{streams:d}=this,m=0,g;for(let y=$h(d.length,e.dedupe);Ah(y,d.length,e.dedupe);y=Eh(y,e.dedupe))if(p=d[y],p.level<=h){if(m!==0&&m!==p.level)break;if(g=p.stream,g[ls]){let{lastTime:b,lastMsg:w,lastObj:v,lastLogger:_}=this;g.lastLevel=h,g.lastTime=b,g.lastMsg=w,g.lastObj=v,g.lastLogger=_}g.write(f),e.dedupe&&(m=p.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return r;let p=typeof f.write=="function"||f.stream,h=f.write?f:f.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:d,streamLevels:m}=this,g;typeof f.levelVal=="number"?g=f.levelVal:typeof f.level=="string"?g=m[f.level]:typeof f.level=="number"?g=f.level:g=Th;let y={stream:h,level:g,levelVal:void 0,id:++r.lastId};return d.unshift(y),d.sort(Oa),this.minLevel=d[0].level,r}function c(f){let{streams:p}=this,h=p.findIndex(d=>d.id===f);return h>=0&&(p.splice(h,1),p.sort(Oa),this.minLevel=p.length>0?p[0].level:-1),r}function l(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function u(f){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:f,stream:this.streams[h].stream};return{write:s,add:a,remove:c,minLevel:f,streams:p,clone:u,emit:i,flushSync:o,[ls]:!0}}}function Oa(t,e){return t.level-e.level}function $h(t,e){return e?t-1:0}function Eh(t,e){return e?t-1:t+1}function Ah(t,e,n){return n?t>=0:t<e}Ia.exports=Ch});var Ka=j((Jw,de)=>{"use strict";var Oh=require("node:os"),qa=Ar(),Rh=Or(),Ih=jr(),Ba=yo(),jh=Ta(),Ha=dt(),{configure:Ph}=Aa(),{assertDefaultLevelFound:Mh,mappings:Wa,genLsCache:Fh,genLevelComparison:Lh,assertLevelComparison:Dh}=Zr(),{DEFAULT_LEVELS:Va,SORTING_ORDER:Nh}=_n(),{createArgsNormalizer:Uh,asChindings:qh,buildSafeSonicBoom:Pa,buildFormatters:Bh,stringify:us,normalizeDestFileDescriptor:Ma,noop:Hh}=vn(),{version:Wh}=es(),{chindingsSym:Fa,redactFmtSym:Vh,serializersSym:La,timeSym:zh,timeSliceIndexSym:Kh,streamSym:Gh,stringifySym:Da,stringifySafeSym:fs,stringifiersSym:Na,setLevelSym:Jh,endSym:Yh,formatOptsSym:Xh,messageKeySym:Qh,errorKeySym:Zh,nestedKeySym:em,mixinSym:tm,levelCompSym:nm,useOnlyCustomLevelsSym:rm,formattersSym:Ua,hooksSym:sm,nestedKeyStrSym:im,mixinMergeStrategySym:om,msgPrefixSym:am}=Ha,{epochTime:za,nullTime:cm}=Ba,{pid:lm}=process,um=Oh.hostname(),fm=qa.err,dm={level:"info",levelComparison:Nh.ASC,levels:Va,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:lm,hostname:um},serializers:Object.assign(Object.create(null),{err:fm}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:za,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},pm=Uh(dm),hm=Object.assign(Object.create(null),qa);function ds(...t){let e={},{opts:n,stream:r}=pm(e,Rh(),...t);n.level&&typeof n.level=="string"&&Va[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:c,errorKey:l,nestedKey:u,base:f,name:p,level:h,customLevels:d,levelComparison:m,mixin:g,mixinMergeStrategy:y,useOnlyCustomLevels:b,formatters:w,hooks:v,depthLimit:_,edgeLimit:T,onChild:A,msgPrefix:E}=n,$=Ph({maximumDepth:_,maximumBreadth:T}),P=Bh(w.level,w.bindings,w.log),U=us.bind({[fs]:$}),N=s?Ih(s,U):{},H=s?{stringify:N[Vh]}:{stringify:U},X="}"+(i?`\r
|
|
44
44
|
`:`
|
|
45
|
-
`),z=
|
|
46
|
-
`)}function
|
|
47
|
-
`+x.border("\u2500\u2500")+n+x.border("\u2500".repeat(
|
|
48
|
-
`+x.accent("\u25C6")+" "+x.strong("Hablas")}function
|
|
49
|
-
`+x.muted("\u2504\u2504")+" "+x.secondary(t)}var
|
|
45
|
+
`),z=qh.bind(null,{[Fa]:"",[La]:o,[Na]:N,[Da]:us,[fs]:$,[Ua]:P}),re="";f!==null&&(p===void 0?re=z(f):re=z(Object.assign({},f,{name:p})));let I=a instanceof Function?a:a?za:cm,M=I().indexOf(":")+1;if(b&&!d)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(E&&typeof E!="string")throw Error(`Unknown msgPrefix type "${typeof E}" - expected "string"`);Mh(h,d,b);let De=Wa(d,b);typeof r.emit=="function"&&r.emit("message",{code:"PINO_CONFIG",config:{levels:De,messageKey:c,errorKey:l}}),Dh(m);let ti=Lh(m);return Object.assign(e,{levels:De,[nm]:ti,[rm]:b,[Gh]:r,[zh]:I,[Kh]:M,[Da]:us,[fs]:$,[Na]:N,[Yh]:X,[Xh]:H,[Qh]:c,[Zh]:l,[em]:u,[im]:u?`,${JSON.stringify(u)}:{`:"",[La]:o,[tm]:g,[om]:y,[Fa]:re,[Ua]:P,[sm]:v,silent:Hh,onChild:A,[am]:E}),Object.setPrototypeOf(e,jh()),Fh(e),e[Jh](h),e}de.exports=ds;de.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Ma(t.dest||process.stdout.fd),Pa(t)):Pa({dest:Ma(t),minLength:0});de.exports.transport=Kr();de.exports.multistream=ja();de.exports.levels=Wa();de.exports.stdSerializers=hm;de.exports.stdTimeFunctions=Object.assign({},Ba);de.exports.symbols=Ha;de.exports.version=Wh;de.exports.default=ds;de.exports.pino=ds});var tr=k(require("os")),sn=k(require("fs")),Rt=k(require("path"));function uu(){let t=[Rt.resolve(__dirname,"..","package.json"),Rt.resolve(__dirname,"..","..","package.json"),Rt.resolve(process.cwd(),"package.json")];for(let e of t)try{if(sn.existsSync(e)){let n=JSON.parse(sn.readFileSync(e,"utf-8"));if(n.version)return n.version}}catch{}return"0.0.0"}var nr=uu(),It=process.stdout.isTTY===!0,oi=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",ai=process.stdout.columns||100;It&&process.stdout.on("resize",()=>{ai=process.stdout.columns||100});var Ue=()=>Math.min(Math.max(ai-4,56),100);function K(t,e){return!It||oi?t:`\x1B[${e}m${t}\x1B[0m`}var x={strong:t=>K(t,"1;38;5;255"),muted:t=>K(t,"38;5;241"),dim:t=>K(t,"2;38;5;245"),border:t=>K(t,"38;5;237"),accent:t=>K(t,"38;5;147"),primary:t=>K(t,"38;5;253"),secondary:t=>K(t,"38;5;247"),info:t=>K(t,"38;5;110"),success:t=>K(t,"38;5;114"),warning:t=>K(t,"38;5;179"),error:t=>K(t,"38;5;167"),plan:t=>K(t,"38;5;144"),code:t=>K(t,"38;5;189"),codeLang:t=>K(t,"38;5;110"),linenum:t=>K(t,"38;5;239"),diffAdd:t=>K(t,"38;5;71"),diffDel:t=>K(t,"38;5;131"),link:t=>K(t,"4;38;5;110")};function _e(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function fu(t,e){let n=_e(t);return t+" ".repeat(Math.max(0,e-n.length))}function er(t,e=2,n){let r=(n??Ue())-e,s=t.split(/(?<=\s)|(?=\s)/).filter(Boolean),i=[],o="";for(let a of s){let c=_e(o),l=_e(a.trimStart());c.trimEnd().length+1+l.length>r&&c.trim()?(i.push(" ".repeat(e)+o.trimStart()),o=a.trimStart()):o+=a}return o.trim()&&i.push(" ".repeat(e)+o.trimStart()),i.length?i:[""]}function du(t,e="\u2500"){return x.border(e.repeat(Math.max(0,t)))}function ri(t,e,n){let r=_e(t),s=Math.max(0,Math.floor((n-2-r.length)/2)),i=Math.max(0,n-2-r.length-s);return x.border("\u2502")+" ".repeat(s)+e+" ".repeat(i)+x.border("\u2502")}function rn(t,e,n){let r=_e(t),s=_e(e),i=Math.max(1,n-4-r.length-s.length);return`${x.border("\u2502")} ${t}${" ".repeat(i)}${e} ${x.border("\u2502")}`}function si(t){return`${x.border("\u2502")}${" ".repeat(t-2)}${x.border("\u2502")}`}function ci(t,e){let n=Math.min(Ue(),76),r=e.replace(tr.homedir(),"~"),s=t.length>42?t.slice(0,40)+"\u2026":t,i=r.length>42?"\u2026"+r.slice(-40):r,o=x.border("\u256D"+"\u2500".repeat(n-2)+"\u256E"),a=x.border("\u2570"+"\u2500".repeat(n-2)+"\u256F"),c=x.border("\u251C"+"\u2500".repeat(n-2)+"\u2524"),l=x.border("\u255E"+"\u2550".repeat(n-2)+"\u2561");return["",o,si(n),ri(" HABLAS "," "+x.accent("\u25C6")+" "+x.strong("HABLAS")+" ",n),ri("engineering runtime",x.dim("engineering runtime"),n),si(n),l,rn(x.secondary("model "),x.accent(s),n),rn(x.secondary("workspace"),x.muted(i),n),rn(x.secondary("version "),x.muted("v"+nr),n),c,rn(x.dim("Type naturally \xB7 /help for commands \xB7 Ctrl+C to cancel"),"",n),a,""].join(`
|
|
46
|
+
`)}function li(t){let e=Ue(),n=" "+x.accent("\u25C6")+" "+x.strong("Turn")+" "+x.muted(String(t))+" ",r=" \u25C6 Turn "+t+" ",s=Math.max(0,e-r.length-2);return`
|
|
47
|
+
`+x.border("\u2500\u2500")+n+x.border("\u2500".repeat(s))}function Ge(){return`
|
|
48
|
+
`+x.accent("\u25C6")+" "+x.strong("Hablas")}function ui(t){return`
|
|
49
|
+
`+x.muted("\u2504\u2504")+" "+x.secondary(t)}var pu={read_file:"\u{1F4C4}",list_dir:"\u{1F4C2}",write_file:"\u270F\uFE0F",edit_file:"\u270F\uFE0F",patch_file:"\u270F\uFE0F",search_and_replace:"\u{1F504}",append_to_file:"\u2795",move_file:"\u{1F69A}",delete_file:"\u{1F5D1}\uFE0F",create_dir:"\u{1F4C1}",search_codebase:"\u{1F50D}",run_command:"\u26A1",execute_code:"\u25B6\uFE0F",web_search:"\u{1F310}",scrape_url:"\u{1F578}\uFE0F",extract_links:"\u{1F517}",download_asset:"\u2B07\uFE0F",detect_bugs:"\u{1F41B}",read_pdf:"\u{1F4CB}",pdf_metadata:"\u{1F4CB}",search_image_candidates:"\u{1F5BC}\uFE0F",inspect_image:"\u{1F50E}",remember:"\u{1F4BE}",recall:"\u{1F9E0}",search_memory:"\u{1F50D}",forget:"\u{1F5D1}\uFE0F",git_status:"\u{1F33F}",git_diff:"\u{1F4DD}",git_log:"\u{1F4DC}",git_branch:"\u{1F33F}"};function fi(t,e){let n=pu[t]??"\xB7",r=t.replace(/_/g," "),s=Math.min(Ue()-4,76),i=n+" "+x.secondary(r),o=e?x.dim(e.slice(0,40)):"",a=_e(i)+(o?" "+e.slice(0,40):""),c=Math.max(0,s-2-a.length),l=" "+x.border("\u256D"+"\u2500".repeat(s)+"\u256E"),u=" "+x.border("\u2502")+" "+i+(o?" "+o:"")+" ".repeat(c)+" "+x.border("\u2502");return`
|
|
50
50
|
`+l+`
|
|
51
|
-
`+u}function
|
|
52
|
-
`+f}function
|
|
53
|
-
`).filter(
|
|
54
|
-
`),n=[],
|
|
51
|
+
`+u}function di(t,e,n){let r=Math.min(Ue()-4,76),s=n>=1e3?(n/1e3).toFixed(1)+"s":n+"ms",i=t?x.success("\u2713"):x.error("\u2717"),o=hu(e),a=i+" "+x.dim(s)+(o?" "+o:""),c=_e(a),l=Math.max(0,r-2-c.length),u=" "+x.border("\u2502")+" "+a+" ".repeat(l)+" "+x.border("\u2502"),f=" "+x.border("\u2570"+"\u2500".repeat(r)+"\u256F");return u+`
|
|
52
|
+
`+f}function hu(t){if(!t?.trim())return"";let e=t.split(`
|
|
53
|
+
`).filter(r=>r.trim());if(e.length>6)return x.dim(e.length+" lines");let n=e.join(" ").replace(/\s+/g," ").trim();return n.length<=55?x.dim(n):x.dim(n.slice(0,52)+"\u2026")}function Ne(t){return t.replace(/\*\*([^*\n]+)\*\*/g,(e,n)=>x.strong(n)).replace(/__([^_\n]+)__/g,(e,n)=>x.strong(n)).replace(/\*([^*\n]+)\*/g,(e,n)=>x.accent(n)).replace(/_([^_\n]+)_/g,(e,n)=>x.accent(n)).replace(/`([^`\n]+)`/g,(e,n)=>x.code(n)).replace(/~~([^~\n]+)~~/g,(e,n)=>x.muted(n)).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,(e,n,r)=>x.link(n)+x.muted(" ("+r+")"))}function mu(t){let e=t.filter(o=>!/^\s*\|?\s*[-:]+[-:\s|]*\s*\|?\s*$/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split("|").map(a=>a.trim()));if(!e.length)return[];let n=Math.max(...e.map(o=>o.length)),r=Array(n).fill(4);for(let o of e)for(let a=0;a<o.length;a++)r[a]=Math.max(r[a],_e(o[a]).length+2);let s=x.border(" \u251C"+r.map(o=>"\u2500".repeat(o+2)).join("\u253C")+"\u2524"),i=[];return e.forEach((o,a)=>{let c=Array(n).fill("").map((u,f)=>{let p=Ne(o[f]??"");return" "+fu(p,r[f])+" "}),l=x.border(" \u2502")+c.join(x.border("\u2502"))+x.border("\u2502");i.push(l),a===0&&i.push(s)}),i}function gu(t,e){let n=Math.max(28,Ue()-8),r=String(t.length).length,s=[],i=e?" "+x.codeLang(e):"";s.push(" "+x.border("\u256D"+"\u2500".repeat(n))+i);for(let o=0;o<t.length;o++){let a=x.linenum(String(o+1).padStart(r)),c=yu(t[o],e);s.push(" "+x.border("\u2502")+" "+a+" "+x.border("\u2502")+" "+c)}return s.push(" "+x.border("\u2570"+"\u2500".repeat(n))),s}function yu(t,e){if(!It||oi)return t;let n=e.toLowerCase();return["sh","bash","zsh","shell"].includes(n)?/^\s*#/.test(t)?x.muted(t):t.replace(/^(\s*)(export|cd|echo|npm|npx|git|node|python|pip|mkdir|rm|cp|mv|ls|cat|grep|sed|awk)(\s)/,(r,s,i,o)=>s+x.accent(i)+o).replace(/(['"`])([^'"` ]*)\1/g,(r,s,i)=>x.warning(s+i+s)):["ts","tsx","js","jsx","typescript","javascript"].includes(n)?/^\s*\/\//.test(t)||/^\s*\/\*/.test(t)?x.muted(t):t.replace(/\b(const|let|var|function|async|await|return|import|export|from|class|extends|interface|type|if|else|for|while|try|catch|throw|new|void|null|undefined|true|false)\b/g,r=>x.accent(r)).replace(/(['"`])([^'"` ]*)\1/g,(r,s,i)=>x.warning(s+i+s)):["py","python"].includes(n)?/^\s*#/.test(t)?x.muted(t):t.replace(/\b(def|class|import|from|return|if|elif|else|for|while|try|except|with|as|pass|in|not|and|or|True|False|None|lambda|yield|async|await)\b/g,r=>x.accent(r)).replace(/(['"`]{1,3})([^'"` ]*?)\1/g,r=>x.warning(r)):["json","jsonc"].includes(n)?t.replace(/"([^"]+)"(\s*:)/g,(r,s,i)=>x.info('"'+s+'"')+x.border(i)).replace(/:\s*"([^"]+)"/g,(r,s)=>": "+x.warning('"'+s+'"')).replace(/:\s*(true|false|null)/g,(r,s)=>": "+x.accent(s)).replace(/:\s*(-?\d+(\.\d+)?)/g,(r,s)=>": "+x.success(s)):x.code(t)}function jt(t){if(!t?.trim()||(t=t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<\/?think(?:ing)?>/gi,"").trim(),!t))return"";let e=t.split(`
|
|
54
|
+
`),n=[],r=!1,s="",i=[],o=[],a=()=>{i.length&&(n.push(...gu(i,s)),i=[],s="")},c=()=>{o.length&&(n.push(...mu(o)),o=[])},l=u=>/^\s*\|.+\|/.test(u)||/^\s*[-:]+[-:\s|]+$/.test(u);for(let u of e){let f=u.trimStart();if(f.startsWith("```")){c(),r?(a(),r=!1,s=""):(r=!0,s=f.slice(3).trim());continue}if(r){i.push(u);continue}if(l(u)){o.push(u);continue}if(c(),!u.trim()){n.push("");continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(f)){n.push(" "+du(Math.min(Ue()-4,56)));continue}let p=/^#\s+(.+)/.exec(f);if(p){n.push(""),n.push(" "+x.strong(Ne(p[1]))),n.push(" "+x.border("\u2500".repeat(Math.min(_e(p[1]).length+2,Ue()-4))));continue}let h=/^##\s+(.+)/.exec(f);if(h){n.push(""),n.push(" "+x.accent("\u25C6")+" "+x.strong(Ne(h[1])));continue}let d=/^###\s+(.+)/.exec(f);if(d){n.push(""),n.push(" "+x.secondary("\u25C7")+" "+x.primary(Ne(d[1])));continue}let m=/^(\s*)([-*•+])\s+(.+)/.exec(u);if(m){let b=m[1].length,w=Ne(m[3]),v=b>0?x.muted("\u25E6"):x.accent("\xB7"),_=er(w,b+4);n.push(" ".repeat(b+2)+v+" "+(_[0]?.trimStart()??""));for(let T=1;T<_.length;T++)n.push(" ".repeat(b+4)+_[T].trimStart());continue}let g=/^(\s*)(\d+)\.\s+(.+)/.exec(u);if(g){let b=g[1].length,w=x.accent(g[2]+"."),v=Ne(g[3]),_=er(v,b+5);n.push(" ".repeat(b+2)+w+" "+(_[0]?.trimStart()??""));for(let T=1;T<_.length;T++)n.push(" ".repeat(b+5)+_[T].trimStart());continue}let y=/^>\s*(.*)/.exec(f);if(y){n.push(" "+x.border("\u258C")+" "+x.secondary(Ne(y[1])));continue}if(/^\+(?!\+\+)/.test(f)){n.push(" "+x.diffAdd(u));continue}if(/^-(?!--)/.test(f)){n.push(" "+x.diffDel(u));continue}n.push(...er(Ne(u),2))}return c(),r&&a(),`
|
|
55
55
|
`+n.join(`
|
|
56
56
|
`)+`
|
|
57
|
-
`}function
|
|
58
|
-
`)}function
|
|
59
|
-
`)}function
|
|
60
|
-
`)}function
|
|
61
|
-
`+x.strong("hablas")+" "+x.accent("v"+
|
|
57
|
+
`}function pi(){let t=(e,n)=>" "+x.accent(e.padEnd(20))+" "+x.muted(n);return[""," "+x.strong("Commands"),"",t("/help","show this reference"),t("/status","runtime status snapshot"),t("/model [name]","show or switch active model"),t("/models [q] [n]","browse & search available models"),t("/provider","inspect or switch LLM provider"),t("/history [n]","show recent turns"),t("/clear","reset session"),t("/workspace","inspect project structure"),t("/memory","show project memory"),t("/diff [file]","show git diff"),t("/git [status|log]","git status or log"),t("/doctor","run diagnostics"),t("/version","show version"),t("/about","product identity"),t("/exit","quit"),""," "+x.secondary("Tips")," "+x.muted("Ctrl+C cancels current work. Ctrl+C twice exits.")," "+x.muted("Hablas reads Arabic, English, and mixed input."),""].join(`
|
|
58
|
+
`)}function hi(t){let e=t.workingDir.replace(tr.homedir(),"~"),n=t.connected?x.success("online"):x.warning("offline"),r=[["model",x.accent(t.model)],["provider",x.primary(t.provider)],["connection",n],["workspace",x.muted(e)],["messages",x.muted(String(t.messageCount))],["tokens (est)",x.muted(t.totalTokens.toLocaleString())]];return[""," "+x.strong("Runtime Status"),"",...r.map(([s,i])=>" "+x.secondary(s.padEnd(14))+" "+i),""].join(`
|
|
59
|
+
`)}function mi(){return[""," "+x.strong("Hablas")+" "+x.dim("v"+nr)," "+x.muted("Single-agent engineering runtime for the terminal."),""," "+x.secondary("Built by")+" "+x.primary("Abdulmoin Hablas")," "+x.link("https://portfolio-monopoly63s-projects.vercel.app/"),""," "+x.secondary("Philosophy")," "+x.muted("One agent. One conversation. Real execution."),""].join(`
|
|
60
|
+
`)}function gi(){return`
|
|
61
|
+
`+x.strong("hablas")+" "+x.accent("v"+nr)+`
|
|
62
62
|
`}function Ae(t){return`
|
|
63
63
|
`+x.error("\u2717")+" "+x.primary(t)+`
|
|
64
|
-
`}function ie(t){return" "+x.warning("\u26A0")+" "+x.secondary(t)}function ke(t){return" "+x.success("\u2713")+" "+x.primary(t)}function D(t){return" "+x.muted("\xB7")+" "+x.secondary(t)}var
|
|
64
|
+
`}function ie(t){return" "+x.warning("\u26A0")+" "+x.secondary(t)}function ke(t){return" "+x.success("\u2713")+" "+x.primary(t)}function D(t){return" "+x.muted("\xB7")+" "+x.secondary(t)}var ii=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ke=class{frame=0;timer;active=!1;label;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!It||this.active||(this.active=!0,this.frame=0,this.timer=setInterval(()=>{let e=K(ii[this.frame++%ii.length],"38;5;147");process.stdout.write("\r "+e+" "+x.muted(this.label)+"\x1B[K")},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=void 0),It&&process.stdout.write("\r\x1B[K"))}};var rr=null;function wi(t){rr=t}function bi(){try{rr?.stop()}catch{}rr=null}function yi(t,e){bi(),process.stdout.write(`
|
|
65
65
|
`);let n=e instanceof Error?e.message:String(e);console.error(Ae(`[${t}] ${n}`)),process.env.HABLAS_DEBUG&&e instanceof Error&&e.stack&&console.error(`
|
|
66
66
|
`+e.stack.split(`
|
|
67
67
|
`).slice(1,5).join(`
|
|
68
|
-
`))}function
|
|
69
|
-
`),console.log(ie("Received SIGTERM \u2014 shutting down gracefully.")),process.exit(0)})}var
|
|
70
|
-
`);o=l.pop()||"";for(let u of l)if(u.trim())try{let f=JSON.parse(u);f.message?.content&&(yield f.message.content)}catch{}}}};var
|
|
71
|
-
`);u=g.pop()||"";for(let y of g){let b=y.trim();if(!(!b||b==="data: [DONE]")&&b.startsWith("data: "))try{let v=JSON.parse(b.slice(6)).choices?.[0]?.delta;if(!v)continue;if(v.content&&(f+=v.content,
|
|
72
|
-
`);a=u.pop()||"";for(let f of u){let p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let d=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;d&&(yield d)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function mt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ue.apiUrl};return new Ut(e)}return t.provider==="custom"&&t.apiUrl?new Ut(t):new En(t)}function nt(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var B=k(require("fs/promises")),
|
|
73
|
-
`));var e=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var
|
|
74
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
75
|
-
`);if(w.lines=v,w.added||w.removed){var _;if(!u){var T=a[b-1];u=h,f=d,T&&(p=o.context>0?c(T.lines.slice(-o.context)):[],u-=p.length,f-=p.length)}(_=p).push.apply(_,
|
|
76
|
-
`);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var n=0;n<t.hunks.length;n++){var
|
|
68
|
+
`))}function xi(){process.on("uncaughtException",t=>{yi("Uncaught Error",t),process.exit(1)}),process.on("unhandledRejection",t=>{yi("Unhandled Promise",t),process.exit(1)}),process.on("SIGTERM",()=>{bi(),process.stdout.write(`
|
|
69
|
+
`),console.log(ie("Received SIGTERM \u2014 shutting down gracefully.")),process.exit(0)})}var ji=k(Ii(),1),{program:iw,createCommand:ow,createArgument:aw,createOption:cw,CommanderError:lw,InvalidArgumentError:uw,InvalidOptionArgumentError:fw,Command:Pi,Argument:dw,Option:pw,Help:hw}=ji.default;var we=k(require("fs")),Je=k(require("path")),Mi=k(require("os"));var lt={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}},ue={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 ut=Je.join(Mi.homedir(),".hablas"),br=Je.join(ut,"config.json");function ft(t={}){let e={};if(we.existsSync(br))try{e=JSON.parse(we.readFileSync(br,"utf-8"))}catch{}let n={...lt,...e,tools:{...lt.tools,...e.tools||{},runCommand:{...lt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...lt.workspace,...e.workspace||{}},vision:{...lt.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(n.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(n.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(n.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(n.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(n.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(n.vision.enabled=!1),process.env.HABLAS_PROVIDER){let r=process.env.HABLAS_PROVIDER;(r==="ollama"||r==="custom"||r==="nvidia")&&(n.provider=r)}if(t.model&&(n.model=t.model),t.host&&(n.ollamaHost=t.host),t.project&&(n.workingDirectory=Je.resolve(t.project)),t.provider){let r=t.provider;(r==="ollama"||r==="custom"||r==="nvidia")&&(n.provider=r)}return t.apiUrl&&(n.apiUrl=t.apiUrl),t.apiKey&&(n.apiKey=t.apiKey),n.apiUrl&&n.provider==="ollama"&&(n.provider="custom"),n}function Ye(t){we.existsSync(ut)||we.mkdirSync(ut,{recursive:!0}),we.writeFileSync(br,JSON.stringify(t,null,2),"utf-8")}function Fi(){let t=[ut,Je.join(ut,"logs"),Je.join(ut,"backup")];for(let e of t)we.existsSync(e)||we.mkdirSync(e,{recursive:!0})}var ps=k(Ka()),hs=k(require("path")),Ga=k(require("os")),Cn=k(require("fs"));function ms(t){let e=hs.join(Ga.homedir(),".hablas","logs");Cn.existsSync(e)||Cn.mkdirSync(e,{recursive:!0});let n=hs.join(e,`session-${Date.now()}.log`);return(0,ps.default)({level:"info"},ps.default.destination({dest:n,sync:!1}))}var $n=k(require("fs")),Nt=k(require("path"));function Ja(){let t=[Nt.resolve(__dirname,"..","package.json"),Nt.resolve(__dirname,"..","..","package.json"),Nt.resolve(process.cwd(),"package.json"),Nt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if($n.existsSync(e)){let n=JSON.parse($n.readFileSync(e,"utf-8"));if(n.version)return n.version}}catch{}return"0.0.0"}var Hl=k(require("fs")),Wl=k(require("path"));var En=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(r=>r.name):[]}catch{return[]}}async chatWithTools(e,n,r){let s={model:this.model,messages:e,stream:!1};n.length>0&&(s.tools=n);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};r&&(i.signal=r);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${c}`)}return await o.json()}async*streamChat(e,n){let r=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:n});if(!r.ok)throw new Error(`Ollama error: ${r.status} ${r.statusText}`);let s=r.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:c}=await s.read();if(a)break;o+=i.decode(c,{stream:!0});let l=o.split(`
|
|
70
|
+
`);o=l.pop()||"";for(let u of l)if(u.trim())try{let f=JSON.parse(u);f.message?.content&&(yield f.message.content)}catch{}}}};var mm={400:{message:"Bad request \u2014 the model may not support this feature.",retryable:!1,fatal:!1},401:{message:"Authentication failed \u2014 check your API key with /provider.",retryable:!1,fatal:!0},402:{message:"Payment required \u2014 your API account needs credits.",retryable:!1,fatal:!0},403:{message:"Access forbidden \u2014 your API key lacks permission for this model.",retryable:!1,fatal:!0},404:{message:"Model not found \u2014 run /models to see available models.",retryable:!1,fatal:!1},413:{message:"Request too large \u2014 the conversation is too long. Starting fresh context.",retryable:!1,fatal:!1},422:{message:"Invalid request format \u2014 the provider rejected this message structure.",retryable:!1,fatal:!1},429:{message:"Rate limit reached \u2014 waiting before retry.",retryable:!0,fatal:!1},500:{message:"Provider server error \u2014 retrying...",retryable:!0,fatal:!1},502:{message:"Provider gateway error \u2014 retrying...",retryable:!0,fatal:!1},503:{message:"Provider temporarily unavailable \u2014 retrying...",retryable:!0,fatal:!1},529:{message:"Provider overloaded \u2014 retrying with backoff...",retryable:!0,fatal:!1}},gs=[{test:t=>/insufficient_quota|credit|billing|payment|out of credits/i.test(t),message:"API credits exhausted \u2014 top up your account or switch provider with /provider.",retryable:!1,fatal:!0},{test:t=>/rate.?limit|too many requests|rpm|tpm/i.test(t),message:"Rate limit reached \u2014 retrying after cooldown.",retryable:!0,fatal:!1},{test:t=>/context.?length|context_length|token.*limit|maximum.*token/i.test(t),message:"Context window full \u2014 the conversation is too long. Some history will be trimmed.",retryable:!1,fatal:!1},{test:t=>/model.*not.*found|does not exist|invalid model/i.test(t),message:"Model not found \u2014 run /models to list available models.",retryable:!1,fatal:!1},{test:t=>/invalid.?api.?key|unauthorized|authentication/i.test(t),message:"Invalid API key \u2014 reconfigure with /provider.",retryable:!1,fatal:!0},{test:t=>/overload|capacity|busy/i.test(t),message:"Provider is overloaded \u2014 retrying...",retryable:!0,fatal:!1}],gm=[{test:t=>/ECONNREFUSED/i.test(t),message:"Connection refused \u2014 is the API server running?",retryable:!0},{test:t=>/ECONNRESET/i.test(t),message:"Connection reset \u2014 network instability detected, retrying...",retryable:!0},{test:t=>/ENOTFOUND/i.test(t),message:"DNS lookup failed \u2014 check your internet connection.",retryable:!1},{test:t=>/ETIMEDOUT/i.test(t),message:"Connection timed out \u2014 network is slow or blocked.",retryable:!0},{test:t=>/fetch failed/i.test(t),message:"Network request failed \u2014 check your connection.",retryable:!0},{test:t=>/AbortError|aborted/i.test(t),message:"Request timed out \u2014 provider took too long to respond.",retryable:!0}];function pe(t,e){let n=t instanceof Error?t.message:String(t),r=/API error: (\d{3})/.exec(n);if(r){let i=parseInt(r[1],10),o=mm[i];if(e){for(let a of gs)if(a.test(e))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i}}for(let a of gs)if(a.test(n))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i};return o?{...o,status:i}:{message:`Server error (${i}) \u2014 retrying...`,retryable:i>=500,fatal:!1,status:i}}for(let i of gm)if(i.test(n))return{message:i.message,retryable:i.retryable,fatal:!1};let s=n+(e||"");for(let i of gs)if(i.test(s))return{message:i.message,retryable:i.retryable,fatal:i.fatal};return{message:n.length>120?n.slice(0,120)+"...":n,retryable:!1,fatal:!1}}var ys=12e4,ym=6e4,An=3,Ya=1e3,wm=20;function ws(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let n=e.tool_calls.filter(r=>r?.function?.name);if(n.length>0)return{role:"assistant",content:e.content||null,tool_calls:n.map((r,s)=>({id:`call_${s}`,type:"function",function:{name:r.function?.name||"",arguments:JSON.stringify(r.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Xa(t){return t.map(e=>({type:"function",function:e.function}))}function Qa(t){return t.filter(e=>e?.function?.name).map(e=>{let n={};try{n=JSON.parse(e.function?.arguments||"{}")}catch{n={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:n}}})}function Za(t){return new Promise(e=>setTimeout(e,t))}function ec(t,e){return t?.name==="AbortError"?!1:e?pe(new Error(`API error: ${e}`)).retryable:pe(t).retryable}function tc(t,e){return pe(t,e).message}function bm(t,e){return pe(t,e).fatal}var Ut=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],n=!0,r,s=0;for(;n&&s<wm;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;r&&o.set("after",r),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let c=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(ym)});if(!c.ok)break;let l=await c.json();if(Array.isArray(l))e.push(...l.map(u=>u.id||u.name||u).filter(Boolean)),n=!1;else if(l.data&&Array.isArray(l.data)){let u=l.data.map(f=>f.id||f.name).filter(Boolean);e.push(...u),l.has_more&&u.length>0?(r=u[u.length-1],s++):n=!1}else l.models&&Array.isArray(l.models)&&e.push(...l.models.map(u=>u.name||u.id).filter(Boolean)),n=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async*streamChatWithTools(e,n,r,s){let i=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",o={model:this.model,messages:ws(e),stream:!0};n.length>0&&(o.tools=Xa(n),o.tool_choice="auto");let a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(o),signal:s||AbortSignal.timeout(ys)})}catch{return await this.chatWithTools(e,n,s)}if(!a.ok){let d=await a.text().catch(()=>"");throw new Error(`API error: ${a.status} ${a.statusText} \u2014 ${d}`)}let c=a.body?.getReader();if(!c)return await this.chatWithTools(e,n,s);let l=new TextDecoder,u="",f="",p=[];for(;;){let{done:d,value:m}=await c.read();if(d)break;u+=l.decode(m,{stream:!0});let g=u.split(`
|
|
71
|
+
`);u=g.pop()||"";for(let y of g){let b=y.trim();if(!(!b||b==="data: [DONE]")&&b.startsWith("data: "))try{let v=JSON.parse(b.slice(6)).choices?.[0]?.delta;if(!v)continue;if(v.content&&(f+=v.content,r?.(v.content)),v.tool_calls)for(let _ of v.tool_calls){let T=_.index??0;p[T]||(p[T]={id:_.id||"",type:"function",index:T,function:{name:_.function?.name||"",arguments:""}}),_.function?.name&&(p[T].function.name=_.function.name),_.function?.arguments&&(p[T].function.arguments+=_.function.arguments)}}catch{}}}let h=p.length>0?Qa(p):void 0;return{message:{role:"assistant",content:f,tool_calls:h},done:!0,done_reason:h?"tool_calls":"stop"}}async chatWithTools(e,n,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:ws(e)};n.length>0&&(i.tools=Xa(n),i.tool_choice="auto");let o=null;for(let a=0;a<=An;a++)try{let c=new AbortController,l=setTimeout(()=>c.abort(),ys),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:r||c.signal};try{let f=await fetch(s,u);if(clearTimeout(l),!f.ok){let m=await f.text().catch(()=>"");if(bm(null,m)||!ec(null,f.status))throw new Error(tc(new Error(`API error: ${f.status}`),m));if(o=new Error(tc(new Error(`API error: ${f.status}`),m)),a<An){let g=Ya*Math.pow(2,a);await Za(g);continue}throw o}let h=(await f.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let d=h.message.tool_calls?Qa(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:d},done:!0,done_reason:h.finish_reason}}catch(f){if(clearTimeout(l),f.name==="AbortError"&&r?.aborted)throw f;if(ec(f)&&(o=f,a<An)){let p=Ya*Math.pow(2,a);await Za(p);continue}throw f}}catch(c){if(c.name==="AbortError")throw c;if(o=c,a>=An)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,n){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:ws(e),stream:!0}),signal:n||AbortSignal.timeout(ys)});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:c,value:l}=await i.read();if(c)break;a+=o.decode(l,{stream:!0});let u=a.split(`
|
|
72
|
+
`);a=u.pop()||"";for(let f of u){let p=f.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let d=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;d&&(yield d)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function mt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ue.apiUrl};return new Ut(e)}return t.provider==="custom"&&t.apiUrl?new Ut(t):new En(t)}function nt(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var B=k(require("fs/promises")),Cs=k(require("fs")),Be=k(require("path"));function Ie(){}Ie.prototype={diff:function(e,n){var r,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(v){return i?(setTimeout(function(){i(void 0,v)},0),!0):v}e=this.castInput(e),n=this.castInput(n),e=this.removeEmpty(this.tokenize(e)),n=this.removeEmpty(this.tokenize(n));var c=n.length,l=e.length,u=1,f=c+l;s.maxEditLength&&(f=Math.min(f,s.maxEditLength));var p=(r=s.timeout)!==null&&r!==void 0?r:1/0,h=Date.now()+p,d=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(d[0],n,e,0);if(d[0].oldPos+1>=l&&m+1>=c)return a([{value:this.join(n),count:n.length}]);var g=-1/0,y=1/0;function b(){for(var v=Math.max(g,-u);v<=Math.min(y,u);v+=2){var _=void 0,T=d[v-1],A=d[v+1];T&&(d[v-1]=void 0);var E=!1;if(A){var $=A.oldPos-v;E=A&&0<=$&&$<c}var P=T&&T.oldPos+1<l;if(!E&&!P){d[v]=void 0;continue}if(!P||E&&T.oldPos+1<A.oldPos?_=o.addToPath(A,!0,void 0,0):_=o.addToPath(T,void 0,!0,1),m=o.extractCommon(_,n,e,v),_.oldPos+1>=l&&m+1>=c)return a(xm(o,_.lastComponent,n,e,o.useLongestToken));d[v]=_,_.oldPos+1>=l&&(y=Math.min(y,v-1)),m+1>=c&&(g=Math.max(g,v+1))}u++}if(i)(function v(){setTimeout(function(){if(u>f||Date.now()>h)return i();b()||v()},0)})();else for(;u<=f&&Date.now()<=h;){var w=b();if(w)return w}},addToPath:function(e,n,r,s){var i=e.lastComponent;return i&&i.added===n&&i.removed===r?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:n,removed:r,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:n,removed:r,previousComponent:i}}},extractCommon:function(e,n,r,s){for(var i=n.length,o=r.length,a=e.oldPos,c=a-s,l=0;c+1<i&&a+1<o&&this.equals(n[c+1],r[a+1]);)c++,a++,l++;return l&&(e.lastComponent={count:l,previousComponent:e.lastComponent}),e.oldPos=a,c},equals:function(e,n){return this.options.comparator?this.options.comparator(e,n):e===n||this.options.ignoreCase&&e.toLowerCase()===n.toLowerCase()},removeEmpty:function(e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function xm(t,e,n,r,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,c=i.length,l=0,u=0;a<c;a++){var f=i[a];if(f.removed){if(f.value=t.join(r.slice(u,u+f.count)),u+=f.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!f.added&&s){var p=n.slice(l,l+f.count);p=p.map(function(m,g){var y=r[u+g];return y.length>m.length?y:m}),f.value=t.join(p)}else f.value=t.join(n.slice(l,l+f.count));l+=f.count,f.added||(u+=f.count)}}var d=i[c-1];return c>1&&typeof d.value=="string"&&(d.added||d.removed)&&t.equals("",d.value)&&(i[c-2].value+=d.value,i.pop()),i}var db=new Ie;var nc=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,rc=/\S/,sc=new Ie;sc.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!rc.test(t)&&!rc.test(e)};sc.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<e.length-1;n++)!e[n+1]&&e[n+2]&&nc.test(e[n])&&nc.test(e[n+2])&&(e[n]+=e[n+2],e.splice(n+1,2),n--);return e};var _s=new Ie;_s.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
73
|
+
`));var e=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var s=n[r];r%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function Sm(t,e,n){return _s.diff(t,e,n)}var vm=new Ie;vm.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var _m=new Ie;_m.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function On(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?On=function(e){return typeof e}:On=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},On(t)}function bs(t){return km(t)||Tm(t)||Cm(t)||$m()}function km(t){if(Array.isArray(t))return xs(t)}function Tm(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Cm(t,e){if(t){if(typeof t=="string")return xs(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if(n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set")return Array.from(t);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return xs(t,e)}}function xs(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function $m(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
74
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Em=Object.prototype.toString,qt=new Ie;qt.useLongestToken=!0;qt.tokenize=_s.tokenize;qt.castInput=function(t){var e=this.options,n=e.undefinedReplacement,r=e.stringifyReplacer,s=r===void 0?function(i,o){return typeof o>"u"?n:o}:r;return typeof t=="string"?t:JSON.stringify(Ss(t,null,null,s),s," ")};qt.equals=function(t,e){return Ie.prototype.equals.call(qt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Ss(t,e,n,r,s){e=e||[],n=n||[],r&&(t=r(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return n[i];var o;if(Em.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),n.push(o),i=0;i<t.length;i+=1)o[i]=Ss(t[i],e,n,r,s);return e.pop(),n.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),On(t)==="object"&&t!==null){e.push(t),o={},n.push(o);var a=[],c;for(c in t)t.hasOwnProperty(c)&&a.push(c);for(a.sort(),i=0;i<a.length;i+=1)c=a[i],o[c]=Ss(t[c],e,n,r,c);e.pop(),n.pop()}else o=t;return o}var vs=new Ie;vs.tokenize=function(t){return t.slice()};vs.join=vs.removeEmpty=function(t){return t};function Am(t,e,n,r,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Sm(n,r,o);if(!a)return;a.push({value:"",lines:[]});function c(y){return y.map(function(b){return" "+b})}for(var l=[],u=0,f=0,p=[],h=1,d=1,m=function(b){var w=a[b],v=w.lines||w.value.replace(/\n$/,"").split(`
|
|
75
|
+
`);if(w.lines=v,w.added||w.removed){var _;if(!u){var T=a[b-1];u=h,f=d,T&&(p=o.context>0?c(T.lines.slice(-o.context)):[],u-=p.length,f-=p.length)}(_=p).push.apply(_,bs(v.map(function(X){return(w.added?"+":"-")+X}))),w.added?d+=v.length:h+=v.length}else{if(u)if(v.length<=o.context*2&&b<a.length-2){var A;(A=p).push.apply(A,bs(c(v)))}else{var E,$=Math.min(v.length,o.context);(E=p).push.apply(E,bs(c(v.slice(0,$))));var P={oldStart:u,oldLines:h-u+$,newStart:f,newLines:d-f+$,lines:p};if(b>=a.length-2&&v.length<=o.context){var U=/\n$/.test(n),N=/\n$/.test(r),H=v.length==0&&p.length>P.oldLines;!U&&H&&n.length>0&&p.splice(P.oldLines,0,"\"),(!U&&!H||!N)&&p.push("\")}l.push(P),u=0,f=0,p=[]}h+=v.length,d+=v.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:l}}function ic(t){if(Array.isArray(t))return t.map(ic).join(`
|
|
76
|
+
`);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var n=0;n<t.hunks.length;n++){var r=t.hunks[n];r.oldLines===0&&(r.oldStart-=1),r.newLines===0&&(r.newStart-=1),e.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@"),e.push.apply(e,r.lines)}return e.join(`
|
|
77
77
|
`)+`
|
|
78
|
-
`}function
|
|
78
|
+
`}function Om(t,e,n,r,s,i,o){return ic(Am(t,e,n,r,s,i,o))}function oc(t,e,n,r,s,i){return Om(t,t,e,n,r,s,i)}function Bt(t,e,n){return oc(t,e,n,"original","modified")}var Ce=k(require("fs/promises")),ks=k(require("fs")),gt=k(require("path")),cc=k(require("os")),Ht=gt.join(cc.homedir(),".hablas","backup"),ac=10;async function rt(t){try{if(!ks.existsSync(t))return;ks.existsSync(Ht)||await Ce.mkdir(Ht,{recursive:!0});let e=await Ce.readFile(t,"utf-8"),n=gt.basename(t),r=Date.now(),s=`${n}.${r}.bak`,i=gt.join(Ht,s);await Ce.writeFile(i,e,"utf-8");let a=(await Ce.readdir(Ht)).filter(c=>c.startsWith(`${n}.`)&&c.endsWith(".bak")).sort().reverse();if(a.length>ac)for(let c of a.slice(ac))await Ce.unlink(gt.join(Ht,c))}catch{}}function lc(t){let e=h=>Be.resolve(t,h);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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let d=e(h.path),g=(await B.readFile(d,"utf-8")).split(`
|
|
79
79
|
`),y=g.length,b=h.start_line?Math.max(1,h.start_line):1,w=h.end_line?Math.min(y,h.end_line):y,v=g.slice(b-1,w),_=String(w).length,T=v.map(($,P)=>`${String(b+P).padStart(_," ")} | ${$}`),A=`[${h.path} \u2014 lines ${b}-${w} of ${y}]`,E=w<y?`
|
|
80
80
|
... [Partial read. Total lines: ${y}.]`:"";return{success:!0,output:`${A}
|
|
81
81
|
${T.join(`
|
|
82
|
-
`)}${E}`}}catch(d){return{success:!1,output:"",error:`[read_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let d=e(h.path);return
|
|
82
|
+
`)}${E}`}}catch(d){return{success:!1,output:"",error:`[read_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let d=e(h.path);return Cs.existsSync(d)&&await rt(d),await B.mkdir(Be.dirname(d),{recursive:!0}),await B.writeFile(d,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(d){return{success:!1,output:"",error:`[write_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!h.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let d=e(h.path),m=await B.readFile(d,"utf-8"),g=h.old_content,y=h.new_content,b=Ts(m,g),w=g;if(b===0){let E=N=>N.replace(/\r\n/g,`
|
|
83
83
|
`).split(`
|
|
84
84
|
`).map(H=>H.trimEnd()).join(`
|
|
85
|
-
`),$=E(m),P=E(g),U=
|
|
85
|
+
`),$=E(m),P=E(g),U=Ts($,P);U===1&&(w=P,b=U)}if(b===0)return{success:!1,output:"",error:`[edit_file]: old_content not found in file. Check for whitespace/newline differences. File preview: "${m.slice(0,200).replace(/\n/g,"\u21B5")}\u2026"`};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations. Provide more surrounding context to make it unique.`};await rt(d);let T=(w!==g?(E=>E.replace(/\r\n/g,`
|
|
86
86
|
`).split(`
|
|
87
87
|
`).map($=>$.trimEnd()).join(`
|
|
88
88
|
`))(m):m).replace(w,y);await B.writeFile(d,T,"utf-8");let A=Bt(h.path,m,T);return{success:!0,output:`Edited: ${h.path}
|
|
89
89
|
${A}`}}catch(d){return{success:!1,output:"",error:`[edit_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!h.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!h.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(h.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let d=e(h.path),m=await B.readFile(d,"utf-8"),g=m.split(`
|
|
90
|
-
`),y=g.length,b=h.start_line,w=h.end_line;if(b<1||b>y)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${y} lines)`};if(w<b||w>y)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${b}, total=${y})`};await
|
|
90
|
+
`),y=g.length,b=h.start_line,w=h.end_line;if(b<1||b>y)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${y} lines)`};if(w<b||w>y)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${b}, total=${y})`};await rt(d);let v=g.slice(0,b-1),_=g.slice(w),T=h.new_content.split(`
|
|
91
91
|
`),A=[...v,...T,..._].join(`
|
|
92
92
|
`);await B.writeFile(d,A,"utf-8");let E=Bt(h.path,m,A),$=w-b+1,P=T.length;return{success:!0,output:`Patched: ${h.path} (replaced ${$} lines with ${P})
|
|
93
|
-
${E}`}}catch(d){return{success:!1,output:"",error:`[patch_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let d=e(h.path),m=await B.readFile(d,"utf-8"),g=h.search,y=h.replace,b=h.is_regex;await
|
|
94
|
-
`)}}catch(d){return{success:!1,output:"",error:`[get_file_info]: ${d.message}`}}}}]}function
|
|
95
|
-
`,c.isDirectory()){let p=e+(l?" ":"\u2502 ");o+=await
|
|
96
|
-
Error: ${a.message}`}),
|
|
97
|
-
Process timed out after ${
|
|
98
|
-
`),i+=
|
|
93
|
+
${E}`}}catch(d){return{success:!1,output:"",error:`[patch_file]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let d=e(h.path),m=await B.readFile(d,"utf-8"),g=h.search,y=h.replace,b=h.is_regex;await rt(d);let w,v;if(b){let _=new RegExp(g,"g");v=(m.match(_)||[]).length,w=m.replace(_,y)}else v=Ts(m,g),w=m.split(g).join(y);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await B.writeFile(d,w,"utf-8"),{success:!0,output:`Replaced ${v} occurrence(s) in ${h.path}`})}catch(d){return{success:!1,output:"",error:`[search_and_replace]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let d=e(h.path);return await B.mkdir(Be.dirname(d),{recursive:!0}),Cs.existsSync(d)&&await rt(d),await B.appendFile(d,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(d){return{success:!1,output:"",error:`[append_to_file]: ${d.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let d=e(h.path);return await rt(d),await B.unlink(d),{success:!0,output:`Deleted: ${h.path}`}}catch(d){return{success:!1,output:"",error:`[delete_file]: ${d.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 h=>{try{if(!h.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!h.to)return{success:!1,output:"",error:"[move_file]: to is required"};let d=e(h.from),m=e(h.to);return await B.mkdir(Be.dirname(m),{recursive:!0}),await B.rename(d,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(d){return{success:!1,output:"",error:`[move_file]: ${d.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let d=e(h.path);return await B.mkdir(d,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(d){return{success:!1,output:"",error:`[create_dir]: ${d.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 h=>{try{let d=e(h.path||"."),m=h.depth||3;return{success:!0,output:await uc(d,"",m,0)||"(empty directory)"}}catch(d){return{success:!1,output:"",error:`[list_dir]: ${d.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 h=>{try{if(!h.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let d=e(h.path),m=await B.stat(d);return{success:!0,output:[`Path: ${h.path}`,`Size: ${Im(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
|
|
94
|
+
`)}}catch(d){return{success:!1,output:"",error:`[get_file_info]: ${d.message}`}}}}]}function Ts(t,e){let n=0,r=0;for(;;){let s=t.indexOf(e,r);if(s===-1)break;n++,r=s+e.length}return n}var Rm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function uc(t,e,n,r){if(r>=n)return"";let i=(await B.readdir(t,{withFileTypes:!0})).filter(a=>!Rm.has(a.name)&&!a.name.startsWith(".")).sort((a,c)=>a.isDirectory()&&!c.isDirectory()?-1:!a.isDirectory()&&c.isDirectory()?1:a.name.localeCompare(c.name)),o="";for(let a=0;a<i.length;a++){let c=i[a],l=a===i.length-1,u=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=c.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${f} ${c.name}
|
|
95
|
+
`,c.isDirectory()){let p=e+(l?" ":"\u2502 ");o+=await uc(Be.join(t,c.name),p,n,r+1)}}return o}function Im(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var pc=require("child_process");var fc=require("child_process"),Rn=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,n){let r=`bg_${this.nextId++}`,s=n?.timeout||this.config.defaultTimeout,i=(0,fc.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...n?.env}}),o={id:r,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
|
|
96
|
+
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(r),o.status="timeout",o.stderr+=`
|
|
97
|
+
Process timed out after ${s}ms`)},s),this.processes.set(r,o),r}readOutput(e,n){let r=this.processes.get(e);if(!r)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=n?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=r.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
|
|
98
|
+
`),i+=r.stderr),n?.lastLines&&(i=i.split(`
|
|
99
99
|
`).slice(-n.lastLines).join(`
|
|
100
|
-
`)),{success:!0,output:i,status:
|
|
101
|
-
PID: ${
|
|
102
|
-
Use bash_output to read output: bash_output(process_id="${c}")`}}return new Promise(c=>{let l=(0,
|
|
103
|
-
... [${g} truncated \u2014 ${m.length} chars total]`:m;c(p===0?{success:!0,output:d(u,"stdout")||"(no output)"}:{success:!1,output:d(u,"stdout"),error:d(f||`Exit code: ${p}`,"stderr")})}),l.on("error",p=>{c({success:!1,output:"",error:p.message})})})}}}var In=k(require("fs/promises")),He=k(require("path")),
|
|
104
|
-
`),o=
|
|
105
|
-
... and ${
|
|
106
|
-
`),l=He.relative(
|
|
107
|
-
`);for(let a of o){let c=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);c&&e.push({file:c[1],line:parseInt(c[2],10),severity:c[3]==="error"?"error":"warning",message:c[4].trim(),source:"typescript"})}}return e}function
|
|
108
|
-
`);for(let a of o){let c=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);c&&e.push({file:"unknown",line:parseInt(c[1],10),severity:c[3]==="error"?"error":"warning",message:`${c[4]} (${c[5]})`,source:"eslint"})}}}return e}function
|
|
109
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&n.push({file:
|
|
110
|
-
`)}function
|
|
111
|
-
`);
|
|
112
|
-
`),"utf-8"),n.push({bug:
|
|
100
|
+
`)),{success:!0,output:i,status:r.status}}kill(e){let n=this.processes.get(e);if(!n)return!1;if(n.process.pid)try{process.kill(-n.process.pid,"SIGTERM")}catch{try{process.kill(n.process.pid,"SIGTERM")}catch{}}return n.status="killed",!0}killAll(){let e=0;for(let n of this.processes.keys())this.kill(n)&&e++;return e}listProcesses(){let e=[];for(let[n,r]of this.processes){let s=Date.now()-r.startTime,i=this.formatUptime(s);e.push({id:n,command:r.command,status:r.status,pid:r.pid,startTime:r.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[n,r]of this.processes)(r.status==="finished"||r.status==="killed"||r.status==="timeout")&&(this.processes.delete(n),e++);return e}formatUptime(e){let n=Math.floor(e/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60);return r<60?`${r}m ${n%60}s`:`${Math.floor(r/60)}h ${r%60}m`}};var jm=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],$s=null;function dc(t){return $s||($s=new Rn({workingDir:t})),$s}function hc(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async n=>{let r=n.command,s=n.run_in_background===!0,i=n.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...jm,...o];if(a.length>0){for(let c of a)if(r.includes(c))return{success:!1,output:"",error:`Blocked pattern: "${c}". This command is prohibited due to security risks.`}}if(s){let c=dc(t).start(r,{timeout:i});return{success:!0,output:`Background process started: ${c}
|
|
101
|
+
PID: ${dc(t).getProcess(c)?.pid}
|
|
102
|
+
Use bash_output to read output: bash_output(process_id="${c}")`}}return new Promise(c=>{let l=(0,pc.exec)(r,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",f="";l.stdout?.on("data",p=>{u+=p}),l.stderr?.on("data",p=>{f+=p}),l.on("close",p=>{let d=(m,g)=>m.length>8e3?m.slice(0,8e3)+`
|
|
103
|
+
... [${g} truncated \u2014 ${m.length} chars total]`:m;c(p===0?{success:!0,output:d(u,"stdout")||"(no output)"}:{success:!1,output:d(u,"stdout"),error:d(f||`Exit code: ${p}`,"stderr")})}),l.on("error",p=>{c({success:!1,output:"",error:p.message})})})}}}var In=k(require("fs/promises")),He=k(require("path")),Pm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Mm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function mc(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let n=e.query,r=He.resolve(t,e.path||"."),s=[];if(await gc(r,n,s,t),s.length===0)return{success:!0,output:`No matches found for: "${n}"`};let i=s.slice(0,50).join(`
|
|
104
|
+
`),o=s.length>50?`
|
|
105
|
+
... and ${s.length-50} more matches`:"";return{success:!0,output:i+o}}catch(n){return{success:!1,output:"",error:`Search failed: ${n.message}`}}}}}async function gc(t,e,n,r){let s=await In.readdir(t,{withFileTypes:!0});for(let i of s){if(Pm.has(i.name)||i.name.startsWith("."))continue;let o=He.join(t,i.name);if(i.isDirectory())await gc(o,e,n,r);else if(Mm.has(He.extname(i.name)))try{let c=(await In.readFile(o,"utf-8")).split(`
|
|
106
|
+
`),l=He.relative(r,o);for(let u=0;u<c.length;u++)new RegExp(e,"i").test(c[u])&&n.push(`${l}:${u+1}: ${c[u].trim()}`)}catch{}}}var Es=require("child_process"),he=k(require("fs")),We=k(require("path"));function Fm(t){let e=[],n=We.join(t,"tsconfig.json");if(!he.existsSync(n))return e;try{(0,Es.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(r){let s=r,o=(s.stdout||s.message||"").split(`
|
|
107
|
+
`);for(let a of o){let c=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);c&&e.push({file:c[1],line:parseInt(c[2],10),severity:c[3]==="error"?"error":"warning",message:c[4].trim(),source:"typescript"})}}return e}function Lm(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(r=>he.existsSync(We.join(t,r))))return e;try{(0,Es.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(r){let i=r.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let c of a.messages||[])e.push({file:We.relative(t,a.filePath),line:c.line||0,severity:c.severity===2?"error":"warning",message:`${c.message} (${c.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
|
|
108
|
+
`);for(let a of o){let c=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);c&&e.push({file:"unknown",line:parseInt(c[1],10),severity:c[3]==="error"?"error":"warning",message:`${c[4]} (${c[5]})`,source:"eslint"})}}}return e}function Dm(t,e,n){let r;try{r=he.readFileSync(t,"utf-8")}catch{return}let s=We.relative(e,t),i=r.split(`
|
|
109
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&n.push({file:s,line:c,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&n.push({file:s,line:c,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&n.push({file:s,line:c,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&n.push({file:s,line:c,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function Nm(t){let e=[],n=[".ts",".tsx",".js",".jsx"];function r(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=he.readdirSync(s)}catch{return}for(let c of a){if(o.includes(c))continue;let l=We.join(s,c),u;try{u=he.statSync(l)}catch{continue}u.isDirectory()?r(l,i+1):n.some(f=>c.endsWith(f))&&Dm(l,t,e)}}return r(t),e.slice(0,20)}function Um(t){let e=[];e.push(...Fm(t)),e.push(...Lm(t)),e.push(...Nm(t));let n={error:0,warning:1,info:2};return e.sort((r,s)=>n[r.severity]-n[s.severity]),e}function yc(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],n=t.filter(i=>i.severity==="error").length,r=t.filter(i=>i.severity==="warning").length,s=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${n} errors, ${r} warnings, ${s} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
|
|
110
|
+
`)}function qm(t,e){let n=[];for(let r of t)if(r.source==="pattern"&&r.message.includes("console.log")){let s=We.join(e,r.file);try{let o=he.readFileSync(s,"utf-8").split(`
|
|
111
|
+
`);r.line>0&&r.line<=o.length&&(o[r.line-1]="// "+o[r.line-1],he.writeFileSync(s,o.join(`
|
|
112
|
+
`),"utf-8"),n.push({bug:r,fixed:!0,action:"Commented out console.log"}))}catch{n.push({bug:r,fixed:!1,action:"Failed to read/write file"})}}else n.push({bug:r,fixed:!1,action:"Requires manual fix or LLM assistance"});return n}function wc(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let n=e.path||t,r=e.fix==="true"||e.fix===!0;try{let s=Um(n);if(r&&s.length>0){let o=qm(s,n).filter(c=>c.fixed).length;return{success:!0,output:`${yc(s)}
|
|
113
113
|
|
|
114
|
-
Auto-fixed: ${o}/${
|
|
114
|
+
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:yc(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var bc=2*1024*1024,xc=15e3,Sc=32e3,Bm="HablasBot/2.0 (+https://hablas.dev)";function Hm(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
|
|
115
115
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
116
116
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
117
|
-
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(n,s
|
|
118
|
-
${"#".repeat(parseInt(
|
|
119
|
-
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(n,s
|
|
117
|
+
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(n,r,s)=>`
|
|
118
|
+
${"#".repeat(parseInt(r))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
119
|
+
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(n,r,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${r})`:r}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(n,r)=>"\n```\n"+r.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(n,r)=>String.fromCharCode(parseInt(r))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
120
120
|
|
|
121
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
121
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Wm(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let n=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return n?n[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Vm(t,e){let n=[],r=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=r.exec(t))!==null;){let o=s[1].trim(),a=s[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),n.push({text:a||o,url:o}))}}return n}async function vc(t){let e=new AbortController,n=setTimeout(()=>e.abort(),xc);try{let r=await fetch(t,{signal:e.signal,headers:{"User-Agent":Bm,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(n),!r.ok)return{html:"",finalUrl:r.url||t,status:r.status};let s=r.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:r.url||t,status:r.status};let i=r.body?.getReader();if(!i)return{html:"",finalUrl:r.url||t,status:r.status};let o=[],a=0;for(;a<bc;){let{done:u,value:f}=await i.read();if(u)break;o.push(f),a+=f.length}if(a>=bc)try{i.cancel()}catch{}let c=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>c.decode(u,{stream:!0})).join("")+c.decode(),finalUrl:r.url||t,status:r.status}}catch(r){clearTimeout(n);let s=r instanceof Error?r:new Error(String(r));throw s.name==="AbortError"?new Error(`Timeout after ${xc/1e3}s`):s}}function _c(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:r,status:s}=await vc(e);if(!n||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Wm(n),o=Hm(n);return o.length>Sc&&(o=o.slice(0,Sc)+`
|
|
122
122
|
|
|
123
|
-
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${
|
|
124
|
-
`)}}catch(n){let
|
|
123
|
+
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${r}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
124
|
+
`)}}catch(n){let r=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to scrape ${e}: ${r}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,n=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:s,status:i}=await vc(e);if(!r||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Vm(r,s);if(n&&(o=o.filter(c=>c.url.toLowerCase().includes(n)||c.text.toLowerCase().includes(n))),o.length===0)return{success:!0,output:"No links found"+(n?` matching "${n}"`:"")};let a=o.slice(0,100).map((c,l)=>`${l+1}. [${c.text}](${c.url})`).join(`
|
|
125
125
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
126
126
|
|
|
127
|
-
${a}`}}catch(
|
|
128
|
-
`)}}catch(
|
|
127
|
+
${a}`}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var zm=3600*1e3,yt=new Map;function Km(t){let e=yt.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>zm?(yt.delete(t.toLowerCase().trim()),null):e.results:null}function Gm(t,e){if(yt.size>200){let n=yt.keys().next().value;n!==void 0&&yt.delete(n)}yt.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Jm(t,e){let n=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!n)return null;try{let r=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${r}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":n},signal:AbortSignal.timeout(1e4)});return s.ok?((await s.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function Ym(t,e){try{let n=new URLSearchParams({q:t}),r=await fetch(`https://html.duckduckgo.com/html/?${n}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!r.ok)return null;let s=await r.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let c=a[1],l=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),f=c.match(/uddg=([^&]+)/);if(f)try{c=decodeURIComponent(f[1])}catch{}l&&c&&!c.startsWith("/")&&i.push({title:l,url:c,snippet:u,source:"duckduckgo"})}if(i.length===0){let c=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,l=new Set;for(;(a=c.exec(s))!==null&&i.length<e;){let u=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!l.has(u)&&!u.includes("duckduckgo.com")&&(l.add(u),i.push({title:f,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function As(t,e=5){let n=Km(t);if(n)return n.slice(0,e);let r=[{name:"brave",fn:()=>Jm(t,e)},{name:"duckduckgo",fn:()=>Ym(t,e)}];for(let s of r)try{let i=await s.fn();if(i&&i.length>0)return Gm(t,i),i}catch{}return[]}function kc(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let n=Math.min(Math.max(1,t.max_results||5),10);try{let r=await As(e.trim(),n);if(r.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${r.length} results, source: ${r[0].source})`,""];for(let i=0;i<r.length;i++){let o=r[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
|
|
128
|
+
`)}}catch(r){return{success:!1,output:"",error:`Search failed: ${r instanceof Error?r.message:String(r)}`}}}}}var je=k(require("fs")),Ac=k(require("path")),Tc=50*1024*1024,Cc=4e4;function $c(t){let e=t.toString("latin1"),n={},r=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(n.title=st(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(n.author=st(a[1]));let c=e.match(/\/Subject\s*\(([^)]*)\)/);c&&(n.subject=st(c[1]));let l=e.match(/\/Creator\s*\(([^)]*)\)/);l&&(n.creator=st(l[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=u.exec(e))!==null;){let h=f[1],d=Ec(h);d.trim()&&r.push(d);try{let m=require("zlib"),g=Buffer.from(h,"latin1"),y=m.inflateSync(g).toString("latin1"),b=Ec(y);b.trim()&&!r.includes(b)&&r.push(b)}catch{}}return{text:r.join(`
|
|
129
129
|
`).replace(/\r\n/g,`
|
|
130
130
|
`).replace(/\n{3,}/g,`
|
|
131
131
|
|
|
132
|
-
`).trim(),pages:
|
|
133
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function
|
|
134
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,n)=>String.fromCharCode(parseInt(n,8)))}function
|
|
132
|
+
`).trim(),pages:s,metadata:n}}function Ec(t){let e=[],n=/\(([^)]*)\)\s*Tj/g,r;for(;(r=n.exec(t))!==null;)e.push(st(r[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(r=s.exec(t))!==null;){let c=r[1].match(/\(([^)]*)\)/g);if(c){let l=c.map(u=>st(u.slice(1,-1))).join("");e.push(l)}}let i=/\(([^)]*)\)\s*'/g;for(;(r=i.exec(t))!==null;)e.push(st(r[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
|
|
133
|
+
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function st(t){return t.replace(/\\n/g,`
|
|
134
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,n)=>String.fromCharCode(parseInt(n,8)))}function Oc(t){let e=n=>Ac.resolve(t,n);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async n=>{let r=e(n.path);if(!je.existsSync(r))return{success:!1,output:"",error:`File not found: ${n.path}`};if(!r.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${n.path}`};let s=je.statSync(r);if(s.size>Tc)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${Tc/1024/1024}MB)`};try{let i=je.readFileSync(r),{text:o,pages:a,metadata:c}=$c(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${n.path} (${a} pages)
|
|
135
135
|
|
|
136
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let l=o;return l.length>
|
|
136
|
+
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let l=o;return l.length>Cc&&(l=l.slice(0,Cc)+`
|
|
137
137
|
|
|
138
|
-
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${n.path}`,`Pages: ${a}`,c.title?`Title: ${c.title}`:"",c.author?`Author: ${c.author}`:"",`Size: ${(
|
|
138
|
+
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${n.path}`,`Pages: ${a}`,c.title?`Title: ${c.title}`:"",c.author?`Author: ${c.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
139
139
|
`)}
|
|
140
|
-
${l}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async n=>{let
|
|
141
|
-
`)}}catch(
|
|
142
|
-
Errors/Warnings:`:"Errors:"),i.push(
|
|
143
|
-
`),error:
|
|
140
|
+
${l}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async n=>{let r=e(n.path);if(!je.existsSync(r))return{success:!1,output:"",error:`File not found: ${n.path}`};try{let s=je.statSync(r),i=je.readFileSync(r),{pages:o,metadata:a}=$c(i);return{success:!0,output:[`File: ${n.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
|
|
141
|
+
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var jc=require("child_process"),jn=k(require("fs")),Pc=k(require("os")),Mc=k(require("path")),Fc=1e4,Rc=16e3;function wt(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 Ic={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>wt("tsx")?`tsx "${t}"`:wt("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=>wt("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>wt("python3")||wt("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>wt("bash")}};async function Xm(t,e,n=Fc){let r=Ic[e];if(!r)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Ic).join(", ")}`,exitCode:1,duration:0,language:e};if(!r.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=Pc.tmpdir(),i=Mc.join(s,`hablas_exec_${Date.now()}${r.extension}`);try{jn.writeFileSync(i,t,"utf-8");let o=r.command(i),a=Date.now();return await new Promise(c=>{let l=(0,jc.exec)(o,{timeout:n,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",f="";l.stdout?.on("data",p=>{u+=p}),l.stderr?.on("data",p=>{f+=p}),l.on("close",p=>{let h=Date.now()-a;c({success:p===0,stdout:u.slice(0,Rc),stderr:f.slice(0,Rc/2),exitCode:p??1,duration:h,language:e})}),l.on("error",p=>{let h=Date.now()-a;c({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{jn.unlinkSync(i)}catch{}}}function Qm(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 Lc(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let n=t.language?.toLowerCase()||Qm(e),r=Math.min(Math.max(1e3,t.timeout||Fc),3e4),s=await Xm(e,n,r),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
|
|
142
|
+
Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
|
|
143
|
+
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Ln=k(require("fs")),Se=k(require("path"));var Zm=["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"],eg=[/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 Os(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 tg=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 Pn(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!tg.has(e))}function Mn(t,e){let n=[...new Set(Pn(t))].slice(0,6);return n.length>0?n.join(" "):t.trim().slice(0,60)}function Wt(t){try{let e=new URL(t).hostname.toLowerCase();return Zm.some(n=>e===n||e.endsWith("."+n))}catch{return!1}}function ng(t){return eg.some(e=>e.test(t))}function Fn(t,e,n,r,s=[]){let i=Wt(t),o=[],a=[],c=0;if(i&&(c+=20,o.push("trusted-host")),ng(t)&&(c+=15,o.push("cdn-direct")),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(c+=8,o.push("image-ext")),(/\/photos?\/[^/?#]+/i.test(t)||/\/images?\/[^/?#]+/i.test(t))&&(c+=6,o.push("photo-page")),s.length>0){let u=Pn([e,n,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),f=new Set(u),p=s.filter(h=>f.has(h));p.length>0&&(c+=p.length*10,o.push("query-match:"+p.slice(0,3).join(",")))}let l=[e,n,t].join(" ").toLowerCase();return(r==="hero"||r==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(l)&&(c+=5,o.push("kind-hero")),(r==="product"||r==="thumbnail")&&/product|closeup|detail|item|buy/i.test(l)&&(c+=5,o.push("kind-product")),(r==="icon"||r==="avatar")&&/icon|avatar|logo|portrait|profile/i.test(l)&&(c+=5,o.push("kind-icon")),/javascript|\.woff|\.eot|\.ttf|\.css/i.test(t)&&(c-=30,a.push("non-image-resource")),{score:c,positives:o,negatives:a,trusted:i}}function Dc(t,e){let n=Mn(t,e),r=encodeURIComponent(n);return n?[{source:"unsplash",url:`https://unsplash.com/s/photos/${r}`},{source:"pexels",url:`https://www.pexels.com/search/${r}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${r}/`}]:[]}function Nc(t,e){let n=Mn(t,e);return[`${n} site:unsplash.com/photos`,`${n} site:pexels.com/photo`,`${n} site:pixabay.com/photos`,`${n} site:commons.wikimedia.org/wiki/File`]}function rg(t,e){try{let n=t.split(",")[0].trim().split(/\s+/)[0],r=new URL(n,e);return/^https?:$/i.test(r.protocol)?r.href:null}catch{return null}}function bt(t,e){let n=new Set,r=[];function s(i){let o=rg(i,e);o&&!n.has(o)&&(n.add(o),r.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 c of a)typeof c=="string"?s(c):typeof c?.url=="string"?s(c.url):typeof c?.contentUrl=="string"?s(c.contentUrl):Array.isArray(c)&&c.forEach(l=>{typeof l=="string"?s(l):l?.url&&s(l.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 c=a.trim().split(/\s+/);return{url:c[0],w:parseInt(c[1]??"0")||0}}).sort((a,c)=>c.w-a.w)[0];o?.url&&s(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))s(i[1]);return r.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:Wt(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function Uc(t,e){let n=new Set,r=[];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))&&!n.has(i.href)&&(n.add(i.href),r.push(i.href))}catch{}return r.slice(0,20)}var qc=15*1024*1024,Bc=15e3,sg=5;function ig(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 Se.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Hc(t){let e="";try{let n=new URL(t);e=`${n.protocol}//${n.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 og(t){let e=await fetch(t,{signal:AbortSignal.timeout(Bc),redirect:"follow",headers:Hc(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let n=e.headers.get("content-type")||"",r=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(n))throw new Error("HTML page returned where a direct image was expected");let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>qc)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:n,finalUrl:r}}async function ag(t,e="generic",n=0){if(n>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let r=await fetch(t,{signal:AbortSignal.timeout(Bc),redirect:"follow",headers:Hc(t)});if(!r.ok)throw new Error(`HTTP ${r.status} while downloading asset`);let s=r.headers.get("content-type")||"",i=r.url||t;if(/text\/html|application\/xhtml\+xml/i.test(s)){let c=await r.text(),l=bt(c,i).map(f=>({url:f,...Fn(f,"","",e)})).sort((f,p)=>p.score-f.score).slice(0,sg);if(l.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let f of l)try{return await og(f.url)}catch(p){u=String(p?.message||p)}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await r.arrayBuffer(),a=Buffer.from(o);if(a.length>qc)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:s,finalUrl:i}}function cg(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 Wc(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 n=String(e.url||""),r=String(e.path||"");if(!n)return{success:!1,output:"",error:"url is required"};if(!r)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(n))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await ag(n,cg(r)),a=Se.resolve(t,r),l=Se.extname(a)?a:a+ig(i,o);return Ln.mkdirSync(Se.dirname(l),{recursive:!0}),Ln.writeFileSync(l,s),{success:!0,output:`Downloaded asset: ${Se.relative(t,l)||Se.basename(l)}
|
|
144
144
|
Final source: ${o}
|
|
145
145
|
Type: ${i||"unknown"}
|
|
146
|
-
Size: ${
|
|
146
|
+
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${s?.message||String(s)}`}}}}}var Dn=k(require("fs")),Nn=k(require("path"));var Is=15e3,Vc=5;function zc(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Kc(t,e){return t[e]|t[e+1]<<8}function lg(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let n=t[e+1],r=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(n))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+r}return{}}function ug(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 n=(t.readUInt16LE(26)&16383)+1,r=(t.readUInt16LE(28)&16383)+1;return{width:n,height:r}}return{}}function Rs(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:zc(t,16),height:zc(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Kc(t,6),height:Kc(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...lg(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...ug(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function Yc(t){let e="";try{let n=new URL(t);e=`${n.protocol}//${n.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 Gc(t){let e=await fetch(t,{signal:AbortSignal.timeout(Is),redirect:"follow",headers:Yc(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let n=e.headers.get("content-type")||"",r=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).subarray(0,2*1024*1024),o=/text\/html|application\/xhtml/i.test(n)?i.toString("utf-8"):void 0;return{status:e.status,contentType:n,bytes:i,finalUrl:r,html:o}}async function Jc(t){let e=await fetch(t,{signal:AbortSignal.timeout(Is),redirect:"follow",headers:{...Yc(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 fg(t,e){let n=new URLSearchParams({action:"query",generator:"search",gsrsearch:Mn(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),r=await fetch(`https://commons.wikimedia.org/w/api.php?${n}`,{signal:AbortSignal.timeout(Is),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!r.ok)throw new Error(`Wikimedia HTTP ${r.status}`);let s=await r.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 dg(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
|
|
147
147
|
|
|
148
148
|
Context from user: "${t}"
|
|
149
149
|
|
|
@@ -162,39 +162,39 @@ Rules:
|
|
|
162
162
|
- confidence: float 0.0\u20131.0
|
|
163
163
|
- suggestedUse: one of "hero", "product", "icon", "generic", "reject"
|
|
164
164
|
- issues: list any quality or relevance problems (empty array if none)
|
|
165
|
-
- Do NOT output anything outside the JSON object`}async function
|
|
165
|
+
- Do NOT output anything outside the JSON object`}async function pg(t,e,n,r){let s=t.provider==="nvidia"?ue.apiUrl:t.apiUrl;if(!s)throw new Error("No API URL configured for vision");let i=`data:${n};base64,${e.toString("base64")}`,o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=t.vision.primaryModel,c=await fetch(s.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:dg(r)},{role:"user",content:[{type:"text",text:"Inspect this image."},{type:"image_url",image_url:{url:i}}]}],temperature:.1,max_tokens:300})});if(!c.ok)throw new Error(`Vision API HTTP ${c.status}`);let l=await c.json(),u=String(l?.choices?.[0]?.message?.content??""),f=null,p=u.indexOf("{"),h=u.lastIndexOf("}");if(p!==-1&&h>p)try{f=JSON.parse(u.slice(p,h+1))}catch{}if(!f)throw new Error("Vision response was not valid JSON");return{model:a,success:!0,description:String(f.description??""),suitable:!!f.suitable,confidence:Number(f.confidence??0),issues:Array.isArray(f.issues)?f.issues.map(String):[],suggestedUse:String(f.suggestedUse??"generic"),summary:String(f.summary??""),raw:u}}function hg(t,e,n){return!e||!n?0:(t==="hero"||t==="banner")&&e>=1200&&n>=500?12:(t==="product"||t==="thumbnail")&&e>=400&&n>=400?8:t==="icon"&&e>=64&&e<=512?6:t==="generic"&&e>=600&&n>=400?5:0}function Xc(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 n=>{let r=String(n.query||"").trim();if(!r)return{success:!1,output:"",error:"query is required"};let s=Os(n.kind),i=Math.min(Math.max(1,Number(n.max_results??5)),10),o=Pn(r),a=new Map,c=[],l=(p,h,d,m)=>{if(a.has(p))return;let g=Fn(p,h,d,s,o);a.set(p,{url:p,title:h,snippet:d,source:m,...g})};for(let p of Dc(r,s))try{let{finalUrl:h,html:d}=await Jc(p.url),m=Uc(d,h),g=0;for(let b of m.slice(0,Vc*2)){if(g>=Vc)break;try{let{finalUrl:w,html:v}=await Jc(b),T=bt(v,w)[0];T&&(l(T,p.source+" photo",r,p.source),g++)}catch{}}let y=bt(d,h);for(let b of y.slice(0,6))l(b,p.source,r,p.source);g===0&&y.length===0&&c.push(`${p.source}: no images found`)}catch(h){c.push(`${p.source}: ${String(h?.message??h)}`)}try{let p=await fg(r,Math.max(4,i));for(let h of p)l(h.url,h.title,h.snippet,h.source)}catch(p){c.push(`wikimedia: ${String(p?.message??p)}`)}if(a.size<i)for(let p of Nc(r,s))try{let h=await As(p,Math.max(6,i));for(let d of h)l(d.url,d.title,d.snippet,d.source);if(a.size>=i*2)break}catch{}let u=[...a.values()].sort((p,h)=>h.score-p.score).slice(0,i);if(u.length===0)return{success:!0,output:`No image candidates found for "${r}".${c.length?`
|
|
166
166
|
Notes:
|
|
167
167
|
- `+c.join(`
|
|
168
|
-
- `):""}`};let f=[`Image candidates for: "${
|
|
169
|
-
`)}}},{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 n=>{let
|
|
170
|
-
`)}}}]}var Ve=k(require("fs")),
|
|
171
|
-
`).length,h=
|
|
172
|
-
`)}}catch(i){return{success:!1,output:"",error:`Graph build failed: ${i.message}`}}}},{name:"find_references",description:"Find all files that import or reference a specific file or symbol. Use before renaming, moving, or deleting any file.",safety:"safe",parameters:{target:{type:"string",description:"File path or symbol name to find references for",required:!0}},execute:async
|
|
173
|
-
`)}}catch(i){return{success:!1,output:"",error:`Reference search failed: ${i.message}`}}}},{name:"impact_analysis",description:"Before changing a file, analyze the blast radius: which files will be affected and how critical the change is.",safety:"safe",parameters:{file:{type:"string",description:"File you intend to modify",required:!0}},execute:async
|
|
174
|
-
`)}}catch(i){return{success:!1,output:"",error:`Impact analysis failed: ${i.message}`}}}}]}var
|
|
168
|
+
- `):""}`};let f=[`Image candidates for: "${r}" (kind=${s}) \u2014 ${u.length} results`,""];return u.forEach((p,h)=>{f.push(`[${h+1}] score=${p.score} trusted=${p.trusted?"yes":"no"} source=${p.source}`),f.push(` url: ${p.url}`),p.title&&f.push(` title: ${p.title}`),p.positives.length&&f.push(` \u2713 ${p.positives.join(", ")}`),p.negatives.length&&f.push(` \u2717 ${p.negatives.join(", ")}`),f.push("")}),c.length&&(f.push("Notes:"),c.slice(0,5).forEach(p=>f.push(" - "+p))),{success:!0,output:f.join(`
|
|
169
|
+
`)}}},{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 n=>{let r=String(n.source||"").trim();if(!r)return{success:!1,output:"",error:"source is required"};let s=Os(n.kind),i=String(n.context||r).slice(0,200),o=String(n.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${r}`,""],c="unknown",l,u,f=!1,p=!1,h=r,d=null,m=!1,g=[];try{if(/^https?:\/\//i.test(r)){let w=await Gc(r);if(h=w.finalUrl,c=w.contentType,p=Wt(h),w.html){if(m=!0,g=bt(w.html,h),g.length>0){let v=g[0];try{let _=await Gc(v);h=_.finalUrl,c=_.contentType,d=_.bytes,p=Wt(h);let T=Rs(d,c);l=T.width,u=T.height,f=/^image\//i.test(c)}catch(_){a.push(` [warn] could not fetch best candidate: ${_.message}`)}}}else{d=w.bytes,f=/^image\//i.test(c)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(h);let v=Rs(d,c);l=v.width,u=v.height}}else{let w=Nn.resolve(t,r);if(!Dn.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${r}`};d=Dn.readFileSync(w).subarray(0,2*1024*1024);let v=Nn.extname(w).toLowerCase();c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml"}[v]||"application/octet-stream",f=!0,p=!1;let _=Rs(d,c);l=_.width,u=_.height}}catch(w){return{success:!1,output:"",error:`Failed to fetch/read source: ${w.message}`}}a.push(` final URL: ${h}`),a.push(` content-type: ${c}`),a.push(` direct image: ${f?"yes":"no (HTML page)"}`),a.push(` trusted host: ${p?"yes":"no"}`),l&&u&&a.push(` dimensions: ${l} \xD7 ${u} px`),d&&a.push(` size (fetched): ${(d.length/1024).toFixed(1)} KB`),m&&(a.push(" resolved via: HTML page extraction"),g.length>1&&(a.push(` other candidates found (${g.length-1}):`),g.slice(1,4).forEach(w=>a.push(` - ${w}`))));let y=hg(s,l,u);if(l&&u){let w=y>0;a.push(` size verdict: ${w?"\u2713 adequate for "+s:"\u2717 may be too small for "+s} (${l}\xD7${u})`)}if(o&&e.vision.enabled&&d&&/^image\//i.test(c)){a.push(""),a.push(" Vision analysis:");try{let w=await pg(e,d.subarray(0,e.vision.maxImageBytes),c,i);a.push(` model: ${w.model}`),a.push(` description: ${w.description}`),a.push(` suitable: ${w.suitable?"yes":"no"}`),a.push(` confidence: ${(w.confidence*100).toFixed(0)}%`),a.push(` suggested: ${w.suggestedUse}`),a.push(` summary: ${w.summary}`),w.issues.length>0&&a.push(` issues: ${w.issues.join("; ")}`)}catch(w){a.push(` [vision unavailable: ${w.message}]`),e.vision.enabled||a.push(" (enable vision in config to use this feature)")}}else e.vision.enabled||(a.push(""),a.push(" [vision: disabled in config]"));a.push("");let b=f&&(p||/^image\//i.test(c));return a.push(` VERDICT: ${b?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
|
|
170
|
+
`)}}}]}var Ve=k(require("fs")),se=k(require("path")),mg=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage",".turbo"]),gg=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java"]),yg=/\b(index|main|app|server|start|entry|cli)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/i;function wg(t,e,n){let r=[],s=se.dirname(e),i=[/from\s+['"]([^'"]+)['"]/g,/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let a of i){let c;for(;(c=a.exec(t))!==null;){let l=c[1];if(l.startsWith(".")){let u=se.resolve(s,l);if(!Ve.existsSync(u)){for(let f of[".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"])if(Ve.existsSync(u+f)){u=u+f;break}}Ve.existsSync(u)&&r.push(se.relative(n,u))}}}let o=[/^from\s+\.\S*\s+import/gm,/^import\s+\./gm];for(let a of o)for(;a.exec(t)!==null;)r.push(s);return[...new Set(r)]}function bg(t,e){let n=[];if(e==="ts"||e==="js"){let r=[/export\s+(?:default\s+)?(?:function|class|const|let|var|interface|type|enum)\s+(\w+)/g,/export\s*\{\s*([^}]+)\}/g];for(let s of r){let i;for(;(i=s.exec(t))!==null;){let o=i[1].split(",").map(a=>a.trim().split(/\s+as\s+/).pop().trim());n.push(...o.filter(Boolean))}}}return[...new Set(n)].slice(0,20)}function Qc(t,e){let n=[];try{let r=Ve.readdirSync(t,{withFileTypes:!0});for(let s of r){if(mg.has(s.name)||s.name.startsWith("."))continue;let i=se.join(t,s.name);s.isDirectory()?n.push(...Qc(i,e)):gg.has(se.extname(s.name))&&n.push(se.relative(e,i))}}catch{}return n}function xg(t){let e=[],n=new Set,r=new Set;function s(i,o){if(r.has(i)){let c=o.indexOf(i);c!==-1&&e.push(o.slice(c));return}if(n.has(i))return;n.add(i),r.add(i);let a=t.get(i);if(a)for(let c of a.imports)s(c,[...o,c]);r.delete(i)}for(let i of t.keys())s(i,[i]);return e.slice(0,5)}function js(t,e=300){let n=Date.now(),r=Qc(t,t).slice(0,e),s=new Map;for(let a of r)try{let c=se.join(t,a),l=Ve.readFileSync(c,"utf-8"),u=se.extname(a).slice(1),f=["ts","tsx"].includes(u)?"ts":["js","jsx","mjs"].includes(u)?"js":u,p=l.split(`
|
|
171
|
+
`).length,h=wg(l,c,t),d=bg(l,f),m=yg.test(a);s.set(a,{path:a,imports:h,exports:d,references:[],isEntryPoint:m,lines:p,language:f})}catch{}for(let[a,c]of s)for(let l of c.imports){let u=s.get(l);u&&!u.references.includes(a)&&u.references.push(a)}let i=[...s.values()].filter(a=>a.isEntryPoint||a.references.length===0&&a.imports.length>0).map(a=>a.path).slice(0,5),o=xg(s);return{nodes:s,entryPoints:i,circularDeps:o,totalFiles:r.length,buildTime:Date.now()-n}}function Zc(t){return[{name:"analyze_project",description:"Build a complete graph of the project: all files, imports, exports, entry points, and circular dependencies. Use this BEFORE making multi-file changes to understand the full impact. Returns ranked file importance.",safety:"safe",parameters:{focus:{type:"string",description:'Optional: focus on a subdirectory (e.g. "src/components")',required:!1},max_files:{type:"number",description:"Max files to analyze (default: 200)",required:!1}},execute:async s=>{try{let i=s.focus?se.join(t,s.focus):t,o=s.max_files||200,a=js(i,o),c=[...a.nodes.values()].sort((u,f)=>f.references.length-u.references.length).slice(0,30),l=[`Project Graph \xB7 ${a.totalFiles} files \xB7 built in ${a.buildTime}ms`,"","\u2500\u2500 Entry Points \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...a.entryPoints.map(u=>` ${u}`),"","\u2500\u2500 Most Referenced Files (impact ranking) \u2500\u2500"];for(let u of c)u.references.length!==0&&(l.push(` ${u.path.padEnd(45)} \u2190 referenced by ${u.references.length} files`),u.exports.length&&l.push(` exports: ${u.exports.slice(0,6).join(", ")}`));if(a.circularDeps.length){l.push(""),l.push("\u2500\u2500 Circular Dependencies (\u26A0 fix before refactoring) \u2500\u2500");for(let u of a.circularDeps)l.push(` ${u.join(" \u2192 ")}`)}return l.push(""),l.push(`Total nodes: ${a.nodes.size} | Entry points: ${a.entryPoints.length} | Circular deps: ${a.circularDeps.length}`),{success:!0,output:l.join(`
|
|
172
|
+
`)}}catch(i){return{success:!1,output:"",error:`Graph build failed: ${i.message}`}}}},{name:"find_references",description:"Find all files that import or reference a specific file or symbol. Use before renaming, moving, or deleting any file.",safety:"safe",parameters:{target:{type:"string",description:"File path or symbol name to find references for",required:!0}},execute:async s=>{try{let i=s.target,o=js(t,300),a=[],c=o.nodes.get(i);if(c){a.push(`File: ${i}`),a.push(`Referenced by ${c.references.length} files:`);for(let l of c.references)a.push(` ${l}`);a.push(""),a.push(`This file imports ${c.imports.length} files:`);for(let l of c.imports)a.push(` ${l}`)}else{a.push(`Symbol search: "${i}"`);let l=0;for(let[u,f]of o.nodes)f.exports.some(p=>p.toLowerCase().includes(i.toLowerCase()))&&(a.push(` exported from: ${u}`),a.push(` referenced by: ${f.references.join(", ")||"none"}`),l++);l||a.push(" No matches found.")}return{success:!0,output:a.join(`
|
|
173
|
+
`)}}catch(i){return{success:!1,output:"",error:`Reference search failed: ${i.message}`}}}},{name:"impact_analysis",description:"Before changing a file, analyze the blast radius: which files will be affected and how critical the change is.",safety:"safe",parameters:{file:{type:"string",description:"File you intend to modify",required:!0}},execute:async s=>{try{let i=s.file,o=js(t,300),a=o.nodes.get(i);if(!a)return{success:!0,output:`File "${i}" not found in graph. It may be new.`};let c=new Set,l=[...a.references];for(;l.length;){let h=l.shift();if(!c.has(h)){c.add(h);let d=o.nodes.get(h);d&&l.push(...d.references)}}let u=c.size,f=u===0?"LOW":u<=3?"MEDIUM":u<=10?"HIGH":"CRITICAL",p=[`Impact Analysis: ${i}`,`Severity: ${f} (${u} files affected)`,"",`Direct referrers (${a.references.length}):`,...a.references.map(h=>` ${h}`)];if(c.size>a.references.length){p.push(""),p.push(`Transitive impact (${c.size} total):`);for(let h of[...c].slice(0,15))p.push(` ${h}`);c.size>15&&p.push(` ... and ${c.size-15} more`)}return p.push(""),p.push(`Exports: ${a.exports.join(", ")||"none"}`),p.push(`Imports: ${a.imports.length} files`),p.push(`Size: ${a.lines} lines`),{success:!0,output:p.join(`
|
|
174
|
+
`)}}catch(i){return{success:!1,output:"",error:`Impact analysis failed: ${i.message}`}}}}]}var el=require("child_process"),tl=k(require("fs")),nl=k(require("path"));function it(t,e,n=15e3){return new Promise(r=>{(0,el.exec)(t,{cwd:e,timeout:n,maxBuffer:4*1024*1024},(s,i,o)=>{let a=s?s.code:void 0;r({out:i||"",err:o||"",code:typeof a=="number"?a:s?1:0})})})}function Vt(t){return tl.existsSync(nl.join(t,".git"))}function rl(t){return[{name:"git_status",description:"Show current git status: staged, unstaged, and untracked files. Use before committing or to understand what changed.",safety:"safe",parameters:{},execute:async()=>{if(!Vt(t))return{success:!0,output:"No git repository in this workspace."};let{out:o,err:a,code:c}=await it("git status --short --branch",t);if(c!==0)return{success:!1,output:"",error:a||"git status failed"};let l=o.trim().split(`
|
|
175
175
|
`),u=l[0]||"",f=l.slice(1).filter(Boolean);return{success:!0,output:[u,f.length?`${f.length} change(s):`:"Working tree clean",...f.map(p=>` ${p}`)].join(`
|
|
176
176
|
`)}}},{name:"git_diff",description:"Show a diff of changes. Optionally specify a file path. Use after writing files to review exactly what changed.",safety:"safe",parameters:{file:{type:"string",description:"Optional file path to diff (default: all changes)",required:!1},staged:{type:"boolean",description:"Show staged (--cached) diff (default: false)",required:!1}},execute:async o=>{if(!Vt(t))return{success:!0,output:"No git repository."};let a=o.staged?"--cached ":"",c=o.file?` -- "${o.file}"`:"",{out:l,err:u,code:f}=await it(`git diff ${a}--stat${c}`,t);if(f!==0)return{success:!1,output:"",error:u};let{out:p}=await it(`git diff ${a}${c}`,t);return{success:!0,output:[l.trim(),"",p.slice(0,6e3)].join(`
|
|
177
|
-
`).trim()||"No changes found."}}},{name:"git_log",description:"Show recent git commit history. Useful for understanding project evolution and finding a good rollback point.",safety:"safe",parameters:{count:{type:"number",description:"Number of commits to show (default: 10)",required:!1},file:{type:"string",description:"Show history for a specific file",required:!1}},execute:async o=>{if(!Vt(t))return{success:!0,output:"No git repository."};let a=Math.min(o.count||10,40),c=o.file?` -- "${o.file}"`:"",{out:l,err:u,code:f}=await it(`git log --oneline --decorate -${a}${c}`,t);return f!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"No commits yet."}}},{name:"git_commit",description:"Stage all changes and commit with a message. Only do this when the user explicitly asks to commit.",safety:"confirm",parameters:{message:{type:"string",description:"Commit message",required:!0},files:{type:"string",description:"Specific files to stage (default: all changes via git add -A)",required:!1}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.message.trim();if(!a)return{success:!1,output:"",error:"Commit message is required."};let c=o.files?`git add ${o.files}`:"git add -A",{err:l,code:u}=await it(c,t);if(u!==0)return{success:!1,output:"",error:`Stage failed: ${l}`};let{out:f,err:p,code:h}=await it(`git commit -m "${a.replace(/"/g,'\\"')}"`,t);return h!==0?{success:!1,output:"",error:`Commit failed: ${p}`}:{success:!0,output:f.trim()}}},{name:"git_stash",description:"Stash current changes (git stash) or restore them (git stash pop). Use to safely save work before a risky change.",safety:"confirm",parameters:{action:{type:"string",description:'"stash" to save changes, "pop" to restore last stash, "list" to see stashes',required:!0}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.action.toLowerCase(),c="";if(a==="stash")c='git stash push -u -m "hablas-auto-stash"';else if(a==="pop")c="git stash pop";else if(a==="list")c="git stash list";else return{success:!1,output:"",error:"action must be: stash | pop | list"};let{out:l,err:u,code:f}=await it(c,t);return f!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"Done."}}}]}var Y=k(require("fs")),me=k(require("path"));var
|
|
177
|
+
`).trim()||"No changes found."}}},{name:"git_log",description:"Show recent git commit history. Useful for understanding project evolution and finding a good rollback point.",safety:"safe",parameters:{count:{type:"number",description:"Number of commits to show (default: 10)",required:!1},file:{type:"string",description:"Show history for a specific file",required:!1}},execute:async o=>{if(!Vt(t))return{success:!0,output:"No git repository."};let a=Math.min(o.count||10,40),c=o.file?` -- "${o.file}"`:"",{out:l,err:u,code:f}=await it(`git log --oneline --decorate -${a}${c}`,t);return f!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"No commits yet."}}},{name:"git_commit",description:"Stage all changes and commit with a message. Only do this when the user explicitly asks to commit.",safety:"confirm",parameters:{message:{type:"string",description:"Commit message",required:!0},files:{type:"string",description:"Specific files to stage (default: all changes via git add -A)",required:!1}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.message.trim();if(!a)return{success:!1,output:"",error:"Commit message is required."};let c=o.files?`git add ${o.files}`:"git add -A",{err:l,code:u}=await it(c,t);if(u!==0)return{success:!1,output:"",error:`Stage failed: ${l}`};let{out:f,err:p,code:h}=await it(`git commit -m "${a.replace(/"/g,'\\"')}"`,t);return h!==0?{success:!1,output:"",error:`Commit failed: ${p}`}:{success:!0,output:f.trim()}}},{name:"git_stash",description:"Stash current changes (git stash) or restore them (git stash pop). Use to safely save work before a risky change.",safety:"confirm",parameters:{action:{type:"string",description:'"stash" to save changes, "pop" to restore last stash, "list" to see stashes',required:!0}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.action.toLowerCase(),c="";if(a==="stash")c='git stash push -u -m "hablas-auto-stash"';else if(a==="pop")c="git stash pop";else if(a==="list")c="git stash list";else return{success:!1,output:"",error:"action must be: stash | pop | list"};let{out:l,err:u,code:f}=await it(c,t);return f!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"Done."}}}]}var Y=k(require("fs")),me=k(require("path"));var Ms=class{entries=[];sessionDir;constructor(e){this.sessionDir=me.join(e,".hablas","rollback",`session_${Date.now()}`),Y.mkdirSync(this.sessionDir,{recursive:!0})}backup(e){let n=Y.existsSync(e);if(n){let r=me.join(this.sessionDir,Buffer.from(e).toString("base64")+".bak");Y.copyFileSync(e,r),this.entries.push({originalPath:e,backupPath:r,existed:n})}else this.entries.push({originalPath:e,backupPath:"",existed:!1})}rollback(){let e=[],n=[],r=[];for(let s of[...this.entries].reverse())try{s.existed&&s.backupPath?(Y.mkdirSync(me.dirname(s.originalPath),{recursive:!0}),Y.copyFileSync(s.backupPath,s.originalPath),e.push(s.originalPath)):!s.existed&&Y.existsSync(s.originalPath)&&(Y.unlinkSync(s.originalPath),n.push(s.originalPath))}catch(i){r.push(`${s.originalPath}: ${i.message}`)}return{restored:e,deleted:n,errors:r}}getBackedUpFiles(){return this.entries.map(e=>e.originalPath)}},Ps=new Map;function sl(t){return Ps.has(t)||Ps.set(t,new Ms(t)),Ps.get(t)}function il(t){return[{name:"atomic_write",description:"Write multiple files in a single atomic operation with automatic rollback. If ANY file fails to write, ALL previously written files are automatically restored to their original state. Use this for multi-file changes that must succeed together (e.g. rename a type across 5 files).",safety:"confirm",parameters:{files:{type:"string",description:'JSON array of {path, content} objects. Example: [{"path":"src/a.ts","content":"..."},{"path":"src/b.ts","content":"..."}]',required:!0},description:{type:"string",description:"Short description of what this atomic operation does (for logging)",required:!1}},execute:async s=>{let i;try{if(i=JSON.parse(s.files),!Array.isArray(i)||!i.every(c=>c.path&&typeof c.content=="string"))throw new Error("Invalid format \u2014 expected array of {path, content}")}catch(c){return{success:!1,output:"",error:`Invalid files JSON: ${c.message}`}}let o=sl(t),a=[];try{for(let{path:l}of i){let u=me.resolve(t,l);o.backup(u)}for(let{path:l,content:u}of i){let f=me.resolve(t,l);Y.mkdirSync(me.dirname(f),{recursive:!0}),Y.writeFileSync(f,u,"utf-8"),a.push(l)}return{success:!0,output:[`Atomic write successful${s.description?` (${s.description})`:""}`,`Written ${a.length} files:`,...a.map(l=>` \u2713 ${l}`)].join(`
|
|
178
178
|
`)}}catch(c){let l=o.rollback();return{success:!1,output:"",error:[`Atomic write FAILED at: ${c.message}`,`Rolled back ${l.restored.length} files.`,a.length>0?`Was writing: ${a.join(", ")}`:"",l.errors.length?`Rollback errors: ${l.errors.join("; ")}`:""].filter(Boolean).join(`
|
|
179
|
-
`)}}}},{name:"diff_preview",description:"Preview what a file would look like AFTER a change, shown as a unified diff. Use before writing to verify the change is correct. Does NOT write anything.",safety:"safe",parameters:{path:{type:"string",description:"File path to preview the change for",required:!0},new_content:{type:"string",description:"The proposed new content of the file",required:!0}},execute:async
|
|
179
|
+
`)}}}},{name:"diff_preview",description:"Preview what a file would look like AFTER a change, shown as a unified diff. Use before writing to verify the change is correct. Does NOT write anything.",safety:"safe",parameters:{path:{type:"string",description:"File path to preview the change for",required:!0},new_content:{type:"string",description:"The proposed new content of the file",required:!0}},execute:async s=>{let i=s.path,o=s.new_content,a=me.resolve(t,i),c="";if(Y.existsSync(a))try{c=Y.readFileSync(a,"utf-8")}catch{}else return{success:!0,output:`[New file: ${i}]
|
|
180
180
|
+++ ${o.split(`
|
|
181
181
|
`).slice(0,40).map(d=>"+ "+d).join(`
|
|
182
182
|
`)}`};if(c===o)return{success:!0,output:`No changes \u2014 content is identical to ${i}`};let l=Bt(i,c,o),u=c.split(`
|
|
183
183
|
`).length,f=o.split(`
|
|
184
184
|
`).length,p=f-u,h=p>=0?`+${p}`:`${p}`;return{success:!0,output:[`Diff preview: ${i} (${u} \u2192 ${f} lines, ${h})`,"",l.slice(0,5e3),l.length>5e3?"... [diff truncated]":""].filter(Boolean).join(`
|
|
185
|
-
`)}}},{name:"rollback_session",description:"EMERGENCY ROLLBACK: Restore all files modified in this session to their state before any changes were made. Use when something went wrong and you need to undo everything.",safety:"dangerous",parameters:{confirm:{type:"string",description:'Type "ROLLBACK" to confirm you want to restore all files',required:!0}},execute:async
|
|
185
|
+
`)}}},{name:"rollback_session",description:"EMERGENCY ROLLBACK: Restore all files modified in this session to their state before any changes were made. Use when something went wrong and you need to undo everything.",safety:"dangerous",parameters:{confirm:{type:"string",description:'Type "ROLLBACK" to confirm you want to restore all files',required:!0}},execute:async s=>{if(s.confirm!=="ROLLBACK")return{success:!1,output:"",error:'Rollback cancelled. Type "ROLLBACK" as the confirm value to proceed.'};let o=sl(t).rollback();return{success:!0,output:["Session rollback complete.",`Restored: ${o.restored.length} files`,`Deleted: ${o.deleted.length} new files`,o.errors.length?`Errors: ${o.errors.join("; ")}`:"","",o.restored.map(a=>` \u21A9 ${me.relative(t,a)}`).join(`
|
|
186
186
|
`)].filter(Boolean).join(`
|
|
187
|
-
`)}}}]}var L=k(require("fs")),V=k(require("path")),
|
|
188
|
-
`)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let i=
|
|
189
|
-
`)}}},{name:"checkpoint_restore",description:"Restore a named checkpoint, overwriting current files with the saved state. This is DESTRUCTIVE \u2014 current unsaved changes will be lost. Use checkpoint_list to see available names.",safety:"dangerous",parameters:{name:{type:"string",description:"Checkpoint name to restore",required:!0},confirm:{type:"string",description:'Type "RESTORE" to confirm destructive operation',required:!0}},execute:async i=>{if(i.confirm!=="RESTORE")return{success:!1,output:"",error:'Restore cancelled. Set confirm="RESTORE" to proceed.'};let o=
|
|
190
|
-
`)}}},{name:"checkpoint_diff",description:"Show which files changed since a checkpoint was saved (without restoring).",safety:"safe",parameters:{name:{type:"string",description:"Checkpoint name to compare against",required:!0}},execute:async i=>{let o=
|
|
191
|
-
`)}}}]}var
|
|
192
|
-
`)[0]}`)}return t.total===0&&(
|
|
193
|
-
`)}function
|
|
194
|
-
`+u).trim(),p=
|
|
187
|
+
`)}}}]}var L=k(require("fs")),V=k(require("path")),al=require("child_process"),Sg=new Set(["node_modules",".git","dist","build",".next",".hablas","__pycache__",".cache","coverage"]),vg=500*1024,_g=20*1024*1024;function Fs(t){let e=V.join(t,".hablas","checkpoints");return L.existsSync(e)||L.mkdirSync(e,{recursive:!0}),e}function cl(t){return V.join(t,".hablas","checkpoints","_index.json")}function ol(t){let e=cl(t);if(L.existsSync(e))try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{}return{version:1,checkpoints:[]}}function kg(t,e){L.writeFileSync(cl(t),JSON.stringify(e,null,2),"utf-8")}function Ds(t,e){let n=[];try{let r=L.readdirSync(t,{withFileTypes:!0});for(let s of r){if(Sg.has(s.name)||s.name.startsWith("."))continue;let i=V.join(t,s.name);if(s.isDirectory())n.push(...Ds(i,e));else try{L.statSync(i).size<=vg&&n.push(V.relative(e,i))}catch{}}}catch{}return n}function Tg(t){return new Promise(e=>{(0,al.exec)("git rev-parse --short HEAD",{cwd:t},(n,r)=>{e(n?void 0:r.trim())})})}function Ls(t){return t.toLowerCase().replace(/[^a-z0-9_-]/g,"-").replace(/-+/g,"-").slice(0,40)}function ll(t){return[{name:"checkpoint_save",description:'Save a named checkpoint of the current workspace state. Useful before risky refactors: "save checkpoint before-auth-refactor". Can be restored later with checkpoint_restore.',safety:"safe",parameters:{name:{type:"string",description:'Short name for this checkpoint (e.g. "before-refactor", "v1-stable")',required:!0},description:{type:"string",description:"What state is being saved and why",required:!1}},execute:async i=>{let o=i.name.trim(),a=Ls(o),c=i.description||"",l=Fs(t),u=V.join(l,a);L.existsSync(u)&&L.rmSync(u,{recursive:!0}),L.mkdirSync(u,{recursive:!0});let f=Ds(t,t),p=await Tg(t),h=0,d=[];for(let y of f){if(h>=_g)break;try{let b=V.join(t,y),w=V.join(u,y);L.mkdirSync(V.dirname(w),{recursive:!0});let v=L.readFileSync(b);L.writeFileSync(w,v),h+=v.length,d.push(y)}catch{}}let m={name:a,createdAt:new Date().toISOString(),description:c,files:d,gitSha:p,totalBytes:h};L.writeFileSync(V.join(u,"_meta.json"),JSON.stringify(m,null,2));let g=ol(t);return g.checkpoints=g.checkpoints.filter(y=>y.name!==a),g.checkpoints.unshift(m),g.checkpoints.length>20&&(g.checkpoints=g.checkpoints.slice(0,20)),kg(t,g),{success:!0,output:[`Checkpoint saved: "${a}"`,`Files: ${d.length} \xB7 Size: ${(h/1024).toFixed(0)} KB`,p?`Git: ${p}`:"",c?`Note: ${c}`:""].filter(Boolean).join(`
|
|
188
|
+
`)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let i=ol(t);if(!i.checkpoints.length)return{success:!0,output:"No checkpoints saved yet. Use checkpoint_save to create one."};let o=["Saved Checkpoints:",""];for(let a of i.checkpoints){let c=new Date(a.createdAt).toLocaleString();o.push(` "${a.name}" \u2014 ${c}`),o.push(` ${a.files.length} files \xB7 ${(a.totalBytes/1024).toFixed(0)} KB`),a.description&&o.push(` ${a.description}`),a.gitSha&&o.push(` git: ${a.gitSha}`),o.push("")}return{success:!0,output:o.join(`
|
|
189
|
+
`)}}},{name:"checkpoint_restore",description:"Restore a named checkpoint, overwriting current files with the saved state. This is DESTRUCTIVE \u2014 current unsaved changes will be lost. Use checkpoint_list to see available names.",safety:"dangerous",parameters:{name:{type:"string",description:"Checkpoint name to restore",required:!0},confirm:{type:"string",description:'Type "RESTORE" to confirm destructive operation',required:!0}},execute:async i=>{if(i.confirm!=="RESTORE")return{success:!1,output:"",error:'Restore cancelled. Set confirm="RESTORE" to proceed.'};let o=Ls(i.name.trim()),a=Fs(t),c=V.join(a,o);if(!L.existsSync(c))return{success:!1,output:"",error:`Checkpoint "${o}" not found. Run checkpoint_list to see available names.`};let l=V.join(c,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(l,"utf-8"))}catch{return{success:!1,output:"",error:"Checkpoint metadata is corrupt."}}let f=[],p=[];for(let h of u.files)try{let d=V.join(c,h),m=V.join(t,h);if(!L.existsSync(d))continue;L.mkdirSync(V.dirname(m),{recursive:!0}),L.copyFileSync(d,m),f.push(h)}catch(d){p.push(`${h}: ${d.message}`)}return{success:!0,output:[`Checkpoint "${o}" restored.`,`Restored: ${f.length} files`,u.gitSha?`Saved at git: ${u.gitSha}`:"",u.description?`Original note: ${u.description}`:"",p.length?`Errors (${p.length}): ${p.slice(0,3).join("; ")}`:""].filter(Boolean).join(`
|
|
190
|
+
`)}}},{name:"checkpoint_diff",description:"Show which files changed since a checkpoint was saved (without restoring).",safety:"safe",parameters:{name:{type:"string",description:"Checkpoint name to compare against",required:!0}},execute:async i=>{let o=Ls(i.name.trim()),a=Fs(t),c=V.join(a,o);if(!L.existsSync(c))return{success:!1,output:"",error:`Checkpoint "${o}" not found.`};let l=V.join(c,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(l,"utf-8"))}catch{return{success:!1,output:"",error:"Corrupt checkpoint metadata."}}let f=[],p=[],h=[];for(let y of u.files){let b=V.join(c,y),w=V.join(t,y);if(!L.existsSync(w)){p.push(y);continue}try{let v=L.readFileSync(b),_=L.readFileSync(w);v.equals(_)||f.push(y)}catch{}}let d=Ds(t,t),m=new Set(u.files);for(let y of d)m.has(y)||h.push(y);if(!f.length&&!p.length&&!h.length)return{success:!0,output:`No changes since checkpoint "${o}".`};let g=[`Changes since checkpoint "${o}" (${new Date(u.createdAt).toLocaleString()}):`,""];return f.length&&(g.push(` Modified (${f.length}):`),f.forEach(y=>g.push(` M ${y}`))),h.length&&(g.push(` Added (${h.length}):`),h.slice(0,20).forEach(y=>g.push(` + ${y}`))),p.length&&(g.push(` Deleted (${p.length}):`),p.forEach(y=>g.push(` - ${y}`))),{success:!0,output:g.join(`
|
|
191
|
+
`)}}}]}var fl=require("child_process"),$e=k(require("fs")),te=k(require("path")),zt=[{name:"vitest",command:"npx vitest run",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"jest",command:"npx jest --no-coverage",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"mocha",command:"npx mocha",coverageFlag:"--reporter=json",filePattern:/\.(test|spec)\.(ts|js)$/},{name:"pytest",command:"python -m pytest -v",coverageFlag:"--cov=.",filePattern:/test_.*\.py$|.*_test\.py$/},{name:"go test",command:"go test ./...",coverageFlag:"-cover",filePattern:/.*_test\.go$/}];function Ns(t){try{let e=JSON.parse($e.readFileSync(te.join(t,"package.json"),"utf-8")),n={...e.dependencies,...e.devDependencies};if(n.vitest)return zt[0];if(n.jest||e.scripts?.test?.includes("jest"))return zt[1];if(n.mocha)return zt[2]}catch{}return $e.existsSync(te.join(t,"pytest.ini"))||$e.existsSync(te.join(t,"pyproject.toml"))?zt[3]:$e.existsSync(te.join(t,"go.mod"))?zt[4]:null}function Cg(t,e){let n={passed:0,failed:0,skipped:0,total:0,failures:[],duration:0,raw:t};if(e==="vitest"||e==="jest"){let r=t.match(/Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+passed,\s+)?(\d+)\s+total/);r&&(n.failed=parseInt(r[1]||"0"),n.passed=parseInt(r[2]||"0"),n.total=parseInt(r[3]||"0"),n.skipped=n.total-n.passed-n.failed);let s=t.match(/Duration\s+([\d.]+)s/);s&&(n.duration=parseFloat(s[1])*1e3);let i=/● (.+?)\n\n([\s\S]*?)(?=●|\n\nTest Suites:|$)/g,o;for(;(o=i.exec(t))!==null;)n.failures.push({test:o[1].trim(),message:o[2].trim().slice(0,300)})}else if(e==="pytest"){let r=t.match(/(\d+)\s+passed(?:,\s+(\d+)\s+failed)?/);r&&(n.passed=parseInt(r[1]||"0"),n.failed=parseInt(r[2]||"0"),n.total=n.passed+n.failed);let s=t.match(/in\s+([\d.]+)s/);s&&(n.duration=parseFloat(s[1])*1e3)}return n.total===0&&n.passed===0&&(n.passed=(t.match(/✓|PASS|passed/gi)||[]).length,n.failed=(t.match(/✗|FAIL|failed/gi)||[]).length,n.total=n.passed+n.failed),n}function $g(t,e){let r=[`${t.failed===0?"\u2713 ALL PASSING":`\u2717 ${t.failed} FAILING`} \u2014 ${e}`,` Passed: ${t.passed} Failed: ${t.failed} Skipped: ${t.skipped} Total: ${t.total}`,t.duration?` Duration: ${(t.duration/1e3).toFixed(2)}s`:""].filter(Boolean);if(t.failures.length){r.push(""),r.push("Failed tests:");for(let s of t.failures.slice(0,5))r.push(` \u2717 ${s.test}`),s.message&&r.push(` ${s.message.split(`
|
|
192
|
+
`)[0]}`)}return t.total===0&&(r.push(""),r.push("Raw output (could not parse structured results):"),r.push(t.raw.slice(0,800))),r.join(`
|
|
193
|
+
`)}function ul(t,e,n=6e4){return new Promise(r=>{(0,fl.exec)(t,{cwd:e,timeout:n,maxBuffer:8*1024*1024},(s,i,o)=>{let a=s?s.code:void 0;r({out:i||"",err:o||"",code:typeof a=="number"?a:s?1:0})})})}function dl(t){return[{name:"run_tests",description:"Run the project test suite. Auto-detects Jest, Vitest, Pytest, or Go test. Parses results and shows pass/fail counts and failure details.",safety:"safe",parameters:{filter:{type:"string",description:"Run only tests matching this pattern/file (optional)",required:!1},timeout:{type:"number",description:"Timeout in seconds (default: 60)",required:!1}},execute:async s=>{let i=Ns(t);if(!i)return{success:!0,output:"No test runner detected. Install Jest, Vitest, Pytest, or use Go modules."};let o=s.filter?` ${s.filter}`:"",a=(s.timeout||60)*1e3,c=`${i.command}${o}`,{out:l,err:u}=await ul(c,t,a),f=(l+`
|
|
194
|
+
`+u).trim(),p=Cg(f,i.name),h=$g(p,i.name);return{success:p.failed===0,output:h,error:p.failed>0?`${p.failed} test(s) failing`:void 0}}},{name:"test_coverage",description:"Run tests with coverage report. Shows which files/lines are covered. Uses the project's configured test runner.",safety:"safe",parameters:{},execute:async()=>{let s=Ns(t);if(!s)return{success:!0,output:"No test runner detected."};let i=`${s.command} ${s.coverageFlag}`,{out:o,err:a}=await ul(i,t,12e4),c=(o+`
|
|
195
195
|
`+a).trim(),l=/(?:All files|TOTAL|coverage)\s*\|\s*([\d.]+)/i,u=c.match(l),f=u?`Overall coverage: ${u[1]}%`:"Coverage data generated.",p=c.indexOf("-------"),h=p>=0?c.slice(p,p+2e3):"";return{success:!0,output:[f,h||c.slice(-1500)].filter(Boolean).join(`
|
|
196
196
|
|
|
197
|
-
`)}}},{name:"tdd_scaffold",description:"Generate a test file scaffold for a function/module BEFORE implementing it. Used to enforce TDD workflow: write the test first, then implement.",safety:"safe",parameters:{target_file:{type:"string",description:'The file you plan to implement (e.g. "src/utils/auth.ts")',required:!0},functions:{type:"string",description:"Comma-separated list of function/class names to generate tests for",required:!0},test_framework:{type:"string",description:'Override framework: "jest" | "vitest" | "pytest" (auto-detected if omitted)',required:!1}},execute:async
|
|
197
|
+
`)}}},{name:"tdd_scaffold",description:"Generate a test file scaffold for a function/module BEFORE implementing it. Used to enforce TDD workflow: write the test first, then implement.",safety:"safe",parameters:{target_file:{type:"string",description:'The file you plan to implement (e.g. "src/utils/auth.ts")',required:!0},functions:{type:"string",description:"Comma-separated list of function/class names to generate tests for",required:!0},test_framework:{type:"string",description:'Override framework: "jest" | "vitest" | "pytest" (auto-detected if omitted)',required:!1}},execute:async s=>{let i=s.target_file,o=s.functions.split(",").map(m=>m.trim()).filter(Boolean),a=te.extname(i),c=te.basename(i,a),l=te.dirname(i),u=Ns(t),f=s.test_framework||u?.name||"jest",p="",h="";if(f==="pytest")h=te.join(l,`test_${c}.py`),p=[`"""Tests for ${i} \u2014 TDD scaffold (generated by Hablas)"""
|
|
198
198
|
`,"import pytest",`from ${l.replace(/\//g,".")}.${c} import ${o.join(", ")}
|
|
199
199
|
`,...o.map(m=>[`class Test${m.charAt(0).toUpperCase()+m.slice(1)}:`,` """Tests for ${m}"""
|
|
200
200
|
`,` def test_${m}_returns_expected(self):`," # Arrange"," # Act",` result = ${m}()`," # Assert",' assert result is not None, "Expected a result"',"",` def test_${m}_handles_invalid_input(self):`," # Arrange / Act / Assert"," with pytest.raises((ValueError, TypeError)):",` ${m}(None) # type: ignore`,""].join(`
|
|
@@ -203,44 +203,44 @@ Notes:
|
|
|
203
203
|
`,...o.map(y=>[`describe('${y}', () => {`," // RED: These tests should FAIL until implementation is written",""," it('should return a valid result', () => {"," // Arrange"," // Act",` const result = ${y}();`," // Assert"," expect(result).toBeDefined();"," });",""," it('should handle edge cases gracefully', () => {",` // TODO: define edge cases for ${y}`,` expect(() => ${y}(null as any)).not.toThrow();`," });",""," it('should match the expected contract', () => {",` // TODO: define the exact contract/interface for ${y}`,` // Example: expect(${y}(input)).toEqual(expectedOutput);`," expect(true).toBe(false); // Replace with real assertion"," });","});",""].join(`
|
|
204
204
|
`))].join(`
|
|
205
205
|
`)}let d=te.resolve(t,h);return $e.mkdirSync(te.dirname(d),{recursive:!0}),$e.writeFileSync(d,p,"utf-8"),{success:!0,output:[`TDD scaffold created: ${h}`,`Functions scaffolded: ${o.join(", ")}`,`Framework: ${f}`,"","Next steps (TDD red-green-refactor):"," 1. Run tests \u2192 confirm they FAIL (red)"," 2. Write minimal implementation in: "+i," 3. Run tests again \u2192 confirm they PASS (green)"," 4. Refactor if needed, run once more"].join(`
|
|
206
|
-
`)}}}]}var xt=k(require("fs")),ge=k(require("path"))
|
|
207
|
-
`).length;let v=
|
|
208
|
-
`)}}}}var St=class{tools=new Map;constructor(e,n){let
|
|
206
|
+
`)}}}]}var xt=k(require("fs")),ge=k(require("path")),Eg=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage"]),Ag=new Set([".ts",".tsx",".js",".jsx",".mjs",".py",".go",".rs",".java",".md",".json",".yaml",".yml",".toml"]),Og=500,Rg=8e3;function pl(t){return t.toLowerCase().replace(/[^a-z0-9\u0600-\u06FF]/g," ").split(/\s+/).filter(e=>e.length>2)}function hl(t,e){let n=0;for(let r of t)e.has(r)&&n++;return t.size>0?n/t.size:0}function Ig(t,e){let n=new Set(t.toLowerCase().replace(/[/_-]/g," ").split(/\s+/).filter(r=>r.length>1));return hl(e,n)}function jg(t,e){let r=(e-t)/(1e3*60*60*24);return r<1?1:r<7?.5:r<30?.2:.05}function Pg(t,e){if(e.size===0)return 0;let n=new Set(pl(t.slice(0,Rg)));return hl(e,n)}function Mg(t){return/\b(index|main|app|server|cli|entry)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/.test(t)}function ml(t,e,n=[]){if(n.length>=Og)return n;try{let r=xt.readdirSync(t,{withFileTypes:!0});for(let s of r){if(Eg.has(s.name)||s.name.startsWith("."))continue;let i=ge.join(t,s.name);if(s.isDirectory())ml(i,e,n);else if(Ag.has(ge.extname(s.name)))try{let o=xt.statSync(i);if(o.size>200*1024)continue;let a=ge.relative(e,i);n.push({path:a,mtime:o.mtimeMs,size:o.size,lines:0,isEntry:Mg(a)})}catch{}}}catch{}return n}function Fg(t){let e=Date.now(),{query:n,workingDir:r,topK:s=12,recentlyTouched:i=[],importantFiles:o=[],skipContentScan:a=!1}=t,c=new Set(pl(n)),l=new Set(i.map(d=>ge.normalize(d))),u=new Set(o.map(d=>ge.normalize(d))),f=Date.now(),p=ml(r,r),h=[];for(let d of p){let m=[],g=0,y=Ig(d.path,c)*.35;y>.1&&(g+=y,m.push(`name-match(${(y*100).toFixed(0)}%)`));let b=jg(d.mtime,f)*.2;if(b>.05&&(g+=b,m.push(`fresh(${(b*100).toFixed(0)}%)`)),l.has(ge.normalize(d.path))&&(g+=.25,m.push("touched-in-session")),u.has(ge.normalize(d.path))&&(g+=.15,m.push("high-centrality")),d.isEntry&&(g+=.05,m.push("entry-point")),!a&&c.size>0&&g>0)try{let w=xt.readFileSync(ge.join(r,d.path),"utf-8");d.lines=w.split(`
|
|
207
|
+
`).length;let v=Pg(w,c)*.3;v>.05&&(g+=v,m.push(`content-match(${(v*100).toFixed(0)}%)`))}catch{}(g>.02||m.length>0)&&h.push({path:d.path,score:Math.min(g,1),reasons:m.length?m:["low-relevance"],lines:d.lines,modifiedAt:d.mtime})}return h.sort((d,m)=>m.score-d.score),{files:h.slice(0,s),totalCandidates:p.length,buildTimeMs:Date.now()-e}}function gl(t){return{name:"suggest_relevant_files",description:"Given your current task/query, rank the project files by relevance and return the top candidates to read first. Use this at the START of complex tasks to avoid reading the wrong files.",safety:"safe",parameters:{query:{type:"string",description:"Description of the task \u2014 used to find relevant files",required:!0},top_k:{type:"number",description:"Number of files to return (default: 12)",required:!1}},execute:async e=>{let n=Fg({query:e.query,workingDir:t,topK:e.top_k||12,skipContentScan:!1});if(!n.files.length)return{success:!0,output:"No relevant files found. The project may be empty or all files are excluded."};let r=[`Top ${n.files.length} relevant files for: "${e.query}"`,`(scanned ${n.totalCandidates} files in ${n.buildTimeMs}ms)`,""];for(let s of n.files){let i=(s.score*100).toFixed(0).padStart(3);r.push(` [${i}%] ${s.path}${s.lines?` (${s.lines}L)`:""}`),r.push(` ${s.reasons.join(" \xB7 ")}`)}return{success:!0,output:r.join(`
|
|
208
|
+
`)}}}}var St=class{tools=new Map;constructor(e,n){let r=lc(e);for(let s of r)this.tools.set(s.name,s);this.tools.set("run_command",hc(e,n)),this.tools.set("search_codebase",mc(e)),this.tools.set("detect_bugs",wc(e)),this.tools.set("web_search",kc());for(let s of _c())this.tools.set(s.name,s);for(let s of Oc(e))this.tools.set(s.name,s);for(let s of Lc())this.tools.set(s.name,s);this.tools.set("download_asset",Wc(e));for(let s of Xc(e,n))this.tools.set(s.name,s);for(let s of Zc(e))this.tools.set(s.name,s);for(let s of rl(e))this.tools.set(s.name,s);for(let s of il(e))this.tools.set(s.name,s);for(let s of ll(e))this.tools.set(s.name,s);for(let s of dl(e))this.tools.set(s.name,s);this.tools.set("suggest_relevant_files",gl(e))}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let n=this.tools.get(e.name);return n?n.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let n={},r=[];for(let[s,i]of Object.entries(e.parameters))n[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&r.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:n,required:r}}}})}getToolDescriptions(){return this.getAll().map(n=>{let r=Object.entries(n.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
|
|
209
209
|
`);return`- ${n.name} [${n.safety}]: ${n.description}
|
|
210
|
-
${
|
|
210
|
+
${r}`}).join(`
|
|
211
211
|
|
|
212
|
-
`)}};var
|
|
213
|
-
... [truncated to fit context budget]`}var vt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,n,
|
|
214
|
-
${c}`),
|
|
215
|
-
${o.content}`),
|
|
212
|
+
`)}};var yl=k(require("crypto"));function Us(t){return Math.ceil(t.length/3.5)}function Kt(t,e){let n=Math.floor(e*3.5);return t.length<=n?t:t.slice(0,n)+`
|
|
213
|
+
... [truncated to fit context budget]`}var vt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,n,r){let s=this.computeHash(n),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=Us(n),a=r?.importance??this.autoImportance(e,n);this.usedTokens+o>this.budget&&this.evictToFit(o);let c={path:e,content:n,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:r?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,c),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,n){let r=this.cache.get(e);return r?r.hash!==this.computeHash(n):!0}buildContext(e){let n=e||this.budget,r=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of r){if(s+o.tokenCount>n){if(o.importance>=7){let a=n-s;if(a>200){let c=Kt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
214
|
+
${c}`),s+=a}}continue}i.push(`--- ${o.path} ---
|
|
215
|
+
${o.content}`),s+=o.tokenCount}return i.join(`
|
|
216
216
|
|
|
217
|
-
`)}buildAgentContext(e,n){let
|
|
217
|
+
`)}buildAgentContext(e,n){let r=n||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(l=>i.length===0?!0:i.some(u=>l.path.includes(u))).sort((l,u)=>this.computeScore(u)-this.computeScore(l)),a=0,c=[];for(let l of o){if(a+l.tokenCount>r)break;c.push(`--- ${l.path} ---
|
|
218
218
|
${l.content}`),a+=l.tokenCount}return c.join(`
|
|
219
219
|
|
|
220
|
-
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,n)=>n.importance-e.importance)}evictToFit(e){let n=Array.from(this.cache.entries()).map(([
|
|
220
|
+
`)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,n)=>n.importance-e.importance)}evictToFit(e){let n=Array.from(this.cache.entries()).map(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),r=0;for(let s of n){if(r>=e)break;s.importance>=9||(r+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,n){let r=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(r=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(r=3);let s=Us(n);return s>2e3&&(r=Math.max(1,r-1)),s>5e3&&(r=Math.max(1,r-2)),r}autoTag(e){let n=[];return/\.(ts|tsx)$/.test(e)&&n.push("typescript"),/\.(js|jsx)$/.test(e)&&n.push("javascript"),/\.json$/.test(e)&&n.push("config"),/\.md$/.test(e)&&n.push("documentation"),/\.(css|scss|sass)$/.test(e)&&n.push("style"),/\.(test|spec)\./i.test(e)&&n.push("test"),/src\//.test(e)&&n.push("source"),n}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let n=this.accessHistory[this.accessHistory.length-1];if(n&&Date.now()-this.getGroupTime(n)<3e4){if(!n.includes(e)){n.push(e);for(let r of n)if(r!==e){let s=this.cache.get(r);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return yl.createHash("md5").update(e).digest("hex")}};var Lg=0;function Gt(){return`msg_${Date.now()}_${++Lg}`}function _t(t){return Math.ceil(t.length/4)}var kt=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,n=200,r=128e3){this.maxMessages=n,this.maxTokens=r,this.sessionId=`session_${Date.now()}`;let s=_t(e);this.messages.push({id:Gt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,n){let r=Gt(),s=_t(e);return this.messages.push({id:r,role:"user",content:e,timestamp:Date.now(),priority:n?.priority||"high",tokenEstimate:s,compressed:!1,tags:n?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),r}addAssistantMessage(e,n,r){let s=Gt(),i=_t(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:r||"hablas",tokenEstimate:i,compressed:!1,tags:r?[`agent:${r}`]:["assistant"]};return n&&n.length>0&&(o.tool_calls=n,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,r&&this.agentMessageCounts.set(r,(this.agentMessageCounts.get(r)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,n){let r=Gt(),s=_t(e);return this.messages.push({id:r,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:n?[`tool:${n}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),r}getMessages(){return this.messages.map(e=>{let n={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(n.tool_calls=e.tool_calls),n})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(n=>n.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let n=_t(e),r={id:Gt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:n,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[r],this.recalculateTokens();return}this.messages[0]=r,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let n={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(r=>({...r})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(n),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),n.id}rollback(e){let n=this.snapshots.find(r=>r.id===e);return n?(this.messages=n.messages.map(r=>({...r})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,n){let r=this.messages.length,s=new t(n,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:r,session:s}),s}mergeFork(e,n){let r=this.forks.get(e);if(!r)return!1;let s=r.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(n)this.addAssistantMessage(`[Agent @${e} result]: ${n}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let n=e.toLowerCase();return this.messages.filter(r=>r.content.toLowerCase().includes(n))}getMessagesByTag(e){return this.messages.filter(n=>n.tags.includes(e))}getLastByRole(e,n=1){return this.messages.filter(r=>r.role===e).slice(-n)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(n=>n.role==="tool"&&!n.compressed&&n.tokenEstimate>200);for(let n of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let n=this.messages.filter(r=>r.role==="assistant"&&!r.compressed&&r.priority!=="critical"&&r.tokenEstimate>300);for(let r of n.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}}if(this.messages.length>this.maxMessages){let n=this.messages[0],r=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=r.sort((o,a)=>{let c=s[a.priority]-s[o.priority];return c!==0?c:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[n,...i],this.recalculateTokens()}}compressMessage(e){let n=e.content.length,r=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,1200)+`
|
|
221
221
|
...(compressed from `+n+" chars)":e.content=e.content.slice(0,800)+`
|
|
222
|
-
...(compressed from `+n+" chars)",e.compressed=!0,e.originalLength=n,e.tokenEstimate=_t(e.content),this.totalTokens-=
|
|
223
|
-
`)}async function $t(t,e){let n=[],
|
|
224
|
-
`)}function
|
|
222
|
+
...(compressed from `+n+" chars)",e.compressed=!0,e.originalLength=n,e.tokenEstimate=_t(e.content),this.totalTokens-=r-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,n)=>e+n.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let n=JSON.parse(e);if(!n.messages||!Array.isArray(n.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=n.sessionId||`session_${Date.now()}`,this.messages=n.messages,this.totalTokens=n.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(n.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var Ct=k(require("fs")),wl=k(require("path"));var O=k(require("fs")),R=k(require("path"));function Dg(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let n=JSON.parse(O.readFileSync(e,"utf-8")),r={...n.dependencies,...n.devDependencies};if(r.next)return"next";if(r.nuxt)return"nuxt";if(r["@angular/core"])return"angular";if(r.svelte||r["@sveltejs/kit"])return"svelte";if(r.vue)return"vue";if(r.react)return"react";if(r["@nestjs/core"])return"nest";if(r.fastify)return"fastify";if(r.express)return"express"}catch{}if(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let n=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.join(t,"requirements.txt"),"utf-8"):"";if(n.includes("django"))return"django";if(n.includes("flask"))return"flask";if(n.includes("fastapi"))return"fastapi"}catch{}if(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Ng(t){return O.existsSync(R.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(R.join(t,"yarn.lock"))?"yarn":O.existsSync(R.join(t,"bun.lockb"))?"bun":O.existsSync(R.join(t,"package-lock.json"))?"npm":O.existsSync(R.join(t,"Cargo.toml"))?"cargo":O.existsSync(R.join(t,"go.mod"))?"go":O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml"))?"pip":"unknown"}function Ug(t){return O.existsSync(R.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(R.join(t,"package.json"))?"JavaScript":O.existsSync(R.join(t,"Cargo.toml"))?"Rust":O.existsSync(R.join(t,"go.mod"))?"Go":O.existsSync(R.join(t,"pyproject.toml"))||O.existsSync(R.join(t,"requirements.txt"))?"Python":"Unknown"}function qg(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let n=O.readFileSync(e,"utf-8").trim();return n.startsWith("ref: refs/heads/")?n.replace("ref: refs/heads/",""):n.substring(0,8)}catch{return null}}function Tt(t){let e=Dg(t),n=Ng(t),r=Ug(t),s=qg(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),c=O.existsSync(R.join(t,".git")),l=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)O.existsSync(R.join(t,m))&&l.push(m);let f=[],p=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of p)O.existsSync(R.join(t,m))&&f.push(m);let h=[],d=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of d)O.existsSync(R.join(t,m))&&h.push(m);return{rootPath:t,framework:e,packageManager:n,language:r,hasDocker:i,hasCICD:o,hasTests:a,hasGit:c,gitBranch:s,envFiles:l,configFiles:f,entryPoints:h}}function Un(t){let e=[` Project: ${R.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
|
|
223
|
+
`)}async function $t(t,e){let n=[],r=wl.join(t,"package.json");if(Ct.existsSync(r))try{let o=JSON.parse(Ct.readFileSync(r,"utf-8"));n.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&n.push(`Description: ${o.description}`)}catch{}let s=Tt(t);n.push(`Framework: ${s.framework}`),n.push(`Language: ${s.language}`),n.push(`Package Manager: ${s.packageManager}`),n.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Bg(t,16);return i.length>0&&n.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&n.push(`Env files: ${s.envFiles.join(", ")}`),n.push(`Directory: ${t}`),n.join(`
|
|
224
|
+
`)}function Bg(t,e){try{return Ct.readdirSync(t).filter(n=>!n.startsWith(".")).filter(n=>!["node_modules","dist","build",".next",".cache"].includes(n)).slice(0,e)}catch{return[]}}var oe=k(require("fs")),Ws=k(require("path")),vl=k(require("os")),_l=k(require("crypto")),Jt=Ws.join(vl.homedir(),".hablas"),qs=Ws.join(Jt,"memory.json"),bl=1,xl=2e3,Hg=1600,Wg=8e3;function Vg(){return _l.randomBytes(8).toString("hex")}function Sl(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function zg(t,e){let n=t+".tmp."+process.pid;oe.writeFileSync(n,e,"utf-8"),oe.renameSync(n,t)}var Hs=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(oe.existsSync(Jt)||oe.mkdirSync(Jt,{recursive:!0}),oe.existsSync(qs)){let e=JSON.parse(oe.readFileSync(qs,"utf-8"));if(e.version===bl)return e}}catch{}return{version:bl,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{oe.existsSync(Jt)||oe.mkdirSync(Jt,{recursive:!0}),zg(qs,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let n of e.tags)this.store.tagIndex[n]||(this.store.tagIndex[n]=[]),this.store.tagIndex[n].includes(e.id)||this.store.tagIndex[n].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 n of e.tags)this.store.tagIndex[n]&&(this.store.tagIndex[n]=this.store.tagIndex[n].filter(r=>r!==e.id),this.store.tagIndex[n].length||delete this.store.tagIndex[n]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(n=>n!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let n=this.store.keyIndex[e.key],r=Date.now(),s=e.value.slice(0,Wg);if(n&&this.store.entries[n]){let a=this.store.entries[n];return this.removeFromIndex(a),a.value=s,a.updatedAt=r,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=r+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=Vg(),o={id:i,kind:e.kind,key:e.key,value:s,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:r,updatedAt:r,accessCount:0,lastAccessed:r,ttl:e.ttl?r+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let n=this.store.keyIndex[e];if(!n)return null;let r=this.store.entries[n];return r?r.ttl&&Date.now()>r.ttl?(this.forget(e),null):(r.accessCount++,r.lastAccessed=Date.now(),this.scheduleFlush(),r):null}forget(e){let n=this.store.keyIndex[e];if(!n)return!1;let r=this.store.entries[n];return r?(this.removeFromIndex(r),delete this.store.entries[n],this.scheduleFlush(),!0):!1}search(e,n){let r=Date.now(),s=n?.limit??10,i=n?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(l=>l.length>2),c=[];for(let l of Object.values(this.store.entries)){if(l.ttl&&r>l.ttl||n?.kind&&l.kind!==n.kind||n?.project&&l.project!==n.project)continue;let u=0,f="value",p=l.key.toLowerCase(),h=l.value.toLowerCase();if(p===o)u=1,f="key";else if(p.includes(o))u=Math.max(u,.8),f="key";else if(l.tags.some(d=>d.toLowerCase().includes(o)))u=Math.max(u,.7),f="tag";else{let d=a.filter(m=>h.includes(m)).length;d>0&&(u=Math.max(u,d/Math.max(a.length,1)*.6),f="value")}u>0&&(u=Math.min(1,u+Sl(l.priority)*.05+Math.min(.1,l.accessCount*.01)),c.push({entry:l,score:u,matchedOn:f}))}return c.filter(l=>l.score>=i).sort((l,u)=>u.score-l.score).slice(0,s)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(n=>this.store.entries[n]).filter(n=>!!n&&(!n.ttl||Date.now()<n.ttl))}getByKind(e,n=20){return Object.values(this.store.entries).filter(r=>r.kind===e&&(!r.ttl||Date.now()<r.ttl)).sort((r,s)=>s.updatedAt-r.updatedAt).slice(0,n)}getRecent(e=10){return Object.values(this.store.entries).filter(n=>!n.ttl||Date.now()<n.ttl).sort((n,r)=>r.lastAccessed-n.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let n of Object.values(this.store.entries))e.total++,e[n.kind]=(e[n.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<xl)return;let n=Date.now();for(let r of Object.values(this.store.entries))r.ttl&&n>r.ttl&&(this.removeFromIndex(r),delete this.store.entries[r.id],e--);if(e>=xl){let r=Object.values(this.store.entries).map(s=>({id:s.id,score:Sl(s.priority)*10+s.accessCount+s.lastAccessed/1e12})).sort((s,i)=>s.score-i.score);for(let{id:s}of r.slice(0,e-Hg)){let i=this.store.entries[s];i&&(this.removeFromIndex(i),delete this.store.entries[s])}}}rememberProject(e,n){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${n.name}
|
|
225
225
|
Stack: ${n.stack}${n.summary?`
|
|
226
|
-
Summary: ${n.summary}`:""}`,tags:["project",n.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,n,
|
|
227
|
-
Rationale: ${
|
|
228
|
-
Outcome: ${
|
|
229
|
-
`).slice(0,n)}},qr=null;function Yt(){return qr||(qr=new Br),qr}function Et(t,e,n){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.","",Z("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."]),"",Z("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."]),"",Z("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"]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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"]),"",Z("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"]),"",Z("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."]),"",Z("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(!n)return[];let s=Yt().buildContextBlock(n,2500);return s.trim()?[Z("PERSISTENT MEMORY",s),""]:[]})(),Z("TASK PROFILE",Gg(e)),"",Z("CURRENT PROJECT CONTEXT",Kg(t)),"",Z("REASONING PROTOCOL",zg(e))].join(`
|
|
230
|
-
`)}function
|
|
226
|
+
Summary: ${n.summary}`:""}`,tags:["project",n.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,n,r){this.remember({kind:"decision",key:`decision:${e}:${n.slice(0,60)}`,value:`Decision: ${n}
|
|
227
|
+
Rationale: ${r}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,n){this.remember({kind:"preference",key:`pref:${e}`,value:n,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,n,r){this.remember({kind:"task_summary",key:`task:${e}:${n.slice(0,60)}:${Date.now()}`,value:`Task: ${n}
|
|
228
|
+
Outcome: ${r}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,n=3e3){let r=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){r.push("## Memory: this project");for(let o of i.slice(0,8))r.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let s=this.getByKind("preference",5);if(s.length>0){r.push("## Memory: user preferences");for(let i of s)r.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return r.join(`
|
|
229
|
+
`).slice(0,n)}},Bs=null;function Yt(){return Bs||(Bs=new Hs),Bs}function Et(t,e,n){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.","",Z("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."]),"",Z("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."]),"",Z("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"]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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."]),"",Z("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"]),"",Z("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"]),"",Z("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."]),"",Z("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(!n)return[];let r=Yt().buildContextBlock(n,2500);return r.trim()?[Z("PERSISTENT MEMORY",r),""]:[]})(),Z("TASK PROFILE",Jg(e)),"",Z("CURRENT PROJECT CONTEXT",Gg(t)),"",Z("REASONING PROTOCOL",Kg(e))].join(`
|
|
230
|
+
`)}function Kg(t){return!t.needsTools||t.kind==="casual"?"For this turn: answer directly and clearly. No tool protocol needed.":t.kind==="read"?["This is a READ/INSPECT turn.","1. Locate the minimum relevant files.","2. Read them. Form your answer from evidence.","3. Do not speculate \u2014 answer only from what you observe."].join(`
|
|
231
231
|
`):t.complexity==="XS"||t.complexity==="S"?["Compact reasoning \u2014 think briefly before acting:","<thinking>Goal | Next step | Why</thinking>","Then execute. One tool call per step."].join(`
|
|
232
232
|
`):["FULL REASONING PROTOCOL (non-negotiable for this task complexity):","","BEFORE any tool call:","<thinking>"," GOAL: What does the user want? (one sentence)"," KNOWN: What do I already have?"," UNKNOWN: What must I still find out?"," PLAN: Numbered steps to reach the goal."," NEXT: The single next action and why.","</thinking>","","AFTER each tool result:","<thinking>"," OBSERVATION: What did the tool return?"," PROGRESS: Which steps are done / which remain?"," NEXT: The logical next step.","</thinking>","","Rules:","- ALWAYS think before acting \u2014 no bare tool calls.","- One tool call per step. Wait for the result.","- If a tool fails, analyze the error before retrying.","- When done: give a concise final answer WITHOUT <thinking> tags.","- Build a PLAN: block first. Then execute step 1."].join(`
|
|
233
233
|
`)}function Z(t,e){let n=Array.isArray(e)?e.join(`
|
|
234
234
|
`):e;return["====================",t,"====================",n].join(`
|
|
235
|
-
`)}function
|
|
235
|
+
`)}function Gg(t){return t.trim()||"No project context captured."}function Jg(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(`
|
|
236
236
|
`):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(`
|
|
237
237
|
`):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(`
|
|
238
238
|
`):[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(`
|
|
239
|
-
`)}var
|
|
239
|
+
`)}var Yg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|yep|nope|sure|cool|got it|noted|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك|ايوه|لا|نعم|صح|ماشي|عادي|اوك|oke|oki|👍|✅)[.!?\s]*$/i,Xg=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|install|setup|configure|integrate|connect|wire|scaffold|patch|repair|extend|modify|replace|upgrade|convert|transform|rewrite|delete|move|rename|copy|link|enable|disable|toggle|init|bootstrap|inject|wrap|expose|mount|register|optimize|compress|bundle|minify|lint|format|seed|populate|import|export|push|commit|release|publish|run|test|launch|start|stop|restart|attach|parse|validate|sanitize|encode|decode|hash|encrypt|sign|index|cache|queue|schedule|trigger|emit|listen|subscribe|stream|sync|clone|fork|merge|rebase|reset|stash|apply)\b/i,Qg=/(اعمل|افعل|اكتب|انشئ|انشأ|إنشاء|اضف|اضافة|أضف|إضافة|عدل|عدّل|تعديل|احذف|حذف|اصلح|إصلاح|صلح|حسّن|تحسين|ارفع|رفع|نفذ|تنفيذ|شغّل|شغل|ابنِ|بناء|اصنع|ادمج|دمج|ربط|اربط|اضبط|ضبط|حوّل|تحويل|ولّد|توليد|طوّر|تطوير|نزّل|تنزيل|نشر|اطلق|اجرِ|جرّب|اختبر|فعّل|عطّل|حدّث|تحديث|كمّل|خلّص|انهِ|ابدأ|أوقف|اعد|ولد|احضر|جيب|حط|وصّل|اتصل|شارك|ابدا|طبق|اطبق|بدّل|استبدل|غيّر|أوصل)/,Zg=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent|addd|dlete|edti|wriet|insatll|confgure|refactr|debugg|buidl|genrate|complet|migarate)\b/i,ey=/\b(architecture|architect|design|blueprint|plan|requirements?|research|compare|investigate|approach|tradeoff|trade-off|pros?|cons?|document|spec|specification|review|audit|analyze|analyse|evaluate|assess|benchmark|profile|diagnose|explain|describe|understand|overview|summary|difference between|vs\.?|versus)\b/i,ty=/(معمارية|تصميم|خطة|متطلبات|بحث|قارن|فهم|اشرح|وضح|ما هو|ما هي|لماذا|الفرق|مقارنة|تحليل|تقييم|دراسة|مراجعة|ملخص|نظرة عامة|توثيق|مواصفات)/,ny=/\b(read|inspect|check|show|list|find|what is|which|where|print|display|view|look at|open|see|tell me|get|retrieve)\b/i,ry=/(اقرأ|اعرض|اظهر|فتش|شوف|وين|انظر|اطلع|اجلب|احضر|قرأ|أظهر|أعرض|بيّن|ليش|وش|إيش)/,kl=/\b(frontend|backend|fullstack|api|rest|graphql|websocket|endpoint|route|handler|middleware|controller|service|repository|model|schema|entity|migration|seed|store|redux|zustand|context|hook|component|widget|page|screen|view|layout|template|theme|style|css|scss|tailwind|ui|ux|design|responsive|mobile|pwa|spa|ssr|ssg|database|db|sql|nosql|postgres|mysql|sqlite|mongo|redis|elasticsearch|cache|queue|job|worker|cron|auth|oauth|jwt|session|cookie|role|permission|admin|dashboard|panel|cms|landing|hero|carousel|modal|form|input|button|table|chart|card|nav|sidebar|header|footer|banner|image|video|file|upload|download|s3|cdn|stream|search|filter|sort|docker|container|kubernetes|nginx|proxy|ssl|deploy|ci|cd|github|workflow|env|config|secret|monitor|log|test|unit|integration|e2e|coverage|build|bundle|compile|typecheck|lint)\b/i,Tl=/(واجهة|خلفية|قاعدة بيانات|مكون|صفحة|نموذج|مسار|خادم|عميل|تطبيق|موقع|واجهة برمجة|مصادقة|تسجيل|مستخدم|جدول|مخطط|ملف|مجلد|مشروع|مكتبة|حزمة|إعداد|تكوين|نشر|اختبار|بناء|سجل|خطأ|أداء|ذاكرة|نسخ احتياطي)/,sy=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from where|carry on|pick up|keep going|where we left|last time|already started|in progress|go on|dont stop|don't stop|from here)\b/i,iy=/(كمّل|تكملة|أكمل|استمر|استمرار|من السابق|المشروع الحالي|ما اكتملنا|واصل|من اللي وقفنا|اللي بدأناه|كمل|تابع|متابعة)/,oy=/\b(one step|no questions?|no ask|just give me|deliver complete|finished project|run it|dont ask|don't ask|just do it|straight to|go ahead|without asking|autonomous|auto|direct|fully|completely)\b/i,ay=/(بدون أسئلة|ما تسأل|روح عليه|مباشرة|كمّل لحالك|تلقائي|أوتوماتيك|انجزه|بدون سؤال|على طول|خلص بدون)/;function cy(t){let e=t.toLowerCase(),n={implementation:0,analysis:0,read:0,casual:0,continuity:!1,oneStep:!1};n.continuity=sy.test(e)||iy.test(t),n.oneStep=oy.test(e)||ay.test(t),n.continuity&&(n.implementation+=6),n.oneStep&&(n.implementation+=3),Xg.test(e)&&(n.implementation+=5),Qg.test(t)&&(n.implementation+=5),Zg.test(e)&&(n.implementation+=4),ey.test(e)&&(n.analysis+=4),ty.test(t)&&(n.analysis+=4),ny.test(e)&&(n.read+=3),ry.test(t)&&(n.read+=3),(kl.test(e)||Tl.test(t))&&(n.implementation+=2);let s=t.split(/\s+/).filter(Boolean).length;return s<=4&&n.implementation<=3&&(n.read+=2),t.endsWith("?")&&(n.read+=2,n.analysis+=1),s>20&&(n.implementation+=2),s>40&&(n.implementation+=2),n}function ly(t){return t<=4?"XS":t<=10?"S":t<=25?"M":t<=50?"L":"XL"}function Xt(t){let e=t.trim(),n=e.toLowerCase(),r=e.split(/\s+/).filter(Boolean).length;if(Yg.test(e))return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,complexity:"XS",reason:"Pure social turn \u2014 no engineering signal detected."};let s=cy(e),i=kl.test(n)||Tl.test(e);return s.implementation>=5||s.implementation===Math.max(s.implementation,s.analysis,s.read)&&s.implementation>=3?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:s.continuity,oneStepDelivery:s.oneStep,requiresProjectContext:!0,complexity:ly(r),reason:s.continuity?"Continuation of in-progress work \u2014 loading existing context.":"Implementation request detected \u2014 tool-based execution required."}:s.analysis>=4&&s.analysis>=s.implementation?{kind:"analysis",needsTools:i,needsWrite:!1,continuity:s.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:i?"Architecture/analysis with project reference \u2014 inspection needed.":"Architecture/design reasoning \u2014 text-first turn."}:s.read>=3||e.endsWith("?")?{kind:"read",needsTools:i,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:i,complexity:"S",reason:i?"Read/inspect request \u2014 file inspection needed.":"Direct factual question \u2014 answer from knowledge."}:{kind:"analysis",needsTools:i,needsWrite:!1,continuity:s.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:"Ambiguous input \u2014 defaulting to analysis mode."}}function uy(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly with full clarity."}];if(t.kind==="read")return[{id:"locate",title:"Locate the minimum relevant files or data."},{id:"inspect",title:"Read and understand the actual content."},{id:"answer",title:"Answer precisely from observed facts only."}];if(t.kind==="analysis")return[{id:"ground",title:"Inspect key files to ground the analysis in reality."},{id:"reason",title:"Form an evidence-based architectural assessment."},{id:"deliver",title:"Present findings as a coherent engineering partner."}];let e=[];return t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery: complete without unnecessary questions."}),t.continuity&&e.push({id:"continuity",title:"Reload existing context \u2014 resume, do not restart."}),e.push({id:"orient",title:"Understand the real goal and success criteria."},{id:"ground",title:"Inspect relevant code, files, and dependencies."},{id:"plan",title:"Choose the smallest correct implementation path."},{id:"implement",title:"Apply the change with the right tools."},{id:"verify",title:"Run verification: build, lint, test, or type-check."},{id:"deliver",title:"Report: what changed, what was verified, what remains."}),e}function Cl(t){let e=Xt(t);return{input:t,profile:e,plan:uy(e)}}var El=k(require("readline")),ye=k(require("fs")),ae=k(require("path")),Al=k(require("os"));var qn=ae.join(Al.homedir(),".hablas","history"),Bn=500,fy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),dy=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],py=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"]),$l=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Hn=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return El.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Bn,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(n=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,r=>{let s=r.trim();s&&(this.history.push(s),this.history=this.history.slice(-Bn),this.saveHistory()),n(r)})})}async confirm(e){return(await this.prompt(` ${x.warning("?")} ${e} ${x.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
240
240
|
${x.error("\u26A0")} ${e}`),console.log(` ${x.muted("Type yes to confirm this dangerous action.")}
|
|
241
|
-
`),(await this.prompt(` ${x.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let
|
|
241
|
+
`),(await this.prompt(` ${x.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let r=$l.filter(s=>s.startsWith(e));return[r.length?r:$l,e]}for(let r of dy)if(e.toLowerCase().includes(r)){let s=e.split(r).pop()??"";if(s&&!s.includes(" "))try{let i=ae.dirname(s)||".",o=ae.basename(s),a=ae.resolve(this.workingDir,i),c=ye.readdirSync(a).filter(l=>l.startsWith(o)).slice(0,8).map(l=>e.slice(0,e.lastIndexOf(s))+ae.join(i,l));if(c.length)return[c,e]}catch{}}let n=e.match(/#([\w./-]*)$/);if(n){let r=n[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(r.toLowerCase())).map(o=>e.slice(0,e.length-n[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-n[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let n=[];return this.scanDir(this.workingDir,"",n,3),this.fileCache=n,this.fileCacheTime=e,n}scanDir(e,n,r,s,i=0){if(!(i>=s))try{let o=ye.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||fy.has(a.name))continue;let c=n?`${n}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(ae.join(e,a.name),c,r,s,i+1);else{let l=ae.extname(a.name).toLowerCase();(py.has(l)||a.name==="Dockerfile"||a.name==="Makefile")&&r.push(c)}}}catch{}}loadHistory(){try{ye.existsSync(qn)&&(this.history=ye.readFileSync(qn,"utf-8").split(`
|
|
242
242
|
`).filter(Boolean).slice(-Bn))}catch{}}saveHistory(){try{let e=ae.dirname(qn);ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(qn,this.history.slice(-Bn).join(`
|
|
243
|
-
`),"utf-8")}catch{}}};var
|
|
243
|
+
`),"utf-8")}catch{}}};var hy={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},my=`
|
|
244
244
|
## Reasoning Protocol
|
|
245
245
|
|
|
246
246
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -269,17 +269,17 @@ After receiving a tool result, think again:
|
|
|
269
269
|
- One tool call per turn. Wait for the result before the next call.
|
|
270
270
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
271
271
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
272
|
-
`.trim(),
|
|
272
|
+
`.trim(),gy=`
|
|
273
273
|
## Reasoning
|
|
274
274
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
275
275
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
276
|
-
`.trim(),
|
|
276
|
+
`.trim(),Vs=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...hy,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,n="M"){return!this.config.thinkingEnabled||n==="XS"?e:n==="S"?`${e}
|
|
277
277
|
|
|
278
|
-
${
|
|
278
|
+
${gy}`:`${e}
|
|
279
279
|
|
|
280
|
-
${
|
|
280
|
+
${my}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let n=[],r=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)n.push(i[1].trim());r=r.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)n.push(i[1].trim());r=r.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(r);a&&(n.push(a[1].trim()),r=r.replace(/<thinking>[\s\S]*$/i,""));let c=/<think>([\s\S]*)$/i.exec(r);return c&&(n.push(c[1].trim()),r=r.replace(/<think>[\s\S]*$/i,"")),{thinking:n.join(`
|
|
281
281
|
|
|
282
|
-
`).trim(),visibleContent:
|
|
282
|
+
`).trim(),visibleContent:r.trim(),hasThinking:n.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let n={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(n),n}recordObservation(e,n){let r=this.turnSteps[this.turnSteps.length-1];r&&(r.observation=e,n&&(r.reflection=n))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,n,r){return`
|
|
283
283
|
<self_eval>
|
|
284
284
|
You just completed this task: "${e}"
|
|
285
285
|
|
|
@@ -288,7 +288,7 @@ Your answer was:
|
|
|
288
288
|
${n.slice(0,1500)}
|
|
289
289
|
"""
|
|
290
290
|
|
|
291
|
-
Tools used: ${
|
|
291
|
+
Tools used: ${r.length>0?r.join(", "):"none"}
|
|
292
292
|
|
|
293
293
|
Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
294
294
|
{
|
|
@@ -299,42 +299,42 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
299
299
|
"confidence": "<high|medium|low>"
|
|
300
300
|
}
|
|
301
301
|
</self_eval>
|
|
302
|
-
`.trim()}parseSelfEval(e){let n=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let
|
|
303
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,n=this.turnSteps.filter(
|
|
304
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let n=this.failures.get(e);return n?n.count<=1&&n.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Zt(t=3){return new
|
|
302
|
+
`.trim()}parseSelfEval(e){let n=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let r of n){let s=e.match(r);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let n=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,r=typeof e.completed=="boolean"?e.completed:n>=7,s=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:n>=8?o="high":n<=4&&(o="low"),{score:n,completed:r,rationale:s,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,n,r){return n?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${r.slice(0,300)}`,"</thinking>"].join(`
|
|
303
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,n=this.turnSteps.filter(s=>s.action).length,r=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${n} actions, ${r} reflections`}};function Qt(t){return new Vs(t)}var yy=[{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}],zs=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,n,r){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:n,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of yy)if(a.test(n)){let c=s?.lastStrategy===a.strategy&&i>=2,l=c?"decompose_task":a.strategy;return o.lastStrategy=l,this.failures.set(e,o),{errorClass:a.errorClass,strategy:l,explanation:a.explanation,suggestion:c?`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:!c&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,n){let r=[`ERROR: ${n}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&r.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":r.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":r.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":r.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":r.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":r.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":r.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return r.join(`
|
|
304
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let n=this.failures.get(e);return n?n.count<=1&&n.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Zt(t=3){return new zs(t)}var Pe=k(require("fs")),Vn=k(require("path")),Ol=k(require("os")),Wn=Vn.join(Ol.homedir(),".hablas","model-formats.json");function wy(){try{if(Pe.existsSync(Wn))return JSON.parse(Pe.readFileSync(Wn,"utf-8"))}catch{}return{}}function by(t){try{let e=Vn.dirname(Wn);Pe.existsSync(e)||Pe.mkdirSync(e,{recursive:!0}),Pe.writeFileSync(Wn,JSON.stringify(t,null,2),"utf-8")}catch{}}function Rl(t,e){let n=0,r=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&r){s=!0;continue}if(o==='"'){r=!r;continue}if(!r&&(o==="{"&&n++,o==="}"&&(n--,n===0)))return t.slice(e,i+1)}return null}function en(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let n={};if(typeof e.arguments=="string")try{n=JSON.parse(e.arguments)}catch{n={}}else e.arguments&&typeof e.arguments=="object"&&(n=e.arguments);return{tool:e.name,args:n}}}return null}function xy(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Sy(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim()),i=en(s);i&&e.push({...i,format:"xml_tags",rawMatch:r[0]})}catch{}return e}function vy(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim());if(s.parameters||s.name){let i=en(s);i&&e.push({...i,format:"hermes",rawMatch:r[0]})}}catch{}return e}function _y(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,r;for(;(r=n.exec(t))!==null;){let s=r[1],i=Il(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:r[0]})}return e}function Il(t){let e=[],n=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch","git_commit","git_stash","atomic_write","diff_preview","rollback_session","checkpoint_save","checkpoint_restore","checkpoint_list","checkpoint_diff","bash_output","kill_shell"];for(let r of n){let s=new RegExp(`<<?${r}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${r}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",c={},l=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=l.exec(o))!==null;){let p=u[1].toLowerCase(),h=u[2]??u[3]??u[4];c[p]=xy(h)}let f=a.trim();f&&(r==="write_file"||r==="append_to_file"?c.content=a:r==="run_command"?c.command=f:r==="patch_file"&&(c.new_content=a)),c.start_line&&(c.start_line=parseInt(c.start_line)),c.end_line&&(c.end_line=parseInt(c.end_line)),c.depth&&(c.depth=parseInt(c.depth)),e.push({tool:r,args:c,format:"xml_prompt",rawMatch:i[0]})}}return e}function ky(t){return Il(t)}function Ty(t){let e=[],n=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,r;for(;(r=n.exec(t))!==null;)try{let s=JSON.parse(r[1].trim()),i=en(s);i&&e.push({...i,format:"markdown_json",rawMatch:r[0]})}catch{}return e}function Cy(t){let e=[],n=/\{\s*"function"\s*:/g,r;for(;(r=n.exec(t))!==null;){let s=Rl(t,r.index);if(s)try{let i=JSON.parse(s),o=en(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function $y(t){let e=[],n=/\{\s*"(?:name|tool)"\s*:/g,r;for(;(r=n.exec(t))!==null;){let s=Rl(t,r.index);if(s)try{let i=JSON.parse(s),o=en(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function Ey(t){let e=[],n=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,r,s=!1;for(;(r=n.exec(t))!==null;){let i=r[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),c={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.exec(i))!==null;){let f=u[1].trim(),p=u[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),c[f]=p}e.push({tool:a,args:c,format:"xml_parameters",rawMatch:r[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,l;for(;(l=c.exec(t))!==null;){let u=l[1].trim(),f=l[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[u]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Ks=[{format:"xml_tool_call_wrapper",parse:_y},{format:"xml_prompt",parse:ky},{format:"xml_tags",parse:Sy},{format:"xml_parameters",parse:Ey},{format:"hermes",parse:vy},{format:"markdown_json",parse:Ty},{format:"function_call",parse:Cy},{format:"json_object",parse:$y}],Js=class{registry;constructor(){this.registry=wy()}parse(e,n,r){if(n&&Array.isArray(n)&&n.length>0){let i=n.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return r&&this.learnFormat(r,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(r){let i=this.registry[r];if(i&&i.format!=="native"){let o=Ks.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(r,i.format),this.buildResult(a,s)}}}for(let{parse:i}of Ks){let o=i(s);if(o.length>0){let a=o[0].format;return r&&this.learnFormat(r,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let n=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(n)||/<function=/i.test(n)||n.includes("```tool_call")||n.includes("```json")&&n.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(n)||n.startsWith("{")&&(n.includes('"name"')||n.includes('"tool"'))&&(n.includes('"arguments"')||n.includes('"args"')||n.includes('"parameters"'))||n.includes('"function"')&&n.includes('"name"'))}detectFormat(e){for(let{format:n,parse:r}of Ks)if(r(e).length>0)return n;return"unknown"}learnFormat(e,n){let r=this.registry[e];r&&r.format===n?(r.successCount++,r.lastUsed=new Date().toISOString()):this.registry[e]={format:n,successCount:1,lastUsed:new Date().toISOString()},by(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[n,r]of Object.entries(this.registry))e[n]={format:r.format,successCount:r.successCount};return e}buildResult(e,n){let r=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=n,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
|
|
305
305
|
|
|
306
|
-
`),{toolCalls:
|
|
306
|
+
`),{toolCalls:r,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
|
|
307
307
|
|
|
308
|
-
`)}},Kr=null;function Il(){return Kr||(Kr=new Gr),Kr}var zn=class t{buf="";inThink=!1;visibleEmitted=!1;onToken;static THINK_OPENS=["<thinking>","<think>"];static THINK_CLOSES=["</thinking>","</think>"];static PARTIAL_SCAN=12;constructor(e){this.onToken=e}push(e){this.buf+=e,this.flush_process()}flush(){if(this.inThink){this.buf="",this.inThink=!1;return}if(this.buf.trim()){let e=this.buf.replace(/<\/?think(?:ing)?>/gi,"").trim();e&&this.emit(e)}this.buf=""}get hasVisibleContent(){return this.visibleEmitted}flush_process(){for(;this.buf.length>0;){if(this.inThink){let s=this.findFirst(t.THINK_CLOSES);if(s===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let r=this.buf.indexOf(">",s)+1;this.buf=this.buf.slice(r),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let s=this.longestPartialTail();if(s>0){let r=this.buf.slice(0,this.buf.length-s);r&&this.emit(r),this.buf=this.buf.slice(this.buf.length-s);return}this.emit(this.buf),this.buf="";return}if(e>0){this.emit(this.buf.slice(0,e)),this.buf=this.buf.slice(e);continue}this.inThink=!0;let n=this.buf.indexOf(">")+1;this.buf=this.buf.slice(n>0?n:this.buf.length)}}findFirst(e){let n=-1,s=this.buf.toLowerCase();for(let r of e){let i=s.indexOf(r.toLowerCase());i!==-1&&(n===-1||i<n)&&(n=i)}return n}longestPartialTail(){let e=t.PARTIAL_SCAN,n=this.buf.slice(-e).toLowerCase(),s=0;for(let r of t.THINK_OPENS){let i=r.toLowerCase();for(let o=Math.min(i.length-1,n.length);o>0;o--)if(i.startsWith(n.slice(-o))){s=Math.max(s,o);break}}return s}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var Ey=600,Ay=4e3,Oy=16e3,jl=2;function Ry(t,e,n){let r=Il().parse(e,t,n);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function Iy(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 jy(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 Pl(t,e,n,s){let r=0,i=Date.now();for(;r<=jl;){let o=await t.execute({name:e,arguments:n});if(o.success||r>=jl)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:r};r++,s.info({tool:e,retry:r,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:r}}async function Jr(t){let{identity:e,client:n,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:c,abortSignal:l,skipTools:u}=t,f=t.reactEngine??Qt(),p=t.errorRecovery??Zt(),h=u?[]:s.getOllamaTools(),d=n.getModel(),m=t.maxIterations??Ey,g=[],y=[],b=[],w=new Map,v="",_=0,T=!1;for(;_<m;){if(_++,l?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:T};let A=f.buildBudgetWarningPrompt();A&&r.addUserMessage(A,{priority:"critical",tags:["system-budget"]});let E;try{if(a.onModelStart?.(y.length>0?"Deciding next step":"Thinking",e),n.streamChatWithTools){let z=!1,se=new zn(De=>{z||(a.onModelStop?.(),z=!0),a.onStreamToken?.(De,e)}),I=n.streamChatWithTools(r.getMessages(),h,De=>{se.push(De)},l),M=await I.next();for(;!M.done;)M=await I.next();se.flush(),E=M.value,z||a.onModelStop?.()}else E=await n.chatWithTools(r.getMessages(),h,l),a.onModelStop?.()}catch(z){a.onModelStop?.();let se=z;if(se.name==="AbortError"||l?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:T};if(_<=1){a.onNotice?.("Transient error: "+pe(se).message+" \u2014 retrying...","retry"),await new Promise(M=>setTimeout(M,1e3)),_--;continue}let I=pe(se);return I.fatal?(a.onError?.(I.message),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:I.message,completedNaturally:T}):(a.onError?.(I.message),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:I.message,completedNaturally:T})}if(!E||!E.message){a.onNotice?.("Model returned an empty response \u2014 retrying...","retry"),await new Promise(z=>setTimeout(z,1500));continue}let $=E.message?.content||"",P=E.message?.tool_calls,U=f.parseThinking($);U.hasThinking&&(f.recordStep({thought:U.thinking}),o.debug({thinking:U.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:H}=Ry(P,$,d);if(H&&H.trim()&&(v=H,await a.onAssistantText?.(H,e)),N.length===0){r.addAssistantMessage($,void 0,e.role),T=!0;break}r.addAssistantMessage($,N,e.role);let X=N.length;for(let z=0;z<X;z++){let se=N[z];if(!se?.function?.name)continue;let I=se.function.name,M=se.function.arguments||{},De=s.getSafetyLevel(I)??"confirm";if(!s.get(I)){a.onNotice?.("Unknown tool: "+I+" \u2014 skipping","warn"),r.addToolMessage('Error: Unknown tool "'+I+'". Available: '+s.getAll().map(Q=>Q.name).join(", "));continue}if(await c(I,De,M)==="skip"){r.addToolMessage("Tool "+I+" was skipped by policy/user.");break}let nu=Iy(I,M),Ot=I==="read_file"?JSON.stringify({path:M.path||"",start:M.start_line||"",end:M.end_line||""}):"";if(I==="read_file"&&Ot&&w.has(Ot)){let Q=w.get(Ot)||"";r.addToolMessage(Q),f.recordObservation(Q.slice(0,300),"Reused cached file read");continue}g.push(I),typeof M.path=="string"&&b.push(M.path),typeof M.from=="string"&&b.push(M.from),typeof M.to=="string"&&b.push(M.to),a.onToolStart?.(I,nu,M),a.onToolCall?.(),f.recordStep({thought:U.hasThinking?"Executing: "+I:"",action:I,actionInput:M});let J=await Pl(s,I,M,o);a.onToolEnd?.(I,J.success,J.error||J.output,J.duration,M);let ze;if(J.success)ze=Ml(I,J.output),f.recordObservation(ze.slice(0,300)),y.push({tool:I,success:!0,summary:J.output.slice(0,150)});else{let Q=J.error||"Unknown error",at=p.analyze(I,Q,M);if(ze=p.buildRecoveryMessage(at,Q),f.recordObservation("FAILED: "+Q,"Recovery: "+at.strategy+" \u2014 "+at.suggestion),o.info({tool:I,errorClass:at.errorClass,strategy:at.strategy},"Error recovery analysis"),y.push({tool:I,success:!1,summary:Q.slice(0,150)}),at.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let ct=await Pl(s,I,M,o);a.onToolEnd?.(I,ct.success,ct.output,ct.duration,M),ct.success&&(ze=Ml(I,ct.output),f.recordObservation(ze.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:I,success:!0,summary:ct.output.slice(0,150)})}}if(r.addToolMessage(ze),J.success&&I==="read_file"&&typeof M.path=="string"&&(i?.addFile(M.path,J.output),Ot&&w.set(Ot,ze)),J.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(I)&&typeof M.path=="string")for(let Q of[...w.keys()])Q.includes('"path":"'+String(M.path).replace(/"/g,'\\"')+'"')&&w.delete(Q);if(J.success&&I==="move_file")for(let Q of[...w.keys()])(M.from&&Q.includes('"path":"'+String(M.from).replace(/"/g,'\\"')+'"')||M.to&&Q.includes('"path":"'+String(M.to).replace(/"/g,'\\"')+'"'))&&w.delete(Q);if(o.info({tool:I,success:J.success,durationMs:J.duration,retries:J.retries},"Tool executed"),!J.success&&jy(J.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}}f.isOverBudget()&&a.onNotice?.("Reached max reasoning steps ("+f.getConfig().maxSteps+"). Wrapping up.","warn")}return _>=m&&!T&&a.onNotice?.("Reached max iterations ("+m+"). Stopping.","warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!0,completedNaturally:T}}function Ee(t){return[...new Set(t)]}function Ml(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?Kt(e,Oy):Kt(e,Ay)}function Fl(t){return async(e,n)=>{let s=e.replace(/_/g," ");return!t.autoMode&&t.interactive?n==="confirm"&&t.confirm?await t.confirm("Proceed with "+s+"?")?"allow":"skip":n==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+s)?"allow":"skip":"allow":!t.autoMode&&n==="dangerous"?"skip":"allow"}}async function Ll(t){let{client:e,session:n,abortSignal:s,onStart:r,onChunk:i,onComplete:o}=t,a="",c=null;for(let l=0;l<2;l++)try{a="",r?.();for await(let u of e.streamChat(n.getMessages(),s)){if(s?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,i?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(n.getMessages(),[],s)).message?.content||"",a&&i?.(a)),n.addAssistantMessage(a||""),o?.(),a}catch(u){if(c=u,u?.name==="AbortError"||s?.aborted)throw u;let p=pe(u);if(p.fatal)throw new Error(p.message);if(l===1)throw new Error(p.message);await new Promise(h=>setTimeout(h,1e3))}throw c||new Error("Text turn failed")}function Py(t){return["list_dir","read_file","search_codebase","get_file_info"].includes(t)?"Inspecting":["web_search"].includes(t)?"Researching":["scrape_url","extract_links","search_image_candidates","inspect_image"].includes(t)?"Fetching":["download_asset"].includes(t)?"Downloading":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing":["run_command","execute_code","detect_bugs"].includes(t)?"Running":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Git":"Working"}function ee(t){process.stdout.write(t)}function Kn(t){process.stdout.write(t+`
|
|
309
|
-
`)}async function Gn(t,e){let n=
|
|
308
|
+
`)}},Gs=null;function jl(){return Gs||(Gs=new Js),Gs}var zn=class t{buf="";inThink=!1;visibleEmitted=!1;onToken;static THINK_OPENS=["<thinking>","<think>"];static THINK_CLOSES=["</thinking>","</think>"];static PARTIAL_SCAN=12;constructor(e){this.onToken=e}push(e){this.buf+=e,this.flush_process()}flush(){if(this.inThink){this.buf="",this.inThink=!1;return}if(this.buf.trim()){let e=this.buf.replace(/<\/?think(?:ing)?>/gi,"").trim();e&&this.emit(e)}this.buf=""}get hasVisibleContent(){return this.visibleEmitted}flush_process(){for(;this.buf.length>0;){if(this.inThink){let r=this.findFirst(t.THINK_CLOSES);if(r===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let s=this.buf.indexOf(">",r)+1;this.buf=this.buf.slice(s),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let r=this.longestPartialTail();if(r>0){let s=this.buf.slice(0,this.buf.length-r);s&&this.emit(s),this.buf=this.buf.slice(this.buf.length-r);return}this.emit(this.buf),this.buf="";return}if(e>0){this.emit(this.buf.slice(0,e)),this.buf=this.buf.slice(e);continue}this.inThink=!0;let n=this.buf.indexOf(">")+1;this.buf=this.buf.slice(n>0?n:this.buf.length)}}findFirst(e){let n=-1,r=this.buf.toLowerCase();for(let s of e){let i=r.indexOf(s.toLowerCase());i!==-1&&(n===-1||i<n)&&(n=i)}return n}longestPartialTail(){let e=t.PARTIAL_SCAN,n=this.buf.slice(-e).toLowerCase(),r=0;for(let s of t.THINK_OPENS){let i=s.toLowerCase();for(let o=Math.min(i.length-1,n.length);o>0;o--)if(i.startsWith(n.slice(-o))){r=Math.max(r,o);break}}return r}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var Ay=600,Oy=4e3,Ry=16e3,Pl=2;function Iy(t,e,n){let s=jl().parse(e,t,n);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function jy(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 Py(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 Ml(t,e,n,r){let s=0,i=Date.now();for(;s<=Pl;){let o=await t.execute({name:e,arguments:n});if(o.success||s>=Pl)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,r.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function Ys(t){let{identity:e,client:n,registry:r,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:c,abortSignal:l,skipTools:u}=t,f=t.reactEngine??Qt(),p=t.errorRecovery??Zt(),h=u?[]:r.getOllamaTools(),d=n.getModel(),m=t.maxIterations??Ay,g=[],y=[],b=[],w=new Map,v="",_=0,T=!1;for(;_<m;){if(_++,l?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:T};let A=f.buildBudgetWarningPrompt();A&&s.addUserMessage(A,{priority:"critical",tags:["system-budget"]});let E;try{if(a.onModelStart?.(y.length>0?"Deciding next step":"Thinking",e),n.streamChatWithTools){let z=!1,re=new zn(De=>{z||(a.onModelStop?.(),z=!0),a.onStreamToken?.(De,e)}),I=n.streamChatWithTools(s.getMessages(),h,De=>{re.push(De)},l),M=await I.next();for(;!M.done;)M=await I.next();re.flush(),E=M.value,z||a.onModelStop?.()}else E=await n.chatWithTools(s.getMessages(),h,l),a.onModelStop?.()}catch(z){a.onModelStop?.();let re=z;if(re.name==="AbortError"||l?.aborted)return{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:"Aborted",completedNaturally:T};if(_<=1){a.onNotice?.("Transient error: "+pe(re).message+" \u2014 retrying...","retry"),await new Promise(M=>setTimeout(M,1e3)),_--;continue}let I=pe(re);return I.fatal?(a.onError?.(I.message),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:I.message,completedNaturally:T}):(a.onError?.(I.message),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!1,error:I.message,completedNaturally:T})}if(!E||!E.message){a.onNotice?.("Model returned an empty response \u2014 retrying...","retry"),await new Promise(z=>setTimeout(z,1500));continue}let $=E.message?.content||"",P=E.message?.tool_calls,U=f.parseThinking($);U.hasThinking&&(f.recordStep({thought:U.thinking}),o.debug({thinking:U.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:H}=Iy(P,$,d);if(H&&H.trim()&&(v=H,await a.onAssistantText?.(H,e)),N.length===0){s.addAssistantMessage($,void 0,e.role),T=!0;break}s.addAssistantMessage($,N,e.role);let X=N.length;for(let z=0;z<X;z++){let re=N[z];if(!re?.function?.name)continue;let I=re.function.name,M=re.function.arguments||{},De=r.getSafetyLevel(I)??"confirm";if(!r.get(I)){a.onNotice?.("Unknown tool: "+I+" \u2014 skipping","warn"),s.addToolMessage('Error: Unknown tool "'+I+'". Available: '+r.getAll().map(Q=>Q.name).join(", "));continue}if(await c(I,De,M)==="skip"){s.addToolMessage("Tool "+I+" was skipped by policy/user.");break}let ru=jy(I,M),Ot=I==="read_file"?JSON.stringify({path:M.path||"",start:M.start_line||"",end:M.end_line||""}):"";if(I==="read_file"&&Ot&&w.has(Ot)){let Q=w.get(Ot)||"";s.addToolMessage(Q),f.recordObservation(Q.slice(0,300),"Reused cached file read");continue}g.push(I),typeof M.path=="string"&&b.push(M.path),typeof M.from=="string"&&b.push(M.from),typeof M.to=="string"&&b.push(M.to),a.onToolStart?.(I,ru,M),a.onToolCall?.(),f.recordStep({thought:U.hasThinking?"Executing: "+I:"",action:I,actionInput:M});let J=await Ml(r,I,M,o);a.onToolEnd?.(I,J.success,J.error||J.output,J.duration,M);let ze;if(J.success)ze=Fl(I,J.output),f.recordObservation(ze.slice(0,300)),y.push({tool:I,success:!0,summary:J.output.slice(0,150)});else{let Q=J.error||"Unknown error",at=p.analyze(I,Q,M);if(ze=p.buildRecoveryMessage(at,Q),f.recordObservation("FAILED: "+Q,"Recovery: "+at.strategy+" \u2014 "+at.suggestion),o.info({tool:I,errorClass:at.errorClass,strategy:at.strategy},"Error recovery analysis"),y.push({tool:I,success:!1,summary:Q.slice(0,150)}),at.autoRetry&&!f.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let ct=await Ml(r,I,M,o);a.onToolEnd?.(I,ct.success,ct.output,ct.duration,M),ct.success&&(ze=Fl(I,ct.output),f.recordObservation(ze.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:I,success:!0,summary:ct.output.slice(0,150)})}}if(s.addToolMessage(ze),J.success&&I==="read_file"&&typeof M.path=="string"&&(i?.addFile(M.path,J.output),Ot&&w.set(Ot,ze)),J.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(I)&&typeof M.path=="string")for(let Q of[...w.keys()])Q.includes('"path":"'+String(M.path).replace(/"/g,'\\"')+'"')&&w.delete(Q);if(J.success&&I==="move_file")for(let Q of[...w.keys()])(M.from&&Q.includes('"path":"'+String(M.from).replace(/"/g,'\\"')+'"')||M.to&&Q.includes('"path":"'+String(M.to).replace(/"/g,'\\"')+'"'))&&w.delete(Q);if(o.info({tool:I,success:J.success,durationMs:J.duration,retries:J.retries},"Tool executed"),!J.success&&Py(J.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}}f.isOverBudget()&&a.onNotice?.("Reached max reasoning steps ("+f.getConfig().maxSteps+"). Wrapping up.","warn")}return _>=m&&!T&&a.onNotice?.("Reached max iterations ("+m+"). Stopping.","warn"),o.info({summary:f.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:v,toolsUsed:Ee(g),toolResults:y,touchedFiles:Ee(b),iterations:_,success:!0,completedNaturally:T}}function Ee(t){return[...new Set(t)]}function Fl(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?Kt(e,Ry):Kt(e,Oy)}function Ll(t){return async(e,n)=>{let r=e.replace(/_/g," ");return!t.autoMode&&t.interactive?n==="confirm"&&t.confirm?await t.confirm("Proceed with "+r+"?")?"allow":"skip":n==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+r)?"allow":"skip":"allow":!t.autoMode&&n==="dangerous"?"skip":"allow"}}async function Dl(t){let{client:e,session:n,abortSignal:r,onStart:s,onChunk:i,onComplete:o}=t,a="",c=null;for(let l=0;l<2;l++)try{a="",s?.();for await(let u of e.streamChat(n.getMessages(),r)){if(r?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,i?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(n.getMessages(),[],r)).message?.content||"",a&&i?.(a)),n.addAssistantMessage(a||""),o?.(),a}catch(u){if(c=u,u?.name==="AbortError"||r?.aborted)throw u;let p=pe(u);if(p.fatal)throw new Error(p.message);if(l===1)throw new Error(p.message);await new Promise(h=>setTimeout(h,1e3))}throw c||new Error("Text turn failed")}function My(t){return["list_dir","read_file","search_codebase","get_file_info"].includes(t)?"Inspecting":["web_search"].includes(t)?"Researching":["scrape_url","extract_links","search_image_candidates","inspect_image"].includes(t)?"Fetching":["download_asset"].includes(t)?"Downloading":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing":["run_command","execute_code","detect_bugs"].includes(t)?"Running":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Git":"Working"}function ee(t){process.stdout.write(t)}function Kn(t){process.stdout.write(t+`
|
|
309
|
+
`)}async function Gn(t,e){let n=Cl(t),r=await $t(e.workingDir,e.config);if(e.session.updateSystemPrompt(Et(r,n.profile,e.workingDir)),n.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context.]",{priority:"critical",tags:["runtime-note","continuity"]}),n.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete fully in one pass without follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:["kind:"+n.profile.kind]}),!n.profile.needsTools){let m=new Ke("Thinking"),g=!1;m.start();try{let y=await Dl({client:e.client,session:e.session,onStart:()=>{},onChunk:b=>{g||(m.stop(),ee(Ge()+`
|
|
310
310
|
`),g=!0),ee(b)},onComplete:()=>{g&&ee(`
|
|
311
311
|
|
|
312
312
|
`)}});g||(m.stop(),Kn(Ge()),ee(jt(y)+`
|
|
313
|
-
`))}catch(y){m.stop();let b=pe(y);Kn(Ae(b.message))}try{Yt().flush()}catch{}return}let
|
|
313
|
+
`))}catch(y){m.stop();let b=pe(y);Kn(Ae(b.message))}try{Yt().flush()}catch{}return}let s=Qt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Zt(3),o=!1,a=!1,c=[],l=new Ke("Thinking"),u="",f=()=>{o&&(ee(`
|
|
314
314
|
`),o=!1,a=!1)},p={onModelStart:()=>{f(),o=!1,a=!1,l.stop(),l.start()},onModelStop:()=>{l.stop()},onStreamToken:m=>{m&&(o||(l.stop(),ee(Ge()+`
|
|
315
315
|
`),o=!0,a=!0),ee(m))},onAssistantText:async m=>{if(m?.trim()){if(c.push(m),a){f();return}l.stop(),ee(Ge()+`
|
|
316
316
|
`),ee(jt(m)+`
|
|
317
|
-
`)}},onToolStart:(m,g)=>{f(),l.stop();let y=
|
|
318
|
-
`),u=y),ee(
|
|
319
|
-
`)},onToolEnd:(m,g,y,b)=>{ee(
|
|
320
|
-
`)},onNotice:(m,g)=>{f();let y=g==="retry"?D("\u21BB "+m):D(m);Kn(y)},onError:m=>{f(),Kn(Ae(m))},onToolCall:()=>e.onToolCall?.()},h=
|
|
317
|
+
`)}},onToolStart:(m,g)=>{f(),l.stop();let y=My(m);y!==u&&(ee(ui(y)+`
|
|
318
|
+
`),u=y),ee(fi(m,g)+`
|
|
319
|
+
`)},onToolEnd:(m,g,y,b)=>{ee(di(g,y,b)+`
|
|
320
|
+
`)},onNotice:(m,g)=>{f();let y=g==="retry"?D("\u21BB "+m):D(m);Kn(y)},onError:m=>{f(),Kn(Ae(m))},onToolCall:()=>e.onToolCall?.()},h=Ll({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}),d=await Ys({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:h,reactEngine:s,errorRecovery:i,skipTools:!1});if(f(),d.toolsUsed.length>0&&c.length>0){let m=c[c.length-1];m?.trim()&&(ee(`
|
|
321
321
|
`+Ge()+`
|
|
322
322
|
`),ee(jt(m)+`
|
|
323
|
-
`))}if(n.profile.kind==="implementation"&&d.toolsUsed.length===0){e.session.addUserMessage("SYSTEM: This was an implementation task. You must use workspace tools to create or modify files. Please proceed with tool use now.",{priority:"critical",tags:["system-correction"]});let m=[];await
|
|
323
|
+
`))}if(n.profile.kind==="implementation"&&d.toolsUsed.length===0){e.session.addUserMessage("SYSTEM: This was an implementation task. You must use workspace tools to create or modify files. Please proceed with tool use now.",{priority:"critical",tags:["system-correction"]});let m=[];await Ys({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 y=>{y?.trim()&&m.push(y)}},safetyPolicy:h,reactEngine:Qt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Zt(3),skipTools:!1});let g=m[m.length-1];g?.trim()&&(ee(`
|
|
324
324
|
`+Ge()+`
|
|
325
325
|
`),ee(jt(g)+`
|
|
326
|
-
`))}try{Yt().flush()}catch{}}var
|
|
327
|
-
`)}async function
|
|
326
|
+
`))}try{Yt().flush()}catch{}}var Xs=k(require("fs")),Nl=k(require("path")),ve=k(require("os")),Ul=require("child_process");async function Jn(t){let e=[],n=process.version,r=parseInt(n.slice(1).split(".")[0],10);e.push({name:"Node.js",status:r>=20?"ok":r>=18?"warn":"error",message:r>=20?`${n} (recommended)`:r>=18?`${n} (works, but 20+ recommended)`:`${n} (too old, need 20+)`});let s=Nl.join(ve.homedir(),".hablas");if(e.push({name:"Config directory",status:Xs.existsSync(s)?"ok":"warn",message:Xs.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=ve.homedir();if(process.platform!=="win32"){let a=(0,Ul.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),c=a[3]||"unknown",l=a[4]||"?";e.push({name:"Disk space",status:parseInt(l)>90?"warn":"ok",message:`${c} available (${l} 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:`${ve.platform()} ${ve.arch()} \u2014 ${ve.cpus().length} cores, ${Math.round(ve.totalmem()/1024/1024/1024)}GB RAM`}),e}function Yn(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},n={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},r="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let c of t){let l=`${n[c.status]}${e[c.status]}${r}`,u=c.name.padEnd(18);i.push(` ${l} ${u}${s}${c.message}${r}`)}let o=t.filter(c=>c.status==="error").length,a=t.filter(c=>c.status==="warn").length;return i.push(""),o>0?i.push(` ${n.error}${o} error(s) found \u2014 fix these for hablas to work properly${r}`):a>0?i.push(` ${n.warn}${a} warning(s) \u2014 hablas should work but check the items above${r}`):i.push(` ${n.ok}All checks passed \u2014 hablas is ready!${r}`),i.push(""),i.join(`
|
|
327
|
+
`)}async function ql(t,e){let n=t.trim().split(/\s+/),r=n[0],s=n.slice(1);switch(r){case"/help":console.log(pi());return;case"/exit":case"/quit":return"quit";case"/about":console.log(mi());return;case"/version":console.log(gi());return;case"/clear":e.session.clear(),console.log(ke("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(!o.length){console.log(D("No history yet."));return}console.log("");for(let a of o){let c=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${c.padEnd(10)} ${a.content.replace(/\s+/g," ").slice(0,140)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(hi({model:e.client.getModel(),provider:nt(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(!s.length){console.log(D(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ").trim(),o=[];try{o=await e.client.listModels()}catch{}if(o.length>0){let a=o.find(l=>l.toLowerCase()===i.toLowerCase());if(a){e.config.model=a,e.client.setModel(a),Ye(e.config),console.log(ke(`Model \u2192 ${a}`));return}let c=o.filter(l=>l.toLowerCase().includes(i.toLowerCase())).slice(0,5);console.log(ie(`Model "${i}" not found in the available list.`)),c.length?(console.log(D("Did you mean one of these?")),c.forEach((l,u)=>console.log(` ${u+1}. ${l}`)),console.log(D(`Run /models ${i} to see the full list`))):console.log(D("Run /models to browse available models"));return}e.config.model=i,e.client.setModel(i),Ye(e.config),console.log(ke(`Model \u2192 ${i} (could not verify \u2014 offline)`));return}case"/models":{let i=[];try{i=await e.client.listModels()}catch{console.log(ie("Could not fetch model list -- check your connection."));return}let o=20,a=1,c="";if(s.length){let g=s[s.length-1].toLowerCase(),y=parseInt(g,10),b=["next","n","prev","previous","p"];if(!Number.isNaN(y)&&y>0)a=y,c=s.slice(0,-1).join(" ").toLowerCase().trim();else if(b.includes(g)){console.log(D("Use page numbers to navigate: /models 2, /models 3")),console.log(D("Search by name: /models qwen"));return}else c=s.join(" ").toLowerCase().trim()}let l=c?i.filter(g=>g.toLowerCase().includes(c)):i;if(!l.length){console.log(ie("No models matching: "+c)),console.log(D("Run /models to see all available models."));return}let u=Math.max(1,Math.ceil(l.length/o)),f=Math.min(Math.max(a,1),u),p=(f-1)*o,h=l.slice(p,p+o),d=e.client.getModel(),m=c?"Models + query + ":"Models";if(console.log(""),console.log(D(m+" | page "+f+"/"+u+" | "+l.length+" found")),console.log(""),h.forEach((g,y)=>{let w=g===d?" <- active":"";console.log(" "+String(p+y+1).padStart(3)+". "+g+w)}),console.log(""),f<u){let g="/models"+(c?" "+c:"")+" "+(f+1);console.log(D(g+" -- next page"))}if(f>1){let g="/models"+(c?" "+c:"")+" "+(f-1);console.log(D(g+" -- prev page"))}console.log(D("Switch model: /model <name>")),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(D(`Provider: ${nt(e.config)}`)),console.log(D(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ke("Connection OK"):Ae("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ue.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=ue.defaultModel);else if(i==="custom"){if(!s[1]){console.log(ie("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(ie("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=mt(e.config);e.setClient(o),Ye(e.config),console.log(ke(`Provider \u2192 ${nt(e.config)}`));return}case"/doctor":{let i=await Jn({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Yn(i));return}case"/workspace":{console.log(""),console.log(Un(Tt(e.workingDir))),console.log("");return}case"/memory":{if(s[0]==="clear"){e.accumulator&&e.accumulator.clear(),console.log(D("Long-context accumulator cleared (pinned entries kept)."));return}if(e.projectMemory){let o=e.projectMemory.getAll();console.log(""),console.log(ke(`Project Memory \xB7 ${o.length} entries \xB7 session #${e.projectMemory.sessionCount}`)),o.length||console.log(D(" No entries yet \u2014 Hablas learns as you work."));for(let a of o.slice(0,10))console.log(` [${a.kind.padEnd(10)}] ${a.title}`),a.files?.length&&console.log(` files: ${a.files.slice(0,3).join(", ")}`)}if(e.accumulator){let o=e.accumulator.getAll();if(o.length){console.log(""),console.log(ke(`Reasoning Accumulator \xB7 ${o.length} observations \xB7 turn #${e.accumulator.turnIndex}`));for(let a of o.slice(0,8)){let c=a.pinned?"\u{1F4CC} ":"";console.log(` ${c}[T${a.turnIndex}][${a.kind}] ${a.text.slice(0,70)}`)}}}console.log("");return}case"/diff":{let{exec:i}=await import("child_process"),o=s[0]||"",a=`git diff ${o?'"'+o+'"':""}`,c=await new Promise(l=>{i(a,{cwd:e.workingDir,maxBuffer:2*1024*1024},(u,f,p)=>{l(f||p||"No changes.")})});if(console.log(""),c.trim()){let l=c.split(`
|
|
328
328
|
`);for(let u of l.slice(0,100))u.startsWith("+")&&!u.startsWith("+++")?process.stdout.write(`\x1B[38;5;71m${u}\x1B[0m
|
|
329
329
|
`):u.startsWith("-")&&!u.startsWith("---")?process.stdout.write(`\x1B[38;5;131m${u}\x1B[0m
|
|
330
330
|
`):u.startsWith("@@")?process.stdout.write(`\x1B[38;5;110m${u}\x1B[0m
|
|
331
|
-
`):console.log(u);l.length>100&&console.log(D(`... ${l.length-100} more lines`))}else console.log(D("No changes to show."));console.log("");return}case"/checkpoint":{let i=
|
|
331
|
+
`):console.log(u);l.length>100&&console.log(D(`... ${l.length-100} more lines`))}else console.log(D("No changes to show."));console.log("");return}case"/checkpoint":{let i=s[0];if(!i||i==="list")console.log(D("Checkpoints: use the agent to manage checkpoints.")),console.log(D(' Tell Hablas: "save checkpoint before-refactor" or "list checkpoints"'));else if(i==="save"){let o=s[1]||"manual";console.log(D(`Telling Hablas to save checkpoint "${o}"...`)),e.session.addUserMessage(`checkpoint_save now, name="${o}", description="manual checkpoint from /checkpoint command"`,{priority:"critical",tags:["checkpoint","system-cmd"]}),console.log(D("Checkpoint request queued \u2014 continue typing to trigger it."))}return}case"/tests":{console.log(D('Running tests... tell Hablas: "run tests" for full output.'));return}case"/git":{let i=s[0];if(!i||i==="status"){let{exec:o}=await import("child_process"),a=await new Promise(c=>{o("git status --short --branch",{cwd:e.workingDir},(l,u)=>c(u))});console.log(""),console.log(a||"Not a git repo."),console.log("")}else if(i==="log"){let{exec:o}=await import("child_process"),a=await new Promise(c=>{o("git log --oneline -15",{cwd:e.workingDir},(l,u)=>c(u))});console.log(""),console.log(a||"No commits."),console.log("")}else console.log(ie("Usage: /git [status|log]"));return}default:console.log(ie(`Unknown command: ${r} \xB7 /help for reference`))}}var Me=k(require("fs")),Qs=k(require("path"));function Zs(t){let e=Qs.join(t,".hablas");return Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),e}function Bl(t){return Qs.join(Zs(t),"session.json")}function Xn(t,e){let n=Bl(t);try{return Me.existsSync(n)?(e.fromJSON(Me.readFileSync(n,"utf-8")),!0):!1}catch{return!1}}function tn(t,e){let n=Bl(t);try{Me.writeFileSync(n,e.toJSON(),"utf-8")}catch{}}async function Vl(t,e){Fi();let n=t.workingDirectory==="."?process.cwd():t.workingDirectory,r=mt(t);Zs(n);let s=new St(n,t),i=new vt(t),o=await $t(n,t),a=new kt(Et(o,Xt("hello")),t.historySize,t.contextBudget);Xn(n,a);let c=new Hn(n);console.log(ci(t.model,n));let l=new Ke("Connecting");l.start();let u=await r.checkConnection();if(l.stop(),u){let g=await r.listModels();console.log(ke(`${nt(t)} \xB7 ${g.length} models available`))}else console.log(ie(`offline \xB7 ${nt(t)} \xB7 file inspection still works \xB7 /provider to switch`));Hl.existsSync(Wl.join(n,".git"))||console.log(D("no git repository detected \u2014 standalone workspace mode")),console.log("");let f=0,p=0,h=Date.now(),d=0,m=null;for(wi({stop:()=>m?.stop()}),process.on("SIGINT",()=>{let g=Date.now();if(m?.stop(),m=null,g-d<1500){process.stdout.write(`
|
|
332
332
|
`);let y=Math.round((Date.now()-h)/1e3);console.log(D(`session ended \xB7 turns=${f} \xB7 tool calls=${p} \xB7 ${y}s`)),c.close(),process.exit(0)}d=g,process.stdout.write(`
|
|
333
|
-
`),console.log(ie("cancelled \u2014 Ctrl+C again to exit"))});;){let y=(await c.prompt(" \u203A ")).trim();if(y){if(y.startsWith("/")){let b=await
|
|
334
|
-
`);for(let{pattern:
|
|
335
|
-
`).length,u=
|
|
336
|
-
`),
|
|
337
|
-
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let n=t.issues.sort((s
|
|
338
|
-
`)}var At=k(require("fs")),
|
|
339
|
-
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let n=Object.entries(t.agentUsage).sort((
|
|
340
|
-
`)}var
|
|
333
|
+
`),console.log(ie("cancelled \u2014 Ctrl+C again to exit"))});;){let y=(await c.prompt(" \u203A ")).trim();if(y){if(y.startsWith("/")){let b=await ql(y,{config:t,client:r,setClient:w=>{r=w},session:a,workingDir:n});if(tn(n,a),b==="quit")break;continue}f++,console.log(li(f));try{await Gn(y,{config:t,client:r,registry:s,contextManager:i,session:a,workingDir:n,logger:e,input:c,interactive:!0,onToolCall:()=>{p++}}),tn(n,a)}catch(b){let w=b;if(w?.name==="AbortError")continue;console.log(Ae(w?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}c.close()}async function zl(t,e,n){let r=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=mt(e),i=new St(r,e),o=new vt(e),a=await $t(r,e),c=new kt(Et(a,Xt(t)),e.historySize,e.contextBudget);Xn(r,c),await Gn(t,{config:e,client:s,registry:i,contextManager:o,session:c,workingDir:r,logger:n,interactive:!1}),tn(r,c)}var Qn=k(require("fs")),ot=k(require("path")),Fy=[{pattern:/(?:api[_-]?key|apikey)\s*[:=]\s*['"][a-zA-Z0-9_\-]{20,}['"]/gi,name:"API Key",severity:"critical"},{pattern:/(?:secret|password|passwd|pwd)\s*[:=]\s*['"][^'"]{8,}['"]/gi,name:"Secret/Password",severity:"critical"},{pattern:/(?:aws_access_key_id)\s*[:=]\s*['"]?AKIA[A-Z0-9]{16}['"]?/gi,name:"AWS Access Key",severity:"critical"},{pattern:/(?:aws_secret_access_key)\s*[:=]\s*['"]?[A-Za-z0-9/+=]{40}['"]?/gi,name:"AWS Secret Key",severity:"critical"},{pattern:/ghp_[A-Za-z0-9]{36}/g,name:"GitHub Token",severity:"critical"},{pattern:/gho_[A-Za-z0-9]{36}/g,name:"GitHub OAuth Token",severity:"critical"},{pattern:/sk-[A-Za-z0-9]{48}/g,name:"OpenAI API Key",severity:"critical"},{pattern:/xox[baprs]-[A-Za-z0-9\-]{10,}/g,name:"Slack Token",severity:"high"},{pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,name:"Private Key",severity:"critical"},{pattern:/(?:mongodb(?:\+srv)?:\/\/)[^\s'"]+/g,name:"MongoDB Connection String",severity:"high"},{pattern:/(?:postgres|postgresql|mysql):\/\/[^\s'"]+/g,name:"Database URL",severity:"high"},{pattern:/(?:Bearer\s+)[A-Za-z0-9\-._~+/]+=*/g,name:"Bearer Token",severity:"medium"}],Ly=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Dy=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Ny(t,e){let n=[],r=e.split(`
|
|
334
|
+
`);for(let{pattern:s,name:i,severity:o}of Fy){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let l=e.substring(0,a.index).split(`
|
|
335
|
+
`).length,u=r[l-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||n.push({severity:o,type:"secret",file:t,line:l,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return n}function Uy(t,e){let n=[],r=e.split(`
|
|
336
|
+
`),s=ot.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&r.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&n.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&n.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&n.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),n}function Kl(t,e=[]){try{let n=Qn.readdirSync(t,{withFileTypes:!0});for(let r of n){if(Ly.has(r.name))continue;let s=ot.join(t,r.name);if(r.isDirectory())Kl(s,e);else if(r.isFile()){let i=ot.extname(r.name);Dy.has(i)||e.push(s)}}}catch{}return e}function Gl(t){let e=Date.now(),n=Kl(t),r=[];for(let o of n)try{let a=Qn.readFileSync(o,"utf-8"),c=ot.relative(t,o),l=Ny(c,a);r.push(...l);let u=Uy(c,a);r.push(...u)}catch{}let s=Date.now()-e,i={critical:r.filter(o=>o.severity==="critical").length,high:r.filter(o=>o.severity==="high").length,medium:r.filter(o=>o.severity==="medium").length,low:r.filter(o=>o.severity==="low").length,info:r.filter(o=>o.severity==="info").length};return{issues:r,scannedFiles:n.length,duration:s,summary:i}}function Jl(t){let e=[];if(e.push(`
|
|
337
|
+
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let n=t.issues.sort((r,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[r.severity]-i[s.severity]}).slice(0,10);for(let r of n){let s=r.severity==="critical"?"\u{1F534}":r.severity==="high"?"\u{1F7E0}":r.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${r.severity.toUpperCase()}] ${r.message}`),e.push(` File: ${r.file}${r.line?`:${r.line}`:""}`),e.push(` Fix: ${r.suggestion}`),e.push("")}}return e.join(`
|
|
338
|
+
`)}var At=k(require("fs")),ei=k(require("path")),Xl=k(require("os")),qy=ei.join(Xl.homedir(),".hablas"),Yl=ei.join(qy,"analytics.json");function Ql(){try{if(At.existsSync(Yl))return JSON.parse(At.readFileSync(Yl,"utf-8"))}catch{}return By()}function By(){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 Zl(t){let e=[];e.push(`
|
|
339
|
+
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let n=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Agents:");for(let[s,i]of n)e.push(` @${s}: ${i} uses`);e.push("")}let r=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Commands:");for(let[s,i]of r)e.push(` ${s}: ${i} calls`)}return e.join(`
|
|
340
|
+
`)}var eu=k(require("readline"));var ne="\x1B[36m",Zn="\x1B[32m",Fe="\x1B[33m",F="\x1B[2m",Le="\x1B[1m",C="\x1B[0m",Hy="\x1B[35m";function G(t,e){return new Promise(n=>t.question(e,r=>n(r)))}function Wy(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var nn={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function tu(t){let e=eu.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Le}${ne} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${C}`),console.log(`${Le}${ne} hablas \u2014 Setup Wizard${C}`),console.log(`${F} Configure your AI provider and model${C}`),console.log(`${Le}${ne} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${C}`),console.log(),console.log(`${Le} Choose your setup:${C}`),console.log(),console.log(` ${Hy}${Le}1${C}. ${Le}Hablas Integrated Engine${C} ${Zn}(instant \u2014 no setup needed)${C}`),console.log(` ${F}Pre-configured cloud AI, ready to use immediately${C}`),console.log(),console.log(` ${ne}${Le}2${C}. ${Le}Custom Provider${C} ${F}(bring your own API key)${C}`),console.log(` ${F}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${C}`),console.log(),(await G(e,` ${F}Your choice (1-2):${C} `)).trim()){case"1":{t.provider=nn.provider,t.apiUrl=nn.apiUrl,t.apiKey=Wy(),t.model=nn.model,Ye(t),console.log(),console.log(`${Zn} \u2713 Hablas Integrated Engine activated!${C}`),console.log(`${F} Model: ${nn.model}${C}`),console.log(`${F} API: ${nn.apiUrl}${C}`),console.log(`${F} No API key needed \u2014 everything is pre-configured.${C}`);break}case"2":{switch(console.log(),console.log(`${F} Select your provider:${C}`),console.log(` ${ne}a${C}. Ollama (local, free, private)`),console.log(` ${ne}b${C}. OpenAI API`),console.log(` ${ne}c${C}. Groq (fast, free tier)`),console.log(` ${ne}d${C}. OpenRouter (many models)`),console.log(` ${ne}e${C}. Together AI`),console.log(` ${ne}f${C}. DeepSeek`),console.log(` ${ne}g${C}. Custom OpenAI-compatible API`),console.log(` ${ne}h${C}. NVIDIA NIM (powerful cloud models)`),console.log(),(await G(e,` ${F}Your choice (a-h):${C} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await G(e,` ${F}Ollama host [http://localhost:11434]:${C} `)).trim(),i=(await G(e,` ${F}Model [qwen2.5-coder:7b]:${C} `)).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,` ${F}OpenAI API Key (sk-...):${C} `)).trim(),i=(await G(e,` ${F}Model [gpt-4o]:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),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,` ${F}Groq API Key (gsk_...):${C} `)).trim(),i=(await G(e,` ${F}Model [llama-3.3-70b-versatile]:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),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,` ${F}OpenRouter API Key (sk-or-...):${C} `)).trim(),i=(await G(e,` ${F}Model [anthropic/claude-3.5-sonnet]:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),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,` ${F}Together API Key:${C} `)).trim(),i=(await G(e,` ${F}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),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,` ${F}DeepSeek API Key:${C} `)).trim(),i=(await G(e,` ${F}Model [deepseek-chat]:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),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,` ${F}API base URL:${C} `)).trim(),i=(await G(e,` ${F}API key (optional):${C} `)).trim(),o=(await G(e,` ${F}Model ID:${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 URL is required \u2014 cancelled${C}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await G(e,` ${F}NVIDIA API Key (nvapi-...):${C} `)).trim();if(!s){console.log(`${Fe} \u26A0 No key provided \u2014 cancelled${C}`),console.log(`${F} Get your key at: https://build.nvidia.com/${C}`),e.close();return}console.log(),console.log(`${F} Available NVIDIA models:${C}`),ue.models.forEach((a,c)=>{console.log(` ${ne}${c+1}${C}. ${a}`)}),console.log();let i=(await G(e,` ${F}Model number [1]:${C} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ue.apiUrl,t.apiKey=s,t.model=ue.models[o]||ue.defaultModel;break}default:console.log(`${Fe} \u26A0 Invalid choice${C}`),e.close();return}Ye(t),console.log(),console.log(`${Zn} \u2713 Custom provider configured successfully${C}`),console.log(`${F} Provider: ${t.provider}${C}`),console.log(`${F} Model: ${t.model}${C}`);break}default:console.log(`${Fe} \u26A0 Invalid choice \u2014 please select 1 or 2${C}`),e.close();return}console.log(),console.log(`${Le}${Zn} \u2713 Setup complete!${C}`),console.log(`${F} Use ${ne}hablas${C}${F} for interactive mode or ${ne}hablas run "..."${C}${F} for one-shot execution.${C}`),console.log(),e.close()}xi();var nu=Ja(),ce=new Pi;ce.name("hablas").description(`Hablas CLI v${nu} \u2014 single-agent engineering runtime for the terminal.`).version(nu).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");ce.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ce.opts(),n=ft({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(n.autoMode=!0),e.timeout&&(n.timeout=parseInt(e.timeout,10));let r=ms(n);await zl(t,n,r)});ce.command("doctor").description("Run system diagnostics").action(async()=>{let t=ce.opts(),e=ft({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),n=await Jn({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Yn(n))});ce.command("info").description("Show workspace information").action(async()=>{let t=ce.opts(),e=ft({project:t.project});console.log(""),console.log(Un(Tt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ce.command("security").description("Run a security scan on the current project").action(async()=>{let t=ce.opts(),e=ft({project:t.project}),n=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Jl(Gl(n)))});ce.command("stats").description("Show local usage statistics").action(async()=>{console.log(Zl(Ql()))});ce.action(async()=>{let t=ce.opts(),e=ft({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 tu(e);return}let n=ms(e);await Vl(e,n)});ce.parse();
|