hablas-ai 1.2.1 → 1.2.3
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 +223 -376
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`).replace(/^/gm," ".repeat(i))}let
|
|
4
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,s,r=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=t-s;if(a<r)return e;let l=e.slice(0,s),
|
|
2
|
+
"use strict";var $g=Object.create;var cs=Object.defineProperty;var Eg=Object.getOwnPropertyDescriptor;var Cg=Object.getOwnPropertyNames;var Tg=Object.getPrototypeOf,Rg=Object.prototype.hasOwnProperty;var N=(n,e)=>()=>(n&&(e=n(n=0)),e);var H=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Pe=(n,e)=>{for(var t in e)cs(n,t,{get:e[t],enumerable:!0})},Pl=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Cg(e))!Rg.call(n,r)&&r!==t&&cs(n,r,{get:()=>e[r],enumerable:!(s=Eg(e,r))||s.enumerable});return n};var O=(n,e,t)=>(t=n!=null?$g(Tg(n)):{},Pl(e||!n||!n.__esModule?cs(t,"default",{value:n,enumerable:!0}):t,n)),Og=n=>Pl(cs({},"__esModule",{value:!0}),n);var _n=H(Hr=>{var us=class extends Error{constructor(e,t,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Fr=class extends us{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Hr.CommanderError=us;Hr.InvalidArgumentError=Fr});var ds=H(Br=>{var{InvalidArgumentError:Pg}=_n(),jr=class{constructor(e,t){switch(this.description=t||"",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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new Pg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Ig(n){let e=n.name()+(n.variadic===!0?"...":"");return n.required?"<"+e+">":"["+e+"]"}Br.Argument=jr;Br.humanReadableArgName=Ig});var Kr=H(Il=>{var{humanReadableArgName:Mg}=ds(),Ur=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(r=>!r._hidden),s=e._getHelpCommand();return s&&!s._hidden&&t.push(s),this.sortSubcommands&&t.sort((r,i)=>r.name().localeCompare(i.name())),t}compareOptions(e,t){let s=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return s(e).localeCompare(s(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),s=e._getHelpOption();if(s&&!s.hidden){let r=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!r&&!i?t.push(s):s.long&&!i?t.push(e.createOption(s.long,s.description)):s.short&&!r&&t.push(e.createOption(s.short,s.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let s=e.parent;s;s=s.parent){let r=s.options.filter(i=>!i.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(s=>Mg(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((s,r)=>Math.max(s,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((s,r)=>Math.max(s,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((s,r)=>Math.max(s,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let s="";for(let r=e.parent;r;r=r.parent)s=r.name()+" "+s;return s+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let s=`(${t.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,t){let s=t.padWidth(e,t),r=t.helpWidth||80,i=2,o=2;function a(p,g){if(g){let _=`${p.padEnd(s+o)}${g}`;return t.wrap(_,r-i,s+o)}return p}function l(p){return p.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,r,0),""]));let f=t.visibleArguments(e).map(p=>a(t.argumentTerm(p),t.argumentDescription(p)));f.length>0&&(c=c.concat(["Arguments:",l(f),""]));let h=t.visibleOptions(e).map(p=>a(t.optionTerm(p),t.optionDescription(p)));if(h.length>0&&(c=c.concat(["Options:",l(h),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(g=>a(t.optionTerm(g),t.optionDescription(g)));p.length>0&&(c=c.concat(["Global Options:",l(p),""]))}let m=t.visibleCommands(e).map(p=>a(t.subcommandTerm(p),t.subcommandDescription(p)));return m.length>0&&(c=c.concat(["Commands:",l(m),""])),c.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,s,r=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=t-s;if(a<r)return e;let l=e.slice(0,s),c=e.slice(s).replace(`\r
|
|
5
5
|
`,`
|
|
6
6
|
`),d=" ".repeat(s),h="\\s\u200B",m=new RegExp(`
|
|
7
|
-
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=
|
|
8
|
-
`?"":(
|
|
9
|
-
`)}};
|
|
7
|
+
|.{1,${a-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),p=c.match(m)||[];return l+p.map((g,_)=>g===`
|
|
8
|
+
`?"":(_>0?d:"")+g.trimEnd()).join(`
|
|
9
|
+
`)}};Il.Help=Ur});var Vr=H(Gr=>{var{InvalidArgumentError:Lg}=_n(),qr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Ng(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),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,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,s)=>{if(!this.argChoices.includes(t))throw new Lg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,s):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Dg(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Wr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,t){let s=t.attributeName();if(!this.dualOptions.has(s))return!0;let r=this.negativeOptions.get(s).presetArg,i=r!==void 0?r:!1;return t.negate===(i===e)}};function Dg(n){return n.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function Ng(n){let e,t,s=n.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),t=s.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Gr.Option=qr;Gr.DualOptions=Wr});var Ll=H(Ml=>{function Fg(n,e){if(Math.abs(n.length-e.length)>3)return Math.max(n.length,e.length);let t=[];for(let s=0;s<=n.length;s++)t[s]=[s];for(let s=0;s<=e.length;s++)t[0][s]=s;for(let s=1;s<=e.length;s++)for(let r=1;r<=n.length;r++){let i=1;n[r-1]===e[s-1]?i=0:i=1,t[r][s]=Math.min(t[r-1][s]+1,t[r][s-1]+1,t[r-1][s-1]+i),r>1&&s>1&&n[r-1]===e[s-2]&&n[r-2]===e[s-1]&&(t[r][s]=Math.min(t[r][s],t[r-2][s-2]+1))}return t[n.length][e.length]}function Hg(n,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=n.startsWith("--");t&&(n=n.slice(2),e=e.map(o=>o.slice(2)));let s=[],r=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Fg(n,o),l=Math.max(n.length,o.length);(l-a)/l>i&&(a<r?(r=a,s=[o]):a===r&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),t&&(s=s.map(o=>`--${o}`)),s.length>1?`
|
|
10
10
|
(Did you mean one of ${s.join(", ")}?)`:s.length===1?`
|
|
11
|
-
(Did you mean ${s[0]}?)`:""}
|
|
12
|
-
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new
|
|
13
|
-
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new
|
|
14
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),s=t(e).find(r=>this._findCommand(r));if(s){let r=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let r=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,o,"env")}),this}_optionEx(e,t,s,r,i){if(typeof t=="object"&&t instanceof
|
|
11
|
+
(Did you mean ${s[0]}?)`:""}Ml.suggestSimilar=Hg});var jl=H(Hl=>{var jg=require("node:events").EventEmitter,zr=require("node:child_process"),ht=require("node:path"),Yr=require("node:fs"),oe=require("node:process"),{Argument:Bg,humanReadableArgName:Ug}=ds(),{CommanderError:Jr}=_n(),{Help:Kg}=Kr(),{Option:Dl,DualOptions:qg}=Vr(),{suggestSimilar:Nl}=Ll(),Qr=class n extends jg{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:t=>oe.stdout.write(t),writeErr:t=>oe.stderr.write(t),getOutHelpWidth:()=>oe.stdout.isTTY?oe.stdout.columns:void 0,getErrHelpWidth:()=>oe.stderr.isTTY?oe.stderr.columns:void 0,outputError:(t,s)=>s(t)},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 t=this;t;t=t.parent)e.push(t);return e}command(e,t,s){let r=t,i=s;typeof r=="object"&&r!==null&&(i=r,r=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return r&&(l.description(r),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new n(e)}createHelp(){return Object.assign(new Kg,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,t){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 t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Bg(e,t)}argument(e,t,s,r){let i=this.createArgument(e,t);return typeof s=="function"?i.default(r).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.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,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,r]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(s);return o.helpOption(!1),r&&o.arguments(r),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),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,t){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,s){this._exitCallback&&this._exitCallback(new Jr(e,t,s)),oe.exit(e)}action(e){let t=s=>{let r=this.registeredArguments.length,i=s.slice(0,r);return this._storeOptionsAsProperties?i[r]=this:i[r]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Dl(e,t)}_callParseArg(e,t,s,r){try{return e.parseArg(t,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${r} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),s=t(e).find(r=>this._findCommand(r));if(s){let r=t(this._findCommand(s)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let r=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;r(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;r(i,o,"env")}),this}_optionEx(e,t,s,r,i){if(typeof t=="object"&&t instanceof Dl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,s);if(o.makeOptionMandatory(!!e.mandatory),typeof r=="function")o.default(i).argParser(r);else if(r instanceof RegExp){let a=r;r=(l,c)=>{let d=a.exec(l);return d?d[0]:c},o.default(i).argParser(r)}else o.default(r);return this.addOption(o)}option(e,t,s,r){return this._optionEx({},e,t,s,r)}requiredOption(e,t,s,r){return this._optionEx({mandatory:!0},e,t,s,r)}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,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,s){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(t=s.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){oe.versions?.electron&&(t.from="electron");let r=oe.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=oe.argv),this.rawArgs=e.slice();let s;switch(t.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":oe.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,t){let s=this._prepareUserArgs(e,t);return this._parseCommand([],s),this}async parseAsync(e,t){let s=this._prepareUserArgs(e,t);return await this._parseCommand([],s),this}_executeSubCommand(e,t){t=t.slice();let s=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,f){let h=ht.resolve(d,f);if(Yr.existsSync(h))return h;if(r.includes(ht.extname(f)))return;let m=r.find(p=>Yr.existsSync(`${h}${p}`));if(m)return`${h}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let d;try{d=Yr.realpathSync(this._scriptPath)}catch{d=this._scriptPath}a=ht.resolve(ht.dirname(d),a)}if(a){let d=i(a,o);if(!d&&!e._executableFile&&this._scriptPath){let f=ht.basename(this._scriptPath,ht.extname(this._scriptPath));f!==this._name&&(d=i(a,`${f}-${e._name}`))}o=d||o}s=r.includes(ht.extname(o));let l;oe.platform!=="win32"?s?(t.unshift(o),t=Fl(oe.execArgv).concat(t),l=zr.spawn(oe.argv[0],t,{stdio:"inherit"})):l=zr.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Fl(oe.execArgv).concat(t),l=zr.spawn(oe.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{oe.on(f,()=>{l.killed===!1&&l.exitCode===null&&l.kill(f)})});let c=this._exitCallback;l.on("close",d=>{d=d??1,c?c(new Jr(d,"commander.executeSubCommandAsync","(close)")):oe.exit(d)}),l.on("error",d=>{if(d.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",h=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
16
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!
|
|
17
|
+
- ${f}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)oe.exit(1);else{let f=new Jr(1,"commander.executeSubCommandAsync","(error)");f.nestedError=d,c(f)}}),this.runningCommand=l}_dispatchSubcommand(e,t,s){let r=this._findCommand(e);r||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,r,"preSubcommand"),i=this._chainOrCall(i,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(s));else return r._parseCommand(t,s)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,r,i)=>{let o=r;if(r!==null&&s.parseArg){let a=`error: command-argument value '${r}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,r,i,a)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((s,r)=>{let i=s.defaultValue;s.variadic?r<this.args.length?(i=this.args.slice(r),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):r<this.args.length&&(i=this.args[r],s.parseArg&&(i=e(s,i,s.defaultValue))),t[r]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let s=e,r=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{r.push({hookedCommand:i,callback:o})})}),t==="postAction"&&r.reverse(),r.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,t,s){let r=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{r=this._chainOrCall(r,()=>i(this,t))}),r}_parseCommand(e,t){let s=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),t=s.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){r(),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,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))r(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let r=s.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let r=e.find(i=>s.conflictsWith.includes(i.attributeName()));r&&this._conflictingOption(s,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],s=[],r=t,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){r===s&&r.push(l),r.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let d=i.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);a=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),i.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),d=this._findOption(l.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(c+1));continue}}if(o(l)&&(r=s),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&s.length===0){if(this._findCommand(l)){t.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){r.push(l),i.length>0&&r.push(...i);break}r.push(l)}return{operands:t,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let s=0;s<t;s++){let r=this.options[s].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){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 s=t||{},r=s.exitCode||1,i=s.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let r=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>
|
|
20
|
+
`),this.outputHelp({error:!0}));let s=t||{},r=s.exitCode||1,i=s.code||"commander.error";this._exit(r,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in oe.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,oe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qg(this.options),t=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&t(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,s.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(f=>f.negate&&a===f.attributeName()),d=this.options.find(f=>!f.negate&&a===f.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:d||o},r=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);r=r.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Nl(e,r)}let s=`error: unknown option '${e}'${t}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,s=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(i=>{r.push(i.name()),i.alias()&&r.push(i.alias())}),t=Nl(e,r)}let s=`error: unknown command '${e}'${t}`;this.error(s,{code:"commander.unknownCommand"})}version(e,t,s){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",s=s||"output the version number";let r=this.createOption(t,s);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let r=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(s=>Ug(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=ht.basename(e,ht.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},s;return t.error?s=r=>this._outputConfiguration.writeErr(r):s=r=>this._outputConfiguration.writeOut(r),t.write=e.write||s,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation(s);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),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 t=oe.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
22
|
Expecting one of '${s.join("', '")}'`);let r=`${e}Help`;return this.on(r,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
24
|
-
`);o=
|
|
25
|
-
`);a=d.pop()||"";for(let f of d){let h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let p=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;p&&(yield p)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function
|
|
26
|
-
`)}var
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Fl(n){return n.map(e=>{if(!e.startsWith("--inspect"))return e;let t,s="127.0.0.1",r="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?r=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],s=i[3],r=i[4]),t&&r!=="0"?`${t}=${s}:${parseInt(r)+1}`:e})}Hl.Command=Qr});var ql=H(Fe=>{var{Argument:Bl}=ds(),{Command:Xr}=jl(),{CommanderError:Wg,InvalidArgumentError:Ul}=_n(),{Help:Gg}=Kr(),{Option:Kl}=Vr();Fe.program=new Xr;Fe.createCommand=n=>new Xr(n);Fe.createOption=(n,e)=>new Kl(n,e);Fe.createArgument=(n,e)=>new Bl(n,e);Fe.Command=Xr;Fe.Option=Kl;Fe.Argument=Bl;Fe.Help=Gg;Fe.CommanderError=Wg;Fe.InvalidArgumentError=Ul;Fe.InvalidOptionArgumentError=Ul});var Vl={};Pe(Vl,{DEFAULT_CONFIG:()=>An,NVIDIA_PROVIDER:()=>Et});var An,Et,kn=N(()=>{"use strict";An={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",contextBudget:32e3,streamingEnabled:!0,autoConfirmSafe:!0,autoMode:!1,workingDirectory:".",historySize:800,timeout:12e4,maxRetries:3,tools:{runCommand:{allowedCommands:[],blocklist:[],timeout:12e4}},ui:{theme:"dark",showTokenCount:!0,diffPreview:!0,compactMode:!1,dashboard:!1},cache:{enabled:!0,maxEntries:100,ttlMs:3e5},logging:{level:"info",file:!0},plugins:{enabled:!0,directory:"~/.hablas/plugins",marketplace:"https://registry.hablas.dev/plugins"},agents:{enabled:!0,orchestration:"auto",maxConcurrent:3},context:{astParsing:!0,projectGraph:!0,longTermMemory:!0,fileWatcher:!0},workspace:{frameworkDetection:!0,gitAwareness:!0,envParsing:!0,autoPush:!1},security:{scanOnCommit:!1,secretDetection:!0,dependencyAudit:!0},analytics:{enabled:!0,trackUsage:!0,weeklyReports:!1},collaboration:{enabled:!1,teamConfigPath:".hablas/team.json",sharedMemory:!1},team:{enabled:!1,user:"",key:""},api:{enabled:!1,port:8080,host:"0.0.0.0",apiKey:""},license:{tier:"free",key:""}},Et={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.1-nemotron-70b-instruct","nvidia/nemotron-4-340b-instruct","meta/llama-3.1-405b-instruct","meta/llama-3.1-70b-instruct","meta/llama-3.1-8b-instruct","mistralai/mixtral-8x22b-instruct-v0.1","mistralai/mistral-large-latest","google/gemma-2-27b-it","microsoft/phi-3-medium-128k-instruct","deepseek-ai/deepseek-coder-33b-instruct","nvidia/llama-3.1-nemotron-51b-instruct","qwen/qwen2.5-coder-32b-instruct"]}});var fs,zl=N(()=>{"use strict";fs=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,t,s){let r={model:this.model,messages:e,stream:!1};t.length>0&&(r.tools=t);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,t){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:t});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let r=s.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await r.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
|
|
24
|
+
`);o=c.pop()||"";for(let d of c)if(d.trim())try{let f=JSON.parse(d);f.message?.content&&(yield f.message.content)}catch{}}}}});function Ql(n){return n.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let t=e.tool_calls.filter(s=>s?.function?.name);if(t.length>0)return{role:"assistant",content:e.content||null,tool_calls:t.map((s,r)=>({id:`call_${r}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Yg(n){return n.map(e=>({type:"function",function:e.function}))}function Jg(n){return n.filter(e=>e?.function?.name).map(e=>{let t={};try{t=JSON.parse(e.function?.arguments||"{}")}catch{t={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:t}}})}function Xl(n){return new Promise(e=>setTimeout(e,n))}function Zl(n,e){return!(n.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var Yl,Vg,ps,Jl,zg,Dt,Zr=N(()=>{"use strict";Yl=12e4,Vg=6e4,ps=3,Jl=1e3,zg=20;Dt=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=[],t=!0,s,r=0;for(;t&&r<zg;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;s&&o.set("after",s),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Vg)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(d=>d.id||d.name||d).filter(Boolean)),t=!1;else if(c.data&&Array.isArray(c.data)){let d=c.data.map(f=>f.id||f.name).filter(Boolean);e.push(...d),c.has_more&&d.length>0?(s=d[d.length-1],r++):t=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(d=>d.name||d.id).filter(Boolean)),t=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,t,s){let r=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:Ql(e)};t.length>0&&(i.tools=Yg(t),i.tool_choice="auto");let o=null;for(let a=0;a<=ps;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),Yl),d={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let f=await fetch(r,d);if(clearTimeout(c),!f.ok){let g=await f.text().catch(()=>"");if(!Zl(null,f.status))throw new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`);if(o=new Error(`API error: ${f.status} ${f.statusText} \u2014 ${g}`),a<ps){let _=Jl*Math.pow(2,a);await Xl(_);continue}throw o}let m=(await f.json()).choices?.[0];if(!m)throw new Error("API returned empty response");let p=m.message.tool_calls?Jg(m.message.tool_calls):void 0;return{message:{role:m.message.role||"assistant",content:m.message.content||"",tool_calls:p},done:!0,done_reason:m.finish_reason}}catch(f){if(clearTimeout(c),f.name==="AbortError"&&s?.aborted)throw f;if(Zl(f)&&(o=f,a<ps)){let h=Jl*Math.pow(2,a);await Xl(h);continue}throw f}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=ps)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,t){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:Ql(e),stream:!0}),signal:t||AbortSignal.timeout(Yl)});if(!r.ok)throw new Error(`API error: ${r.status} ${r.statusText}`);let i=r.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let d=a.split(`
|
|
25
|
+
`);a=d.pop()||"";for(let f of d){let h=f.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let p=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;p&&(yield p)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}}});function He(n){if(n.provider==="nvidia"){let e={...n,provider:"custom",apiUrl:Et.apiUrl};return new Dt(e)}return n.provider==="custom"&&n.apiUrl?new Dt(n):new fs(n)}function ec(n){if(n.provider==="nvidia")return"NVIDIA NIM";if(n.provider==="custom")try{return`Custom (${new URL(n.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var $n=N(()=>{"use strict";kn();zl();Zr()});var tc=N(()=>{"use strict"});function Nt(){let n={providers:[],activeProvider:null,activeModel:null};try{if(mt.existsSync(ti)){let e=mt.readFileSync(ti,"utf-8"),t=JSON.parse(e);return{...n,...t}}}catch{}return n}function si(n){mt.existsSync(ei)||mt.mkdirSync(ei,{recursive:!0}),mt.writeFileSync(ti,JSON.stringify(n,null,2),"utf-8")}function ze(n){let e=Nt();e.providers=e.providers.filter(t=>t.name!==n.name),e.providers.push(n),si(e)}function sc(n){let e=Nt(),t=e.providers.length;return e.providers=e.providers.filter(s=>s.name!==n),e.providers.length<t?(e.activeProvider===n&&(e.activeProvider=null,e.activeModel=null),si(e),!0):!1}function rc(n){return Nt().providers.find(t=>t.name.toLowerCase()===n.toLowerCase())}function hs(){return Nt().providers}function ic(n,e){let t=Nt(),s=t.providers.find(r=>r.name===n);s&&(t.activeProvider=n,t.activeModel=e||s.defaultModel,si(t))}function oc(n,e){if(n.length===0)return" No saved providers. Use /addmodel to add one.";let t=[];t.push(" Saved Providers:"),t.push("");for(let s of n){let r=s.name===e,i=r?" \u25CF active":"",o=s.apiKey?"***"+s.apiKey.slice(-4):"no key";t.push(` ${r?"\u25B8":"\xB7"} ${s.name}${i}`),t.push(` URL: ${s.apiUrl}`),t.push(` Key: ${o}`),t.push(` Model: ${s.defaultModel}`),t.push(` Added: ${new Date(s.addedAt).toLocaleDateString()}`),t.push("")}return t.join(`
|
|
26
|
+
`)}var mt,ni,nc,ei,ti,ri=N(()=>{"use strict";mt=O(require("fs")),ni=O(require("path")),nc=O(require("os"));tc();ei=ni.join(nc.homedir(),".hablas"),ti=ni.join(ei,"models.json")});function ys(){try{if(gt.existsSync(ms))return JSON.parse(gt.readFileSync(ms,"utf-8"))}catch{}return{}}function lc(n){let e=gs.dirname(ms);gt.existsSync(e)||gt.mkdirSync(e,{recursive:!0}),gt.writeFileSync(ms,JSON.stringify(n,null,2),"utf-8")}function cc(n,e){let t=ys();t[n]=e,lc(t)}function uc(n){let e=ys();return e[n]?(delete e[n],lc(e),!0):!1}function dc(n){let e=ys(),t=n.trim();for(let[s,r]of Object.entries(e))if(t===s||t.startsWith(s+" "))return t.replace(s,r);return n}function fc(){let n=ys(),e=Object.entries(n);return e.length===0?` No aliases defined.
|
|
27
27
|
Use: /alias set <name> <command>`:e.map(([t,s])=>` ${t} \u2192 ${s}`).join(`
|
|
28
|
-
`)}var
|
|
28
|
+
`)}var gt,gs,ac,ms,ii=N(()=>{"use strict";gt=O(require("fs")),gs=O(require("path")),ac=O(require("os")),ms=gs.join(ac.homedir(),".hablas","aliases.json")});var mc={};Pe(mc,{disablePlugin:()=>ci,enablePlugin:()=>li,ensurePluginsDir:()=>ws,listPlugins:()=>hc,renderPlugins:()=>ui});function ai(){try{if(Ie.existsSync(vs))return JSON.parse(Ie.readFileSync(vs,"utf-8"))}catch{}return{disabled:[]}}function pc(n){let e=Xt.dirname(vs);Ie.existsSync(e)||Ie.mkdirSync(e,{recursive:!0}),Ie.writeFileSync(vs,JSON.stringify(n,null,2),"utf-8")}function ws(){Ie.existsSync(bs)||Ie.mkdirSync(bs,{recursive:!0})}function hc(){ws();let n=ai(),e=[];try{let t=Ie.readdirSync(bs).filter(s=>s.endsWith(".js"));for(let s of t){let r=Xt.join(bs,s);try{let i=require(r);e.push({name:i.name||s.replace(".js",""),description:i.description||"No description",version:i.version||"0.0.0",enabled:!n.disabled.includes(i.name||s.replace(".js","")),path:r,commands:i.commands})}catch{e.push({name:s.replace(".js",""),description:"Failed to load",version:"?",enabled:!1,path:r})}}}catch{}return e}function li(n){let e=ai(),t=e.disabled.indexOf(n);return t!==-1?(e.disabled.splice(t,1),pc(e),!0):!1}function ci(n){let e=ai();return e.disabled.includes(n)?!1:(e.disabled.push(n),pc(e),!0)}function ui(){let n=hc();return n.length===0?` No plugins installed.
|
|
29
29
|
Add .js files to ~/.hablas/plugins/`:n.map(e=>{let t=e.enabled?"\u25CF enabled":"\u25CB disabled";return` ${e.name} v${e.version} [${t}]
|
|
30
30
|
${e.description}`}).join(`
|
|
31
31
|
|
|
32
|
-
`)}var
|
|
33
|
-
`)}var
|
|
34
|
-
`)}var
|
|
32
|
+
`)}var Ie,Xt,oi,bs,vs,di=N(()=>{"use strict";Ie=O(require("fs")),Xt=O(require("path")),oi=O(require("os")),bs=Xt.join(oi.homedir(),".hablas","plugins"),vs=Xt.join(oi.homedir(),".hablas","plugins.json")});var bc={};Pe(bc,{renderDiagnostics:()=>hi,runDiagnostics:()=>pi});async function pi(n){let e=[],t=process.version,s=parseInt(t.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${t} (recommended)`:s>=18?`${t} (works, but 20+ recommended)`:`${t} (too old, need 20+)`});let r=gc.join(Ye.homedir(),".hablas");if(e.push({name:"Config directory",status:fi.existsSync(r)?"ok":"warn",message:fi.existsSync(r)?r:"Not created yet (will be created on first use)"}),n.provider==="ollama")try{let i=await fetch(`${n.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=n.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=Ye.homedir();if(process.platform!=="win32"){let a=(0,yc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:n.model?"ok":"warn",message:n.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Ye.platform()} ${Ye.arch()} \u2014 ${Ye.cpus().length} cores, ${Math.round(Ye.totalmem()/1024/1024/1024)}GB RAM`}),e}function hi(n){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},t={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",r="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of n){let c=`${t[l.status]}${e[l.status]}${s}`,d=l.name.padEnd(18);i.push(` ${c} ${d}${r}${l.message}${s}`)}let o=n.filter(l=>l.status==="error").length,a=n.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${t.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${t.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${t.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
|
|
33
|
+
`)}var fi,gc,Ye,yc,mi=N(()=>{"use strict";fi=O(require("fs")),gc=O(require("path")),Ye=O(require("os")),yc=require("child_process")});function gi(n){let e=n.trim();return!!(e.length<15&&!vc.test(e)||Qg.test(e)||Xg.test(e)||Zg.test(e)||ey.test(e))}function wc(n){let e=n.toLowerCase(),t=["hablas"];return gi(n)||(/\b(design|architect|schema|structure|api\s*design|database\s*design|system\s*design|blueprint|uml|erd|class\s*diagram)\b/i.test(e)&&t.push("bob"),/\b(create|build|implement|write|generate|code|function|component|class|fix|bug|debug|deploy|docker|ci\/cd|test|refactor|edit|modify|update|change)\b/i.test(e)&&t.push("alex"),/\b(research|find\s+info|search\s+for|documentation|how\s+to|best\s+practice|compare|analyze|data\s+analysis|optimize|benchmark|explain\s+concept)\b/i.test(e)&&t.push("david"),/\b(prd|product\s*requirements|user\s*stories|market\s*research|competitive\s*analysis|requirements\s*document|feature\s*spec|product\s*spec|stakeholder|user\s*needs|roadmap)\b/i.test(e)&&t.push("emma"),t.length===1&&vc.test(n)&&t.push("alex")),t}function xc(n,e){let t=[],s=1,r=e.includes("emma"),i=e.includes("bob"),o=e.includes("alex"),a=e.includes("david");if(r&&t.push({id:`task-${s++}`,role:"emma",agentName:"Emma",description:"Analyze requirements, create PRD, and define user stories",input:n,dependencies:[],status:"pending"}),a&&t.push({id:`task-${s++}`,role:"david",agentName:"David",description:"Research requirements, best practices, and relevant documentation",input:n,dependencies:r?[t.find(c=>c.role==="emma").id]:[],status:"pending"}),i){let c=[];a?c.push(t.find(d=>d.role==="david").id):r&&c.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"bob",agentName:"Bob",description:"Design system architecture and structure",input:n,dependencies:c,status:"pending"})}if(o){let c=[];i?c.push(t.find(d=>d.role==="bob").id):a?c.push(t.find(d=>d.role==="david").id):r&&c.push(t.find(d=>d.role==="emma").id),t.push({id:`task-${s++}`,role:"alex",agentName:"Alex",description:"Implement the code based on architecture/requirements",input:n,dependencies:c,status:"pending"})}let l="sequential";return t.length>2&&t.some(c=>c.dependencies.length===0)&&(l="mixed"),{id:`plan-${Date.now()}`,description:`Orchestration plan for: ${n.substring(0,100)}`,tasks:t,strategy:l,createdAt:new Date,approved:!1}}function Sc(){let n=[];for(let e of ge){let s=e.role==="hablas"?" \u2605":"";n.push(` @${e.name}${s} \u2014 ${e.title}`),n.push(` ${e.description}`)}return n.join(`
|
|
34
|
+
`)}var ge,Qg,Xg,Zg,ey,vc,En=N(()=>{"use strict";ge=[{role:"hablas",name:"Hablas",title:"Team Leader",description:"Software Engineer & Team Coordinator. Receives user requests, creates plans, distributes tasks, and compiles final responses.",expertise:["planning","coordination","architecture","code-review","decision-making"]},{role:"bob",name:"Bob",title:"Architect",description:"System Architect. Designs software architecture, database schemas, API structures, and system blueprints.",expertise:["system-design","architecture","database","api-design","scalability"]},{role:"alex",name:"Alex",title:"Engineer",description:"Full-Stack Engineer. Implements code, builds features, fixes bugs, handles DevOps and deployment.",expertise:["coding","implementation","debugging","devops","testing","deployment"]},{role:"david",name:"David",title:"Data Analyst",description:"Data & Research Specialist. Handles research, data analysis, documentation, and information gathering.",expertise:["research","data-analysis","documentation","ml","optimization"]},{role:"emma",name:"Emma",title:"Product Manager",description:"Product Manager. Analyzes user needs, creates PRDs, competitive analysis, market research, and requirement specifications.",expertise:["product-management","requirements","prd","market-research","competitive-analysis","user-stories"]}],Qg=/^(hi|hello|hey|howdy|yo|sup|hiya|good\s*(morning|afternoon|evening|night)|what'?s\s*up|greetings)\b/i,Xg=/^(مرحبا|أهلا|أهلاً|هلا|السلام\s*عليكم|وعليكم\s*السلام|كيف\s*حالك|كيفك|شلونك|صباح\s*الخير|مساء\s*الخير|شكرا|شكراً|يعطيك\s*العافية|تمام|اهلين|هلو|مرحبتين|الله\s*يسلمك|حياك|حياك\s*الله|يا\s*هلا|كيف\s*الحال|اخبارك|شخبارك)/i,Zg=/^(thanks?|thank\s*you|bye|goodbye|see\s*ya|ok(ay)?|yes|no|yep|nope|cool|nice|great|got\s*it|sure|alright|fine|good|perfect|awesome|amazing|wow|lol|haha|hmm|well|right|exactly|indeed|absolutely|of\s*course|no\s*problem|you'?re\s*welcome|np)\s*[.!?]*$/i,ey=/^(how\s*are\s*you|what'?s\s*your\s*name|who\s*are\s*you|what\s*can\s*you\s*do|help|can\s*you\s*help|what\s*is\s*this|tell\s*me\s*about\s*yourself)\s*[?!.]*$/i,vc=/\b(create|build|implement|write|generate|code|make|develop|design|architect|setup|configure|install|deploy|fix|debug|refactor|rewrite|restructure|migrate|convert|add|remove|delete|update|change|modify|edit|move|rename|test|run|execute|analyze|research|find|search|compare|optimize|benchmark)\b/i});function Cn(){try{if(Zt.existsSync(yi)){let n=Zt.readFileSync(yi,"utf-8"),e=JSON.parse(n);return{..._c,...e}}}catch{}return{..._c}}function kc(){return yi}var Zt,bi,Ac,yi,_c,vi=N(()=>{"use strict";Zt=O(require("fs")),bi=O(require("path")),Ac=O(require("os")),yi=bi.join(Ac.homedir(),".hablas","agents.json"),_c={hablas:{model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{model:"stepfun-ai/step-3.7-flash",temperature:.6}}});var ki={};Pe(ki,{formatStats:()=>ay,loadStats:()=>Tn,saveStats:()=>_i,trackAgentUsage:()=>ry,trackFileModified:()=>iy,trackMessage:()=>sy,trackSession:()=>ny,trackToolCall:()=>Ai});function Tn(){try{if(yt.existsSync(xi))return JSON.parse(yt.readFileSync(xi,"utf-8"))}catch{}return ty()}function _i(n){try{yt.existsSync(wi)||yt.mkdirSync(wi,{recursive:!0}),yt.writeFileSync(xi,JSON.stringify(n,null,2))}catch{}}function ty(){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 ny(n){return n.totalSessions++,n.lastUsed=new Date().toISOString(),oy(n),n}function sy(n,e=0){n.totalMessages++,n.totalTokensUsed+=e;let t=xs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].messages++,n.dailyActivity[t].tokens+=e,n}function Ai(n,e){n.totalToolCalls++,n.commandUsage[e]=(n.commandUsage[e]||0)+1;let t=xs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].toolCalls++,n}function ry(n,e){return n.agentUsage[e]=(n.agentUsage[e]||0)+1,n}function iy(n,e=0){n.totalFilesModified++,n.totalLinesWritten+=e;let t=xs();return n.dailyActivity[t]||(n.dailyActivity[t]={messages:0,tokens:0,toolCalls:0,filesModified:0,linesWritten:0}),n.dailyActivity[t].filesModified++,n.dailyActivity[t].linesWritten+=e,n}function oy(n){let e=xs(),t=Ec(new Date(Date.now()-864e5));n.dailyActivity[t]||n.dailyActivity[e]?n.streak++:n.streak=1,n.streak>n.longestStreak&&(n.longestStreak=n.streak)}function xs(){return Ec(new Date)}function Ec(n){return n.toISOString().split("T")[0]}function ay(n){let e=[];e.push(`
|
|
35
35
|
\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: ${n.totalSessions}`),e.push(` Messages: ${n.totalMessages}`),e.push(` Tokens used: ${n.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${n.totalToolCalls}`),e.push(` Files modified: ${n.totalFilesModified}`),e.push(` Lines written: ${n.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${n.totalBugsFixed}`),e.push(` Commits: ${n.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${n.streak} days (best: ${n.longestStreak})`),e.push("");let t=Object.entries(n.agentUsage).sort((r,i)=>i[1]-r[1]).slice(0,5);if(t.length>0){e.push(" Top Agents:");for(let[r,i]of t)e.push(` @${r}: ${i} uses`);e.push("")}let s=Object.entries(n.commandUsage).sort((r,i)=>i[1]-r[1]).slice(0,5);if(s.length>0){e.push(" Top Commands:");for(let[r,i]of s)e.push(` ${r}: ${i} calls`)}return e.join(`
|
|
36
|
-
`)}var
|
|
37
|
-
`);for(let{pattern:r,name:i,severity:o}of
|
|
38
|
-
`).length,d=s[
|
|
39
|
-
`),r=
|
|
36
|
+
`)}var yt,Si,$c,wi,xi,Rn=N(()=>{"use strict";yt=O(require("fs")),Si=O(require("path")),$c=O(require("os")),wi=Si.join($c.homedir(),".hablas"),xi=Si.join(wi,"analytics.json")});var Tc={};Pe(Tc,{formatScanResults:()=>Ei,runSecurityScan:()=>$i});function dy(n,e){let t=[],s=e.split(`
|
|
37
|
+
`);for(let{pattern:r,name:i,severity:o}of ly){r.lastIndex=0;let a;for(;(a=r.exec(e))!==null;){let c=e.substring(0,a.index).split(`
|
|
38
|
+
`).length,d=s[c-1]||"";d.trim().startsWith("#")||d.trim().startsWith("//")||n.includes(".example")||n.includes(".sample")||t.push({severity:o,type:"secret",file:n,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return t}function fy(n,e){let t=[],s=e.split(`
|
|
39
|
+
`),r=Ft.extname(n);return[".ts",".js",".tsx",".jsx"].includes(r)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&t.push({severity:"high",type:"code",file:n,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)&&t.push({severity:"medium",type:"code",file:n,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)&&t.push({severity:"high",type:"code",file:n,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),t}function Cc(n,e=[]){try{let t=Ss.readdirSync(n,{withFileTypes:!0});for(let s of t){if(cy.has(s.name))continue;let r=Ft.join(n,s.name);if(s.isDirectory())Cc(r,e);else if(s.isFile()){let i=Ft.extname(s.name);uy.has(i)||e.push(r)}}}catch{}return e}function $i(n){let e=Date.now(),t=Cc(n),s=[];for(let o of t)try{let a=Ss.readFileSync(o,"utf-8"),l=Ft.relative(n,o),c=dy(l,a);s.push(...c);let d=fy(l,a);s.push(...d)}catch{}let r=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:t.length,duration:r,summary:i}}function Ei(n){let e=[];if(e.push(`
|
|
40
40
|
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: ${n.scannedFiles}`),e.push(` Duration: ${n.duration}ms`),e.push(""),n.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${n.issues.length}`),e.push(` Critical: ${n.summary.critical}`),e.push(` High: ${n.summary.high}`),e.push(` Medium: ${n.summary.medium}`),e.push(` Low: ${n.summary.low}`),e.push("");let t=n.issues.sort((s,r)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[s.severity]-i[r.severity]}).slice(0,10);for(let s of t){let r=s.severity==="critical"?"\u{1F534}":s.severity==="high"?"\u{1F7E0}":s.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${r} [${s.severity.toUpperCase()}] ${s.message}`),e.push(` File: ${s.file}${s.line?`:${s.line}`:""}`),e.push(` Fix: ${s.suggestion}`),e.push("")}}return e.join(`
|
|
41
|
-
`)}var
|
|
42
|
-
`).filter(Boolean)){let d=
|
|
43
|
-
... (truncated)`:e.trim()}catch{return""}}async function
|
|
44
|
-
`).filter(Boolean).map(s=>{let[r,i,o,a]=s.split("|");return{hash:r,message:i,author:o,date:a,files:[]}})}catch{return[]}}function
|
|
41
|
+
`)}var Ss,Ft,ly,cy,uy,Ci=N(()=>{"use strict";Ss=O(require("fs")),Ft=O(require("path")),ly=[{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"}],cy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),uy=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"])});var On={};Pe(On,{formatGitStatus:()=>vy,generateChangelogPrompt:()=>by,generateCommitPrompt:()=>gy,generatePRPrompt:()=>yy,getDetailedDiff:()=>hy,getGitStatus:()=>Ti,getRecentCommits:()=>my,getStagedDiff:()=>py});async function Ti(n){try{let{stdout:e}=await en("git branch --show-current",{cwd:n}),{stdout:t}=await en("git status --porcelain",{cwd:n}),s=e.trim(),r=[],i=[],o=[];for(let c of t.split(`
|
|
42
|
+
`).filter(Boolean)){let d=c.substring(0,2),f=c.substring(3);(d.startsWith("A")||d.startsWith("M")||d.startsWith("R"))&&d[0]!==" "&&r.push(f),(d[1]==="M"||d[1]==="D")&&i.push(f),d==="??"&&o.push(f)}let a=0,l=0;try{let{stdout:c}=await en("git rev-list --left-right --count HEAD...@{upstream}",{cwd:n}),d=c.trim().split(" ");a=parseInt(d[0])||0,l=parseInt(d[1])||0}catch{}return{branch:s,staged:r,modified:i,untracked:o,ahead:a,behind:l}}catch{return null}}async function py(n){try{let{stdout:e}=await en("git diff --cached --stat",{cwd:n});return e.trim()}catch{return""}}async function hy(n){try{let{stdout:e}=await en("git diff --cached",{cwd:n,maxBuffer:1048576});return e.length>1e4?e.substring(0,1e4)+`
|
|
43
|
+
... (truncated)`:e.trim()}catch{return""}}async function my(n,e=20){try{let{stdout:t}=await en(`git log --oneline --format="%H|%s|%an|%ai" -n ${e}`,{cwd:n});return t.trim().split(`
|
|
44
|
+
`).filter(Boolean).map(s=>{let[r,i,o,a]=s.split("|");return{hash:r,message:i,author:o,date:a,files:[]}})}catch{return[]}}function gy(n,e){return`Based on the following git diff, generate a concise, conventional commit message.
|
|
45
45
|
|
|
46
46
|
Rules:
|
|
47
47
|
- Use conventional commits format: type(scope): description
|
|
@@ -55,7 +55,7 @@ Staged files: ${e.join(", ")}
|
|
|
55
55
|
Diff:
|
|
56
56
|
${n}
|
|
57
57
|
|
|
58
|
-
Generate ONLY the commit message, nothing else.`}function
|
|
58
|
+
Generate ONLY the commit message, nothing else.`}function yy(n,e,t){let s=n.map(r=>`- ${r.message}`).join(`
|
|
59
59
|
`);return`Generate a comprehensive Pull Request description.
|
|
60
60
|
|
|
61
61
|
Base branch: ${e}
|
|
@@ -77,7 +77,7 @@ Format:
|
|
|
77
77
|
## Notes
|
|
78
78
|
(Any additional context)
|
|
79
79
|
|
|
80
|
-
Generate ONLY the PR description in markdown.`}function
|
|
80
|
+
Generate ONLY the PR description in markdown.`}function by(n,e){let t=n.map(s=>`- ${s.hash.substring(0,7)} ${s.message} (${s.author})`).join(`
|
|
81
81
|
`);return`Generate a changelog entry for version ${e} from these commits.
|
|
82
82
|
|
|
83
83
|
Commits:
|
|
@@ -98,9 +98,9 @@ Format:
|
|
|
98
98
|
### Removed
|
|
99
99
|
- (removed features)
|
|
100
100
|
|
|
101
|
-
Only include sections that have entries. Generate ONLY the changelog markdown.`}function
|
|
102
|
-
`)}var
|
|
103
|
-
`)}var
|
|
101
|
+
Only include sections that have entries. Generate ONLY the changelog markdown.`}function vy(n){let e=[];return e.push(` Branch: ${n.branch}`),(n.ahead>0||n.behind>0)&&e.push(` Sync: \u2191${n.ahead} \u2193${n.behind}`),n.staged.length>0&&e.push(` Staged: ${n.staged.length} file(s)`),n.modified.length>0&&e.push(` Modified: ${n.modified.length} file(s)`),n.untracked.length>0&&e.push(` Untracked: ${n.untracked.length} file(s)`),e.join(`
|
|
102
|
+
`)}var Rc,Oc,en,tn=N(()=>{"use strict";Rc=require("child_process"),Oc=require("util"),en=(0,Oc.promisify)(Rc.exec)});var Dc={};Pe(Dc,{detectFramework:()=>Pc,detectLanguage:()=>Mc,detectPackageManager:()=>Ic,formatWorkspaceInfo:()=>Ri,getGitBranch:()=>Lc,scanWorkspace:()=>_s});function Pc(n){let e=V.join(n,"package.json");if(G.existsSync(e))try{let t=JSON.parse(G.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(G.existsSync(V.join(n,"requirements.txt"))||G.existsSync(V.join(n,"pyproject.toml")))try{let t=G.existsSync(V.join(n,"requirements.txt"))?G.readFileSync(V.join(n,"requirements.txt"),"utf-8"):"";if(t.includes("django"))return"django";if(t.includes("flask"))return"flask";if(t.includes("fastapi"))return"fastapi"}catch{}if(G.existsSync(V.join(n,"Cargo.toml")))try{if(G.readFileSync(V.join(n,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(G.existsSync(V.join(n,"go.mod")))try{if(G.readFileSync(V.join(n,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Ic(n){return G.existsSync(V.join(n,"pnpm-lock.yaml"))?"pnpm":G.existsSync(V.join(n,"yarn.lock"))?"yarn":G.existsSync(V.join(n,"bun.lockb"))?"bun":G.existsSync(V.join(n,"package-lock.json"))?"npm":G.existsSync(V.join(n,"Cargo.toml"))?"cargo":G.existsSync(V.join(n,"go.mod"))?"go":G.existsSync(V.join(n,"requirements.txt"))||G.existsSync(V.join(n,"pyproject.toml"))?"pip":"unknown"}function Mc(n){return G.existsSync(V.join(n,"tsconfig.json"))?"TypeScript":G.existsSync(V.join(n,"package.json"))?"JavaScript":G.existsSync(V.join(n,"Cargo.toml"))?"Rust":G.existsSync(V.join(n,"go.mod"))?"Go":G.existsSync(V.join(n,"pyproject.toml"))||G.existsSync(V.join(n,"requirements.txt"))?"Python":"Unknown"}function Lc(n){let e=V.join(n,".git","HEAD");if(!G.existsSync(e))return null;try{let t=G.readFileSync(e,"utf-8").trim();return t.startsWith("ref: refs/heads/")?t.replace("ref: refs/heads/",""):t.substring(0,8)}catch{return null}}function _s(n){let e=Pc(n),t=Ic(n),s=Mc(n),r=Lc(n),i=G.existsSync(V.join(n,"Dockerfile"))||G.existsSync(V.join(n,"docker-compose.yml"))||G.existsSync(V.join(n,"docker-compose.yaml")),o=G.existsSync(V.join(n,".github","workflows"))||G.existsSync(V.join(n,".gitlab-ci.yml"))||G.existsSync(V.join(n,"Jenkinsfile")),a=G.existsSync(V.join(n,"__tests__"))||G.existsSync(V.join(n,"tests"))||G.existsSync(V.join(n,"test"))||G.existsSync(V.join(n,"spec")),l=G.existsSync(V.join(n,".git")),c=[],d=[".env",".env.local",".env.development",".env.production",".env.example"];for(let g of d)G.existsSync(V.join(n,g))&&c.push(g);let f=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let g of h)G.existsSync(V.join(n,g))&&f.push(g);let m=[],p=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let g of p)G.existsSync(V.join(n,g))&&m.push(g);return{rootPath:n,framework:e,packageManager:t,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:r,envFiles:c,configFiles:f,entryPoints:m}}function Ri(n){let e=[` Project: ${V.basename(n.rootPath)}`,` Framework: ${n.framework}`,` Language: ${n.language}`,` Package: ${n.packageManager}`,` Git: ${n.hasGit?`\u2713 (${n.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${n.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${n.hasCICD?"\u2713":"\u2717"}`,` Tests: ${n.hasTests?"\u2713":"\u2717"}`];return n.envFiles.length>0&&e.push(` Env files: ${n.envFiles.join(", ")}`),e.join(`
|
|
103
|
+
`)}var G,V,Oi=N(()=>{"use strict";G=O(require("fs")),V=O(require("path"))});function Nc(){return`
|
|
104
104
|
## Available Tools (HEP-1 Protocol)
|
|
105
105
|
|
|
106
106
|
You can execute tools by outputting a strict JSON block wrapped inside <action>...</action> tags.
|
|
@@ -181,58 +181,54 @@ You MUST NOT write any conversational text or explanation outside of these tags
|
|
|
181
181
|
1. ONLY ONE tool execution per turn. Wait for result before calling another.
|
|
182
182
|
2. The JSON block inside <action>...</action> MUST be valid JSON (use double quotes, escape newlines properly).
|
|
183
183
|
3. If you have no tools to run, output your response inside <response>...</response> tags. Do NOT use <action> tags if you are answering.
|
|
184
|
-
`.trim()}var
|
|
185
|
-
`)}function
|
|
186
|
-
`)}function
|
|
187
|
-
`)}function
|
|
188
|
-
`)}function
|
|
189
|
-
${(n==="Hablas"?
|
|
190
|
-
`)}function
|
|
191
|
-
`)}function
|
|
192
|
-
`)}function
|
|
193
|
-
`)
|
|
194
|
-
`)
|
|
195
|
-
`))}return s&&i.length>0&&t.push(...ou(i,r)),`
|
|
184
|
+
`.trim()}var Fc=N(()=>{"use strict"});function wy(){try{let n=[As.resolve(__dirname,"..","..","package.json"),As.resolve(__dirname,"..","package.json"),As.resolve(__dirname,"package.json")];for(let e of n)if(ks.existsSync(e)){let t=JSON.parse(ks.readFileSync(e,"utf-8"));if(t.version)return t.version}return"1.2.0"}catch{return"1.2.0"}}function ae(n,e){return Bc||!nn?n:`${e}${n}\x1B[0m`}function xy(n){let e=je();if(!n)return u.border("\u2500".repeat(e));let t=n.replace(/\x1b\[[0-9;]*m/g,""),s=Math.max(0,e-t.length-2),r=Math.floor(s/2),i=s-r;return u.border("\u2500".repeat(r))+" "+n+" "+u.border("\u2500".repeat(i))}function Sy(n,e=2){let t=je()-e;if(t<=0)return" ".repeat(e)+n;let s=n.split(" "),r=[],i="";for(let o of s)(i+" "+o).trim().length>t&&i?(r.push(i.trim()),i=o):i+=(i?" ":"")+o;return i&&r.push(i.trim()),r.map(o=>" ".repeat(e)+o).join(`
|
|
185
|
+
`)}function _y(n){let e=Math.max(...n.map(([t])=>t.length));return n.map(([t,s])=>` ${u.muted(t.padEnd(e))} ${s}`).join(`
|
|
186
|
+
`)}function Ay(n){if(Bc||!nn)return n;let e=["\x1B[38;5;111m","\x1B[38;5;111m","\x1B[38;5;141m","\x1B[38;5;141m","\x1B[38;5;117m","\x1B[38;5;117m"],t="";for(let s=0;s<n.length;s++){let r=Math.floor(s/n.length*e.length);t+=e[r]+n[s]}return t+"\x1B[0m"}function Kc(n,e){let t=je(),s=e?e.replace(Mi.homedir(),"~"):"",r=u.border("\u2554"+"\u2550".repeat(t-2)+"\u2557"),i=u.border("\u2560"+"\u2550".repeat(t-2)+"\u2563"),o=u.border("\u255A"+"\u2550".repeat(t-2)+"\u255D"),a="H A B L A S A I",l="EXECUTIVE SYSTEM COORDINATOR",c="developed by abdulmoin hablas",d=Math.max(0,Math.floor((t-2-a.length)/2)),f=u.border("\u2551")+" ".repeat(d)+u.strong(a)+" ".repeat(t-2-a.length-d)+u.border("\u2551"),h=Math.max(0,Math.floor((t-2-l.length)/2)),m=u.border("\u2551")+" ".repeat(h)+u.secondary(l)+" ".repeat(t-2-l.length-h)+u.border("\u2551"),p=Math.max(0,Math.floor((t-2-c.length)/2)),g=u.border("\u2551")+" ".repeat(p)+u.muted(c)+" ".repeat(t-2-c.length-p)+u.border("\u2551"),_=u.muted(`SYSTEM VERSION: v${jc}`),A=u.warning(`CORE MODEL: ${n}`);return["",r,f,m,c?g:"",i,` ${u.muted("\u25B8")} ${_}`,` ${u.muted("\u25B8")} ${A}`,s?` ${u.muted("\u25B8")} ${u.muted(`WORKSPACE: ${s}`)}`:"",` ${u.chrome("\u251C"+"\u2500".repeat(t-2)+"\u2524")}`,` ${u.muted(" \u203A")} ${u.secondary("Type naturally to get started")}`,` ${u.muted(" \u203A")} ${u.secondary("/help for commands \xB7 Ctrl+C to cancel \xB7 Ctrl+C\xD72 to exit")}`,o,""].filter(Boolean).join(`
|
|
187
|
+
`)}function qc(){let n=je();return[` ${u.border("\u2554"+"\u2550".repeat(n-4)+"\u2557")}`,` ${u.border("\u2551")} ${u.leader("\u2605 Hablas")} ${u.muted("Leader")} ${u.border("\u2551")} ${u.product("\u25C6 Emma")} ${u.muted("Product")} ${u.border("\u2551")} ${u.architect("\u25C6 Bob")} ${u.muted("Architect")} ${u.border("\u2551")} ${u.engineer("\u25C6 Alex")} ${u.muted("Engineer")} ${u.border("\u2551")} ${u.analyst("\u25C6 David")} ${u.muted("Analyst")} ${u.border("\u2551")}`,` ${u.border("\u255A"+"\u2550".repeat(n-4)+"\u255D")}`].join(`
|
|
188
|
+
`)}function Pn(n,e){return`
|
|
189
|
+
${(n==="Hablas"?u.leader:n==="Bob"?u.architect:n==="Alex"?u.engineer:n==="David"?u.analyst:n==="Emma"?u.product:u.primary)("\u25C6")} ${u.strong(n)} ${u.muted(`[${e.toUpperCase()}]`)}`}function Wc(n,e,t,s){let r=n==="Hablas"?u.leader:n==="Bob"?u.architect:n==="Alex"?u.engineer:n==="David"?u.analyst:n==="Emma"?u.product:u.primary,i=e==="Hablas"?u.leader:e==="Bob"?u.architect:e==="Alex"?u.engineer:e==="David"?u.analyst:e==="Emma"?u.product:u.primary,o=[];if(o.push(""),o.push(` ${r("\u2605")} ${r(n)} ${u.muted("\u2192")} ${u.strong("Delegating to")} ${i(`@${e}`)} ${u.muted(`(${t})`)}`),s){let a=s.length>80?s.slice(0,80)+"...":s;o.push(` ${u.muted(" \u2517")} ${u.secondary(a)}`)}return o.push(""),o.join(`
|
|
190
|
+
`)}function Gc(){let n=je();return["",u.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E"),` ${u.strong("Abdulmoin Hablas")} ${u.muted("\u2014 Full-Stack Developer")}`,u.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),"",` ${u.accent("\u25C6")} ${u.primary("Portfolio")} ${u.muted("https://portfolio-monopoly63s-projects.vercel.app/")}`,` ${u.accent("\u25C6")} ${u.primary("GitHub")} ${u.muted("https://github.com/Monopoly63?tab=repositories")}`,` ${u.accent("\u25C6")} ${u.primary("Telegram")} ${u.muted("https://t.me/Hablas_Trade")}`,` ${u.accent("\u25C6")} ${u.primary("WhatsApp")} ${u.muted("https://wa.me/13232128875")}`,` ${u.accent("\u25C6")} ${u.primary("Instagram")} ${u.muted("https://www.instagram.com/li0vy_")}`,"",u.chrome("\u251C"+"\u2500".repeat(n-2)+"\u2524"),` ${u.strong("Projects")}`,"",` ${u.muted("\u25B8")} AI Search Engine ${u.muted("\u2192")} ${u.highlight("https://ai-search-engine-ashy.vercel.app/")}`,` ${u.muted("\u25B8")} Trade Tracker ${u.muted("\u2192")} ${u.highlight("https://trade-tracker-monopoly63s-projects.vercel.app/")}`,` ${u.muted("\u25B8")} Tree Algo Lab ${u.muted("\u2192")} ${u.highlight("https://tree-algorithms-lab.vercel.app/")}`,"",u.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F"),""].join(`
|
|
191
|
+
`)}function Vc(){return["",` ${Ay("\u25C6 hablas")} ${u.success(`v${jc}`)}`,"",` ${u.muted("Runtime")} ${u.secondary(`Node.js ${process.version}`)}`,` ${u.muted("Platform")} ${u.secondary(`${process.platform} ${process.arch}`)}`,` ${u.muted("Author")} ${u.secondary("Abdulmoin Hablas")}`,` ${u.muted("License")} ${u.secondary("MIT")}`,""].join(`
|
|
192
|
+
`)}function Hc(n,e){let t=Math.min(je()-8,60),s=e?` ${u.accent(e)} `:"",r=`${u.error("\u25CF")} ${u.warning("\u25CF")} ${u.success("\u25CF")}`,i=` ${u.chrome("\u250C"+"\u2500".repeat(4))} ${r} ${u.chrome("\u2500".repeat(Math.max(0,t-10-(e?e.length+2:0))))}${s}`,o=String(n.length).length,a=n.map((c,d)=>{let f=u.lineNum(String(d+1).padStart(o)+" \u2502 "),h=u.codeBlock(c);return` ${u.chrome("\u2502")} ${f}${h}`}),l=` ${u.chrome("\u2514"+"\u2500".repeat(t))}`;return[i,...a,l]}function In(n){let e=n.split(`
|
|
193
|
+
`),t=[],s=!1,r="",i=[];for(let o of e){if(o.trimStart().startsWith("```")){s?(t.push(...Hc(i,r)),s=!1,i=[]):(s=!0,r=o.trimStart().slice(3).trim(),i=[]);continue}if(s){i.push(o);continue}if(/^#{1,3}\s/.test(o)){let l=o.replace(/^#+\s/,"");t.push(""),t.push(` ${u.strong(u.primary(l))}`);continue}if(/^[-*]\s/.test(o.trim())){let l=o.trim().slice(2),c=Pi(l);t.push(` ${u.accent("\u25B8")} ${c}`);continue}if(/^\d+\.\s/.test(o.trim())){let l=o.trim().match(/^(\d+)\.\s(.+)/);if(l){t.push(` ${u.muted(l[1]+".")} ${Pi(l[2])}`);continue}}if(!o.trim()){t.push("");continue}let a=Sy(Pi(o),2);t.push(...a.split(`
|
|
194
|
+
`))}return s&&i.length>0&&t.push(...Hc(i,r)),`
|
|
196
195
|
`+t.join(`
|
|
197
196
|
`)+`
|
|
198
|
-
`}function
|
|
197
|
+
`}function Pi(n){let e=n.replace(/`([^`]+)`/g,(t,s)=>u.highlight(s));return e=e.replace(/\*\*([^*]+)\*\*/g,(t,s)=>u.strong(u.primary(s))),e=e.replace(/\*([^*]+)\*/g,(t,s)=>`\x1B[3m${s}\x1B[23m`),e}function zc(n,e){let t=je(),s=` [TOOL: ${n.replace(/_/g," ").toUpperCase()}] `,r=` ${u.border("\u250C\u2500\u2500")}${u.accent(s)}${u.border("\u2500".repeat(Math.max(0,t-s.length-6)))}`,i=` ${u.border("\u2502")} ${u.secondary(e)}`,o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,t-8-o.length);return`
|
|
199
198
|
${r}
|
|
200
|
-
${i}${" ".repeat(a)} ${
|
|
201
|
-
`).filter(Boolean),d=
|
|
202
|
-
`)[0].slice(0,s-24);i=` ${
|
|
199
|
+
${i}${" ".repeat(a)} ${u.border("\u2502")}`}function Yc(n,e,t){let s=je(),r=u.muted(`${t}ms`),i="";if(n){let c=e.split(`
|
|
200
|
+
`).filter(Boolean),d=c.length;if(d>5){let f=c[0].slice(0,s-30).trim();i=` ${u.border("\u2502")} ${u.success("\u2713")} ${u.muted(`${d} lines`)} ${u.secondary(f+"\u2026")} ${r}`}else{let f=c.join(" \xB7 ").slice(0,s-24);i=` ${u.border("\u2502")} ${u.success("\u2713")} ${u.muted(f)} ${r}`}}else{let c=e.split(`
|
|
201
|
+
`)[0].slice(0,s-24);i=` ${u.border("\u2502")} ${u.error("\u2717")} ${u.error(c)} ${r}`}let o=i.replace(/\x1b\[[0-9;]*m/g,""),a=Math.max(0,s-8-o.length),l=` ${u.border("\u2514"+"\u2500".repeat(s-6)+"\u2518")}`;return`${i}${" ".repeat(a)} ${u.border("\u2502")}
|
|
203
202
|
${l}
|
|
204
|
-
`}function
|
|
205
|
-
`),t=[];for(let s of e)s.startsWith("+++")||s.startsWith("---")?t.push(` ${
|
|
206
|
-
`)}function
|
|
207
|
-
`+
|
|
208
|
-
`}function $e(n){return` ${
|
|
209
|
-
${
|
|
210
|
-
`+
|
|
211
|
-
${
|
|
212
|
-
|
|
213
|
-
`+
|
|
214
|
-
|
|
215
|
-
`+
|
|
216
|
-
`}function
|
|
217
|
-
`+
|
|
218
|
-
${
|
|
203
|
+
`}function Li(n){let e=n.split(`
|
|
204
|
+
`),t=[];for(let s of e)s.startsWith("+++")||s.startsWith("---")?t.push(` ${u.muted(s)}`):s.startsWith("+")?t.push(` ${u.added(s)}`):s.startsWith("-")?t.push(` ${u.removed(s)}`):s.startsWith("@@")?t.push(` ${u.hunk(s)}`):s.trim()&&t.push(` ${u.muted(s)}`);return t.join(`
|
|
205
|
+
`)}function Jc(n){let e=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"}),t=`${u.accent("\u25C6")} ${u.strong(u.primary(`Turn #${n}`))} ${u.muted(`\xB7 ${e} \xB7`)}`;return`
|
|
206
|
+
`+xy(t)+`
|
|
207
|
+
`}function $e(n){return` ${u.error("\u2717")} ${n}`}function sn(n,e){return` ${u.error("\u2717")} ${n}
|
|
208
|
+
${u.warning("\u2192")} ${u.muted(e)}`}function J(n){return` ${u.success("\u2713")} ${n}`}function xe(n){return` ${u.muted(n)}`}function B(n){return` ${u.warning("\u26A0")} ${n}`}function ky(n,e){let s=Math.round(Math.min(n,e)/Math.max(e,1)*16),r=e>0?n/e:0;return(r>.85?u.error:r>.6?u.warning:u.success)("\u2588".repeat(s))+u.muted("\u2591".repeat(16-s))}function Qc(n){let e=je(),t=n.connected?u.success("\u25CF connected"):u.error("\u25CB offline"),s=ky(n.cacheTokens,n.budgetTokens),r=[["model",u.highlight(n.model)],["mindset",u.accent(n.mindset||"coder")],["host",u.muted(n.host)],["directory",u.muted(n.directory.replace(Mi.homedir(),"~"))],["context",`${s} ${u.muted(`${n.cacheFiles} files \xB7 ${n.cacheTokens}/${n.budgetTokens} tokens`)}`],["turns",u.muted(String(n.turnCount))],["status",t]];return`
|
|
209
|
+
`+u.chrome("\u256D"+"\u2500".repeat(e-2)+"\u256E")+`
|
|
210
|
+
${u.accent("\u2726")} ${u.strong("Status")}
|
|
211
|
+
|
|
212
|
+
`+_y(r)+`
|
|
213
|
+
|
|
214
|
+
`+u.chrome("\u2570"+"\u2500".repeat(e-2)+"\u256F")+`
|
|
215
|
+
`}function Xc(){let n=je(),e=Math.max(...Ii.map(r=>r.cmd.length+(r.arg?r.arg.length+1:0))),t=Ii.map(({cmd:r,arg:i,desc:o})=>{let a=r.length+(i?i.length+1:0),l=" ".repeat(e-a+3);return` ${u.primary(r)}${i?" "+u.muted(i):""}${l}${u.secondary(o)}`}),s=["",` ${u.accent("\u2726")} ${u.strong("Tips")}`,"",` ${u.muted("\u25B8")} Use ${u.highlight("#filename")} to reference files inline`,` ${u.muted("\u25B8")} Press ${u.highlight("Ctrl+C")} once to cancel current operation`,` ${u.muted("\u25B8")} Press ${u.highlight("Ctrl+C\xD72")} quickly to exit CLI`,` ${u.muted("\u25B8")} Use ${u.highlight("--auto")} flag to skip tool confirmations`,` ${u.muted("\u25B8")} All file edits are backed up to ${u.muted("~/.hablas/backup/")}`,` ${u.muted("\u25B8")} Complex tasks \u2192 Hablas creates a plan \u2192 approve/edit \u2192 execute`];return`
|
|
216
|
+
`+u.chrome("\u256D"+"\u2500".repeat(n-2)+"\u256E")+`
|
|
217
|
+
${u.accent("\u2726")} ${u.strong("Commands")}
|
|
219
218
|
|
|
220
219
|
`+t.join(`
|
|
221
220
|
`)+`
|
|
222
221
|
`+s.join(`
|
|
223
222
|
`)+`
|
|
224
223
|
|
|
225
|
-
`+
|
|
226
|
-
`}function
|
|
227
|
-
`)}function
|
|
228
|
-
`)}
|
|
229
|
-
`)}
|
|
230
|
-
|
|
231
|
-
`);
|
|
232
|
-
`)
|
|
233
|
-
`+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:u,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function rb(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
|
|
234
|
-
`);switch(e){case"jest":case"vitest":{for(let a of o){let l=a.match(/Tests:\s+(\d+)\s+passed.*?(\d+)\s+total/);if(l&&(s=parseInt(l[1]),t=parseInt(l[2]),r=t-s),a.match(/✕|FAIL|✗|×/)){let d=a.replace(/.*(?:✕|FAIL|✗|×)\s*/,"").trim();d&&i.push(d)}}break}case"pytest":{for(let a of o){let l=a.match(/(\d+)\s+passed.*?(\d+)\s+failed/);l&&(s=parseInt(l[1]),r=parseInt(l[2]),t=s+r);let u=a.match(/(\d+)\s+passed/);u&&t===0&&(s=parseInt(u[1]),t=s),a.includes("FAILED")&&i.push(a.trim())}break}case"go":{for(let a of o)a.includes("--- PASS")&&s++,a.includes("--- FAIL")&&(r++,i.push(a.replace("--- FAIL:","").trim()));t=s+r;break}default:{for(let a of o)/\bpass(ed|ing)?\b/i.test(a)&&/\d/.test(a)&&s++,/\bfail(ed|ing|ure)?\b/i.test(a)&&/\d/.test(a)&&r++;t=s+r}}return{totalTests:t,passedTests:s,failedTests:r,failedTestNames:i}}function ku(n){let e=[],t=n.passed?"\u2713 PASSED":"\u2717 FAILED",s=(n.duration/1e3).toFixed(1);if(e.push(` ${n.passed?"\u2713":"\u2717"} ${t} (${n.framework}) \u2014 ${s}s`),e.push(` Command: ${n.command}`),n.totalTests>0&&e.push(` Tests: ${n.passedTests} passed, ${n.failedTests} failed, ${n.totalTests} total`),n.failedTestNames.length>0){e.push(""),e.push(" Failed tests:");for(let r of n.failedTestNames.slice(0,10))e.push(` \u2717 ${r}`)}return e.join(`
|
|
235
|
-
`)}function $u(n){return`The following tests are failing. Analyze the error output and fix the code.
|
|
224
|
+
`+u.chrome("\u2570"+"\u2500".repeat(n-2)+"\u256F")+`
|
|
225
|
+
`}function Zc(n,e){let t=je(),s=[];s.push(""),s.push(` ${u.chrome("\u256D"+"\u2500".repeat(t-4)+"\u256E")}`),s.push(` ${u.chrome("\u2502")} ${u.leader("\u2605")} ${u.strong("Hablas")} ${u.muted("\u2014 Execution Plan")}${" ".repeat(Math.max(0,t-35))}${u.chrome("\u2502")}`);let r=20,i=Math.round(e.percent/100*r),o=r-i,a=u.success("\u2588".repeat(i))+u.muted("\u2591".repeat(o));s.push(` ${u.chrome("\u2502")} ${a} ${u.muted(`${e.percent}%`)} ${u.muted(`(${e.done}/${e.total} tasks)`)}`),s.push(` ${u.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`);for(let l=0;l<n.tasks.length;l++){let c=n.tasks[l],d=Ey[c.status]($y[c.status]),h=(c.assignee==="hablas"?u.leader:c.assignee==="bob"?u.architect:c.assignee==="alex"?u.engineer:c.assignee==="david"?u.analyst:c.assignee==="emma"?u.product:u.muted)(`@${c.assigneeName}`),m="";c.dependent_task_ids.length>0&&(m=u.muted(` \u2190 [${c.dependent_task_ids.join(", ")}]`));let p=u.secondary(c.description);s.push(` ${u.chrome("\u2502")} ${d} ${u.muted(`${c.task_id}.`)} ${h} ${u.muted("\u2192")} ${p}${m}`)}return s.push(` ${u.chrome("\u251C"+"\u2500".repeat(t-4)+"\u2524")}`),s.push(` ${u.chrome("\u2502")} ${u.muted("Strategy:")} ${u.highlight(n.strategy)} ${u.muted("\xB7")} ${u.muted(`${n.tasks.length} tasks`)}`),s.push(` ${u.chrome("\u2570"+"\u2500".repeat(t-4)+"\u256F")}`),s.push(""),s.join(`
|
|
226
|
+
`)}function eu(n){let e=Math.min(je(),80),t=[],s=`\u250C${"\u2500".repeat(e-2)}\u2510`,r=`\u251C${"\u2500".repeat(e-2)}\u2524`,i=`\u2514${"\u2500".repeat(e-2)}\u2518`;t.push(` ${u.border(s)}`);let a=`\u2605 MISSION STATUS: ${n.taskTitle}`.slice(0,e-4).padEnd(e-4);t.push(` ${u.border("\u2502")} ${u.strong(a)} ${u.border("\u2502")}`),t.push(` ${u.border(r)}`);let c=`Phase: ${n.currentPhase}`.slice(0,e-4).padEnd(e-4);t.push(` ${u.border("\u2502")} ${u.primary(c)} ${u.border("\u2502")}`);let d=[];for(let[y,v]of Object.entries(n.roster)){let b=y==="Hablas"?u.leader:y==="Bob"?u.architect:y==="Alex"?u.engineer:y==="David"?u.analyst:u.product,w="";v==="done"?w=u.success("\u2713"):v==="active"?w=u.highlight("\u25CF"):w=u.muted("\u25CB"),d.push(`@${b(y)} ${w}`)}let f=`Roster: ${d.join(" ")}`,h=f.replace(/\x1b\[[0-9;]*m/g,""),m=Math.max(0,e-4-h.length);t.push(` ${u.border("\u2502")} ${f}${" ".repeat(m)} ${u.border("\u2502")}`);let p=`Active: @${n.activeAgent} (${n.activeAgentTitle})`,g=p.replace(/\x1b\[[0-9;]*m/g,""),_=Math.max(0,e-4-g.length);t.push(` ${u.border("\u2502")} ${p}${" ".repeat(_)} ${u.border("\u2502")}`);let A=`Action: ${n.currentActivity}`,S=A.replace(/\x1b\[[0-9;]*m/g,""),k=Math.max(0,e-4-S.length);return t.push(` ${u.border("\u2502")} ${u.secondary(A)}${" ".repeat(k)} ${u.border("\u2502")}`),t.push(` ${u.border(i)}`),t.join(`
|
|
227
|
+
`)}var Mi,ks,As,jc,nn,Bc,Uc,je,u,Je,Ii,$y,Ey,Di,rn=N(()=>{"use strict";Mi=O(require("os")),ks=O(require("fs")),As=O(require("path"));jc=wy(),nn=process.stdout.isTTY===!0,Bc=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",Uc=process.stdout.columns||80;nn&&process.stdout.on("resize",()=>{Uc=process.stdout.columns||80});je=()=>Math.min(Uc-4,100);u={primary:n=>ae(n,"\x1B[38;5;253m"),secondary:n=>ae(n,"\x1B[38;5;247m"),muted:n=>ae(n,"\x1B[38;5;242m"),strong:n=>ae(n,"\x1B[1;38;5;255m"),accent:n=>ae(n,"\x1B[38;5;145m"),highlight:n=>ae(n,"\x1B[38;5;231m"),success:n=>ae(n,"\x1B[38;5;108m"),error:n=>ae(n,"\x1B[38;5;167m"),warning:n=>ae(n,"\x1B[38;5;179m"),info:n=>ae(n,"\x1B[38;5;110m"),codeBlock:n=>ae(n,"\x1B[38;5;188m"),lineNum:n=>ae(n,"\x1B[38;5;239m"),border:n=>ae(n,"\x1B[38;5;237m"),chrome:n=>ae(n,"\x1B[38;5;235m"),added:n=>ae(n,"\x1B[38;5;108m"),removed:n=>ae(n,"\x1B[38;5;167m"),hunk:n=>ae(n,"\x1B[38;5;145m"),leader:n=>ae(n,"\x1B[38;5;179m"),architect:n=>ae(n,"\x1B[38;5;250m"),engineer:n=>ae(n,"\x1B[38;5;145m"),analyst:n=>ae(n,"\x1B[38;5;108m"),product:n=>ae(n,"\x1B[38;5;180m")};Je=class{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];interval=null;frameIndex=0;message;startTime=0;constructor(e="Thinking"){this.message=e}start(){if(this.startTime=Date.now(),!nn){process.stderr.write(` ${this.message}...
|
|
228
|
+
`);return}this.interval=setInterval(()=>{let e=((Date.now()-this.startTime)/1e3).toFixed(1),t=u.accent(this.frames[this.frameIndex]);process.stdout.write(`\r ${t} ${u.muted(this.message)} ${u.muted(e+"s")}`),this.frameIndex=(this.frameIndex+1)%this.frames.length},80)}setPhase(e){this.message=e}updateMessage(e){this.message=e}stop(e){this.interval&&(clearInterval(this.interval),this.interval=null);let t=Date.now()-this.startTime;if(nn&&process.stdout.write("\r"+" ".repeat(80)+"\r"),e&&nn){let s=u.muted(`${t}ms`);console.log(` ${u.muted("\xB7")} ${u.secondary(e)} ${s}`)}}};Ii=[{cmd:"/help",desc:"Show this help"},{cmd:"/about",desc:"Developer info & links"},{cmd:"/version",desc:"Version & runtime info"},{cmd:"/team",desc:"Show agent team roster"},{cmd:"/model",arg:"<name>",desc:"Switch model"},{cmd:"/models",arg:"[search|page]",desc:"Browse all models"},{cmd:"/tree",desc:"Project file tree"},{cmd:"/status",desc:"Agent status & context"},{cmd:"/history",arg:"[n]",desc:"Show last n turns"},{cmd:"/undo",arg:"[path]",desc:"Restore last backup"},{cmd:"/clear",desc:"Clear session & context"},{cmd:"/config",desc:"Show current config"},{cmd:"/quit",desc:"Exit hablas"}];$y={pending:"\u25CB",running:"\u25C9",done:"\u2713",failed:"\u2717",skipped:"\u2013"},Ey={pending:u.muted,running:u.accent,done:u.success,failed:u.error,skipped:u.muted};Di=Ii.map(n=>n.cmd).concat(["/exit","/addmodel","/listmodels","/removemodel","/usemodel","/provider","/task","/memory","/mindset","/mindsets","/alias","/doctor","/plugins","/team","/agents","/delegate"])});function Ni(n){let e=Qe.join(n,"package.json");if(Me.existsSync(e))try{let t=JSON.parse(Me.readFileSync(e,"utf-8")),s={...t.dependencies,...t.devDependencies};if(s.vitest)return"vitest";if(s.jest||s["@jest/core"])return"jest";if(s.mocha)return"mocha"}catch{}if(Me.existsSync(Qe.join(n,"pytest.ini"))||Me.existsSync(Qe.join(n,"pyproject.toml"))||Me.existsSync(Qe.join(n,"setup.py")))try{let t=Me.existsSync(Qe.join(n,"requirements.txt"))?Me.readFileSync(Qe.join(n,"requirements.txt"),"utf-8"):"",s=Me.existsSync(Qe.join(n,"pyproject.toml"))?Me.readFileSync(Qe.join(n,"pyproject.toml"),"utf-8"):"";if(t.includes("pytest")||s.includes("pytest"))return"pytest"}catch{}return Me.existsSync(Qe.join(n,"go.mod"))?"go":Me.existsSync(Qe.join(n,"Cargo.toml"))?"cargo":"unknown"}function Cy(n,e){switch(n){case"vitest":return e?`npx vitest run ${e}`:"npx vitest run";case"jest":return e?`npx jest ${e} --no-coverage`:"npx jest --no-coverage";case"mocha":return e?`npx mocha ${e}`:"npx mocha";case"pytest":return e?`python -m pytest ${e} -v`:"python -m pytest -v";case"go":return e?`go test ./${e}`:"go test ./...";case"cargo":return"cargo test";default:return"npm test"}}function nu(n,e){let t=Ni(n),s=Cy(t,e),r=Date.now(),i="",o="",a=!1;try{i=(0,tu.execSync)(s,{cwd:n,encoding:"utf-8",timeout:12e4,maxBuffer:5*1024*1024,stdio:["pipe","pipe","pipe"]}),a=!0}catch(m){i=m.stdout||"",o=m.stderr||m.message||"",a=!1}let l=Date.now()-r,{totalTests:c,passedTests:d,failedTests:f,failedTestNames:h}=Ty(i+`
|
|
229
|
+
`+o,t);return{framework:t,command:s,passed:a,output:i.slice(0,5e3),errorOutput:o.slice(0,3e3),totalTests:c,passedTests:d,failedTests:f,duration:l,failedTestNames:h}}function Ty(n,e){let t=0,s=0,r=0,i=[],o=n.split(`
|
|
230
|
+
`);switch(e){case"jest":case"vitest":{for(let a of o){let l=a.match(/Tests:\s+(\d+)\s+passed.*?(\d+)\s+total/);if(l&&(s=parseInt(l[1]),t=parseInt(l[2]),r=t-s),a.match(/✕|FAIL|✗|×/)){let d=a.replace(/.*(?:✕|FAIL|✗|×)\s*/,"").trim();d&&i.push(d)}}break}case"pytest":{for(let a of o){let l=a.match(/(\d+)\s+passed.*?(\d+)\s+failed/);l&&(s=parseInt(l[1]),r=parseInt(l[2]),t=s+r);let c=a.match(/(\d+)\s+passed/);c&&t===0&&(s=parseInt(c[1]),t=s),a.includes("FAILED")&&i.push(a.trim())}break}case"go":{for(let a of o)a.includes("--- PASS")&&s++,a.includes("--- FAIL")&&(r++,i.push(a.replace("--- FAIL:","").trim()));t=s+r;break}default:{for(let a of o)/\bpass(ed|ing)?\b/i.test(a)&&/\d/.test(a)&&s++,/\bfail(ed|ing|ure)?\b/i.test(a)&&/\d/.test(a)&&r++;t=s+r}}return{totalTests:t,passedTests:s,failedTests:r,failedTestNames:i}}function su(n){let e=[],t=n.passed?"\u2713 PASSED":"\u2717 FAILED",s=(n.duration/1e3).toFixed(1);if(e.push(` ${n.passed?"\u2713":"\u2717"} ${t} (${n.framework}) \u2014 ${s}s`),e.push(` Command: ${n.command}`),n.totalTests>0&&e.push(` Tests: ${n.passedTests} passed, ${n.failedTests} failed, ${n.totalTests} total`),n.failedTestNames.length>0){e.push(""),e.push(" Failed tests:");for(let r of n.failedTestNames.slice(0,10))e.push(` \u2717 ${r}`)}return e.join(`
|
|
231
|
+
`)}function ru(n){return`The following tests are failing. Analyze the error output and fix the code.
|
|
236
232
|
|
|
237
233
|
Test framework: ${n.framework}
|
|
238
234
|
Command: ${n.command}
|
|
@@ -252,21 +248,21 @@ Instructions:
|
|
|
252
248
|
1. Read the failing test files to understand what's expected
|
|
253
249
|
2. Read the source files being tested
|
|
254
250
|
3. Fix the source code (not the tests) to make them pass
|
|
255
|
-
4. After fixing, explain what was wrong and what you changed`}var
|
|
256
|
-
`).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await
|
|
257
|
-
`)}var
|
|
258
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function
|
|
259
|
-
`),g==="+"?m++:g==="-"?p++:g===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(
|
|
260
|
-
`;if(
|
|
261
|
-
`));for(var
|
|
262
|
-
`);if(
|
|
251
|
+
4. After fixing, explain what was wrong and what you changed`}var tu,Me,Qe,iu=N(()=>{"use strict";tu=require("child_process"),Me=O(require("fs")),Qe=O(require("path"))});function Es(n){let e=Buffer.from(n).toString("base64url").slice(0,16);return Ee.join(Ry,e)}async function au(n,e,t){let s=Es(n);Ae.existsSync(s)||Ae.mkdirSync(s,{recursive:!0});let r=`cp_${Date.now()}`,i=[];for(let f of t){let h=Ee.resolve(n,f);if(Ae.existsSync(h))try{let m=await bt.readFile(h,"utf-8");i.push({path:f,content:m})}catch{}}try{let f=(0,$s.execSync)("git ls-files -m",{cwd:n,encoding:"utf-8",timeout:5e3}).split(`
|
|
252
|
+
`).filter(Boolean);for(let h of f)if(!i.find(m=>m.path===h))try{let m=await bt.readFile(Ee.resolve(n,h),"utf-8");i.push({path:h,content:m})}catch{}}catch{}let o,a;try{o=(0,$s.execSync)("git branch --show-current",{cwd:n,encoding:"utf-8",timeout:5e3}).trim(),a=(0,$s.execSync)("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8",timeout:5e3}).trim()}catch{}let l={id:r,label:e,timestamp:Date.now(),files:i,gitBranch:o,gitHash:a,projectPath:n},c=Ee.join(s,`${r}.json`);await bt.writeFile(c,JSON.stringify(l,null,2),"utf-8");let d=Ae.readdirSync(s).filter(f=>f.endsWith(".json")).sort();if(d.length>20)for(let f of d.slice(0,d.length-20))try{Ae.unlinkSync(Ee.join(s,f))}catch{}return{id:r,label:e,timestamp:l.timestamp,fileCount:i.length,projectPath:n}}function lu(n){let e=Es(n);if(!Ae.existsSync(e))return[];let t=Ae.readdirSync(e).filter(r=>r.endsWith(".json")).sort().reverse(),s=[];for(let r of t)try{let i=JSON.parse(Ae.readFileSync(Ee.join(e,r),"utf-8"));s.push({id:i.id,label:i.label,timestamp:i.timestamp,fileCount:i.files.length,projectPath:i.projectPath})}catch{}return s}async function cu(n,e){let t=Es(n),s=Ee.join(t,`${e}.json`);if(!Ae.existsSync(s))return{success:!1,filesRestored:0,error:`Checkpoint ${e} not found`};try{let r=JSON.parse(await bt.readFile(s,"utf-8")),i=0;for(let o of r.files)try{let a=Ee.resolve(n,o.path);await bt.mkdir(Ee.dirname(a),{recursive:!0}),await bt.writeFile(a,o.content,"utf-8"),i++}catch{}return{success:!0,filesRestored:i}}catch(r){return{success:!1,filesRestored:0,error:r.message}}}function uu(n,e){let t=Es(n),s=Ee.join(t,`${e}.json`);try{if(Ae.existsSync(s))return Ae.unlinkSync(s),!0}catch{}return!1}function du(n){if(n.length===0)return" No checkpoints saved";let e=[];for(let t of n){let s=new Date(t.timestamp).toLocaleString();e.push(` ${t.id} "${t.label}" (${t.fileCount} files, ${s})`)}return e.join(`
|
|
253
|
+
`)}var Ae,bt,Ee,ou,$s,Ry,fu=N(()=>{"use strict";Ae=O(require("fs")),bt=O(require("fs/promises")),Ee=O(require("path")),ou=O(require("os")),$s=require("child_process"),Ry=Ee.join(ou.homedir(),".hablas","checkpoints")});function vt(){}function Oy(n,e,t,s,r){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,d=0;a<l;a++){var f=i[a];if(f.removed){if(f.value=n.join(s.slice(d,d+f.count)),d+=f.count,a&&i[a-1].added){var m=i[a-1];i[a-1]=i[a],i[a]=m}}else{if(!f.added&&r){var h=t.slice(c,c+f.count);h=h.map(function(g,_){var A=s[d+_];return A.length>g.length?A:g}),f.value=n.join(h)}else f.value=n.join(t.slice(c,c+f.count));c+=f.count,f.added||(d+=f.count)}}var p=i[l-1];return l>1&&typeof p.value=="string"&&(p.added||p.removed)&&n.equals("",p.value)&&(i[l-2].value+=p.value,i.pop()),i}function Py(n,e,t){return Ui.diff(n,e,t)}function Cs(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Cs=function(e){return typeof e}:Cs=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cs(n)}function Fi(n){return Ly(n)||Dy(n)||Ny(n)||Fy()}function Ly(n){if(Array.isArray(n))return Hi(n)}function Dy(n){if(typeof Symbol<"u"&&Symbol.iterator in Object(n))return Array.from(n)}function Ny(n,e){if(n){if(typeof n=="string")return Hi(n,e);var t=Object.prototype.toString.call(n).slice(8,-1);if(t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set")return Array.from(n);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Hi(n,e)}}function Hi(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=n[t];return s}function Fy(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
254
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ji(n,e,t,s,r){e=e||[],t=t||[],s&&(n=s(r,n));var i;for(i=0;i<e.length;i+=1)if(e[i]===n)return t[i];var o;if(Hy.call(n)==="[object Array]"){for(e.push(n),o=new Array(n.length),t.push(o),i=0;i<n.length;i+=1)o[i]=ji(n[i],e,t,s,r);return e.pop(),t.pop(),o}if(n&&n.toJSON&&(n=n.toJSON()),Cs(n)==="object"&&n!==null){e.push(n),o={},t.push(o);var a=[],l;for(l in n)n.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=ji(n[l],e,t,s,l);e.pop(),t.pop()}else o=n;return o}function jy(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},t=n.split(/\r\n|[\n\v\f\r\x85]/),s=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],r=[],i=0;function o(){var c={};for(r.push(c);i<t.length;){var d=t[i];if(/^(\-\-\-|\+\+\+|@@)\s/.test(d))break;var f=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(d);f&&(c.index=d.substring(f[0].length).trim()),i++}for(a(c),a(c),c.hunks=[];i<t.length;){var h=t[i];if(/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(h))break;if(/^@@/.test(h))c.hunks.push(l());else{if(h&&e.strict)throw new Error("Unknown line "+(i+1)+" "+JSON.stringify(h));i++}}}function a(c){var d=/^(---|\+\+\+)\s+/.exec(t[i]);if(d){var f=d[1]==="---"?"old":"new",h=t[i].substring(3).trim().split(" ",2),m=h[0].replace(/\\\\/g,"\\");m.startsWith('"')&&m.endsWith('"')&&(m=m.substr(1,m.length-2)),c[f+"FileName"]=m,c[f+"Header"]=(h[1]||"").trim(),i++}}function l(){var c=i,d=t[i++],f=d.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),h={oldStart:+f[1],oldLines:typeof f[2]>"u"?1:+f[2],newStart:+f[3],newLines:typeof f[4]>"u"?1:+f[4],lines:[],linedelimiters:[]};h.oldLines===0&&(h.oldStart+=1),h.newLines===0&&(h.newStart+=1);for(var m=0,p=0;i<t.length&&!(t[i].indexOf("--- ")===0&&i+2<t.length&&t[i+1].indexOf("+++ ")===0&&t[i+2].indexOf("@@")===0);i++){var g=t[i].length==0&&i!=t.length-1?" ":t[i][0];if(g==="+"||g==="-"||g===" "||g==="\\")h.lines.push(t[i]),h.linedelimiters.push(s[i]||`
|
|
255
|
+
`),g==="+"?m++:g==="-"?p++:g===" "&&(m++,p++);else break}if(!m&&h.newLines===1&&(h.newLines=0),!p&&h.oldLines===1&&(h.oldLines=0),e.strict){if(m!==h.newLines)throw new Error("Added line count did not match for hunk at line "+(c+1));if(p!==h.oldLines)throw new Error("Removed line count did not match for hunk at line "+(c+1))}return h}for(;i<t.length;)o();return r}function By(n,e,t){var s=!0,r=!1,i=!1,o=1;return function a(){if(s&&!i){if(r?o++:s=!1,n+o<=t)return o;i=!0}if(!r)return i||(s=!0),e<=n-o?-o++:(r=!0,a())}}function gu(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(typeof e=="string"&&(e=jy(e)),Array.isArray(e)){if(e.length>1)throw new Error("applyPatch only works with a single input.");e=e[0]}var s=n.split(/\r\n|[\n\v\f\r\x85]/),r=n.match(/\r\n|[\n\v\f\r\x85]/g)||[],i=e.hunks,o=t.compareLine||function(C,E,K,D){return E===D},a=0,l=t.fuzzFactor||0,c=0,d=0,f,h;function m(C,E){for(var K=0;K<C.lines.length;K++){var D=C.lines[K],Q=D.length>0?D[0]:" ",me=D.length>0?D.substr(1):D;if(Q===" "||Q==="-"){if(!o(E+1,s[E],Q,me)&&(a++,a>l))return!1;E++}}return!0}for(var p=0;p<i.length;p++){for(var g=i[p],_=s.length-g.oldLines,A=0,S=d+g.oldStart-1,k=By(S,c,_);A!==void 0;A=k())if(m(g,S+A)){g.offset=d+=A;break}if(A===void 0)return!1;c=g.offset+g.oldStart+g.oldLines}for(var y=0,v=0;v<i.length;v++){var b=i[v],w=b.oldStart+b.offset+y-1;y+=b.newLines-b.oldLines;for(var x=0;x<b.lines.length;x++){var T=b.lines[x],L=T.length>0?T[0]:" ",$=T.length>0?T.substr(1):T,F=b.linedelimiters&&b.linedelimiters[x]||`
|
|
256
|
+
`;if(L===" ")w++;else if(L==="-")s.splice(w,1),r.splice(w,1);else if(L==="+")s.splice(w,0,$),r.splice(w,0,F),w++;else if(L==="\\"){var j=b.lines[x-1]?b.lines[x-1][0]:null;j==="+"?f=!0:j==="-"&&(h=!0)}}}if(f)for(;!s[s.length-1];)s.pop(),r.pop();else h&&(s.push(""),r.push(`
|
|
257
|
+
`));for(var z=0;z<s.length-1;z++)s[z]=s[z]+r[z];return s.join("")}function Uy(n,e,t,s,r,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Py(t,s,o);if(!a)return;a.push({value:"",lines:[]});function l(A){return A.map(function(S){return" "+S})}for(var c=[],d=0,f=0,h=[],m=1,p=1,g=function(S){var k=a[S],y=k.lines||k.value.replace(/\n$/,"").split(`
|
|
258
|
+
`);if(k.lines=y,k.added||k.removed){var v;if(!d){var b=a[S-1];d=m,f=p,b&&(h=o.context>0?l(b.lines.slice(-o.context)):[],d-=h.length,f-=h.length)}(v=h).push.apply(v,Fi(y.map(function(z){return(k.added?"+":"-")+z}))),k.added?p+=y.length:m+=y.length}else{if(d)if(y.length<=o.context*2&&S<a.length-2){var w;(w=h).push.apply(w,Fi(l(y)))}else{var x,T=Math.min(y.length,o.context);(x=h).push.apply(x,Fi(l(y.slice(0,T))));var L={oldStart:d,oldLines:m-d+T,newStart:f,newLines:p-f+T,lines:h};if(S>=a.length-2&&y.length<=o.context){var $=/\n$/.test(t),F=/\n$/.test(s),j=y.length==0&&h.length>L.oldLines;!$&&j&&t.length>0&&h.splice(L.oldLines,0,"\"),(!$&&!j||!F)&&h.push("\")}c.push(L),d=0,f=0,h=[]}m+=y.length,p+=y.length}},_=0;_<a.length;_++)g(_);return{oldFileName:n,newFileName:e,oldHeader:r,newHeader:i,hunks:c}}function yu(n){if(Array.isArray(n))return n.map(yu).join(`
|
|
263
259
|
`);var e=[];n.oldFileName==n.newFileName&&e.push("Index: "+n.oldFileName),e.push("==================================================================="),e.push("--- "+n.oldFileName+(typeof n.oldHeader>"u"?"":" "+n.oldHeader)),e.push("+++ "+n.newFileName+(typeof n.newHeader>"u"?"":" "+n.newHeader));for(var t=0;t<n.hunks.length;t++){var s=n.hunks[t];s.oldLines===0&&(s.oldStart-=1),s.newLines===0&&(s.newStart-=1),e.push("@@ -"+s.oldStart+","+s.oldLines+" +"+s.newStart+","+s.newLines+" @@"),e.push.apply(e,s.lines)}return e.join(`
|
|
264
260
|
`)+`
|
|
265
|
-
`}function
|
|
266
|
-
`));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var s=0;s<t.length;s++){var r=t[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=r:(this.options.ignoreWhitespace&&(r=r.trim()),e.push(r))}return e};
|
|
261
|
+
`}function Ky(n,e,t,s,r,i,o){return yu(Uy(n,e,t,s,r,i,o))}function bu(n,e,t,s,r,i){return Ky(n,n,e,t,s,r,i)}var X0,pu,hu,mu,Ui,Iy,My,Hy,Mn,Bi,vu=N(()=>{vt.prototype={diff:function(e,t){var s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=r.callback;typeof r=="function"&&(i=r,r={}),this.options=r;var o=this;function a(y){return i?(setTimeout(function(){i(void 0,y)},0),!0):y}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var l=t.length,c=e.length,d=1,f=l+c;r.maxEditLength&&(f=Math.min(f,r.maxEditLength));var h=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+h,p=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(p[0],t,e,0);if(p[0].oldPos+1>=c&&g+1>=l)return a([{value:this.join(t),count:t.length}]);var _=-1/0,A=1/0;function S(){for(var y=Math.max(_,-d);y<=Math.min(A,d);y+=2){var v=void 0,b=p[y-1],w=p[y+1];b&&(p[y-1]=void 0);var x=!1;if(w){var T=w.oldPos-y;x=w&&0<=T&&T<l}var L=b&&b.oldPos+1<c;if(!x&&!L){p[y]=void 0;continue}if(!L||x&&b.oldPos+1<w.oldPos?v=o.addToPath(w,!0,void 0,0):v=o.addToPath(b,void 0,!0,1),g=o.extractCommon(v,t,e,y),v.oldPos+1>=c&&g+1>=l)return a(Oy(o,v.lastComponent,t,e,o.useLongestToken));p[y]=v,v.oldPos+1>=c&&(A=Math.min(A,y-1)),g+1>=l&&(_=Math.max(_,y+1))}d++}if(i)(function y(){setTimeout(function(){if(d>f||Date.now()>m)return i();S()||y()},0)})();else for(;d<=f&&Date.now()<=m;){var k=S();if(k)return k}},addToPath:function(e,t,s,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===s?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:s,previousComponent:i}}},extractCommon:function(e,t,s,r){for(var i=t.length,o=s.length,a=e.oldPos,l=a-r,c=0;l+1<i&&a+1<o&&this.equals(t[l+1],s[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],s=0;s<e.length;s++)e[s]&&t.push(e[s]);return t},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};X0=new vt,pu=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,hu=/\S/,mu=new vt;mu.equals=function(n,e){return this.options.ignoreCase&&(n=n.toLowerCase(),e=e.toLowerCase()),n===e||this.options.ignoreWhitespace&&!hu.test(n)&&!hu.test(e)};mu.tokenize=function(n){for(var e=n.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),t=0;t<e.length-1;t++)!e[t+1]&&e[t+2]&&pu.test(e[t])&&pu.test(e[t+2])&&(e[t]+=e[t+2],e.splice(t+1,2),t--);return e};Ui=new vt;Ui.tokenize=function(n){this.options.stripTrailingCr&&(n=n.replace(/\r\n/g,`
|
|
262
|
+
`));var e=[],t=n.split(/(\n|\r\n)/);t[t.length-1]||t.pop();for(var s=0;s<t.length;s++){var r=t[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=r:(this.options.ignoreWhitespace&&(r=r.trim()),e.push(r))}return e};Iy=new vt;Iy.tokenize=function(n){return n.split(/(\S.+?[.!?])(?=\s+|$)/)};My=new vt;My.tokenize=function(n){return n.split(/([{}:;,]|\s+)/)};Hy=Object.prototype.toString,Mn=new vt;Mn.useLongestToken=!0;Mn.tokenize=Ui.tokenize;Mn.castInput=function(n){var e=this.options,t=e.undefinedReplacement,s=e.stringifyReplacer,r=s===void 0?function(i,o){return typeof o>"u"?t:o}:s;return typeof n=="string"?n:JSON.stringify(ji(n,null,null,r),r," ")};Mn.equals=function(n,e){return vt.prototype.equals.call(Mn,n.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};Bi=new vt;Bi.tokenize=function(n){return n.slice()};Bi.join=Bi.removeEmpty=function(n){return n}});var wu={};Pe(wu,{applyDiff:()=>qy,formatDiffForDisplay:()=>Wy,generateDiff:()=>Ts});function Ts(n,e,t){return bu(n,e,t,"original","modified")}function qy(n,e){return gu(n,e)}function Wy(n){return n.split(`
|
|
267
263
|
`).map(t=>t.startsWith("+")&&!t.startsWith("+++")?`\x1B[32m${t}\x1B[0m`:t.startsWith("-")&&!t.startsWith("---")?`\x1B[31m${t}\x1B[0m`:t.startsWith("@@")?`\x1B[36m${t}\x1B[0m`:t).join(`
|
|
268
|
-
`)}var
|
|
269
|
-
`)}function
|
|
264
|
+
`)}var Ki=N(()=>{"use strict";vu()});async function on(n,e){let t=[],s=Se.join(n,"package.json");if(le.existsSync(s))try{let o=JSON.parse(le.readFileSync(s,"utf-8"));t.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&t.push(`Description: ${o.description}`);let a=Object.keys(o.dependencies||{}).concat(Object.keys(o.devDependencies||{}));a.length>0&&t.push(`Key deps: ${a.slice(0,15).join(", ")}${a.length>15?"...":""}`)}catch{}if(e?.workspace?.frameworkDetection){let o=_s(n);t.push(`Framework: ${o.framework}`),t.push(`Language: ${o.language}`),t.push(`Package Manager: ${o.packageManager}`),o.hasDocker&&t.push("Docker: detected"),o.hasCICD&&t.push("CI/CD: detected"),o.hasTests&&t.push("Tests: detected")}if(e?.workspace?.gitAwareness)try{let o=await Ti(n);o&&(t.push(`Git branch: ${o.branch}`),o.modified.length>0&&t.push(`Modified files: ${o.modified.length}`),o.staged.length>0&&t.push(`Staged files: ${o.staged.length}`))}catch{}if(e?.workspace?.envParsing){let a=[".env",".env.local",".env.development",".env.production"].filter(l=>le.existsSync(Se.join(n,l)));a.length>0&&t.push(`Env files: ${a.join(", ")}`)}let i=["tsconfig.json",".eslintrc.json","vite.config.ts","next.config.js","tailwind.config.js"].filter(o=>le.existsSync(Se.join(n,o)));if(i.length>0&&t.push(`Config: ${i.join(", ")}`),e?.context?.projectGraph)try{let o=le.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,25);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}else try{let o=le.readdirSync(n).filter(a=>!["node_modules",".git","dist","build",".next",".cache"].includes(a)).filter(a=>!a.startsWith(".")).slice(0,20);o.length>0&&t.push(`Structure: ${o.join(", ")}`)}catch{}return t.push(`Directory: ${n}`),e?.agents?.enabled&&(t.push("Multi-Agent: enabled (Team Leader: Hablas)"),t.push("Team: @Hablas (Leader), @Bob (Architect), @Alex (Engineer), @David (Data Analyst), @Emma (Product Manager)")),t.join(`
|
|
265
|
+
`)}function an(n,e,t,s){let r=n+`
|
|
270
266
|
|
|
271
267
|
## Current Project
|
|
272
268
|
`+e;if(t){let i=t.getSummary();i&&(r+=`
|
|
@@ -276,14 +272,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
276
272
|
## Shared Context
|
|
277
273
|
`+i)}return r+=`
|
|
278
274
|
|
|
279
|
-
`+
|
|
275
|
+
`+Nc(),r}async function Gy(n){try{if(!le.existsSync(qi))return null;let t=(await Ct.readdir(qi)).filter(f=>f.endsWith(".bak"));if(n){let f=Se.basename(n);t=t.filter(h=>h.startsWith(`${f}.`))}if(t.length===0)return null;t.sort().reverse();let s=t[0],r=Se.join(qi,s),i=s.replace(".bak","").split("."),o=parseInt(i[i.length-1],10),a=i.slice(0,-1).join("."),l=Date.now()-o,c=Math.floor(l/6e4),d=c<1?"just now":c<60?`${c} minutes ago`:`${Math.floor(c/60)} hours ago`;return{backupPath:r,originalName:a,age:d}}catch{return null}}async function xu(n,e,t,s,r,i,o,a,l,c,d,f,h,m,p,g,_){let A=n.split(/\s+/),S=A[0],k=A.slice(1).join(" ");switch(S){case"/quit":case"/exit":return"quit";case"/help":console.log(Xc()),console.log(u.muted(" Model & Provider:")),console.log(u.muted(" /addmodel Interactive wizard to add a custom API")),console.log(u.muted(" /listmodels Show saved providers")),console.log(u.muted(" /removemodel <name> Remove a saved provider")),console.log(u.muted(" /usemodel <name> Switch to a saved provider")),console.log(u.muted(" /models [page|search] Browse all available models")),console.log(u.muted(" /provider Show/switch API provider")),console.log(),console.log(u.muted(" Aliases & Plugins:")),console.log(u.muted(" /alias Show all aliases")),console.log(u.muted(" /alias set <n> <cmd> Create an alias")),console.log(u.muted(" /alias del <name> Remove an alias")),console.log(u.muted(" /plugins List installed plugins")),console.log(u.muted(" /doctor Run system diagnostics")),console.log(),console.log(u.muted(" Task & Memory:")),console.log(u.muted(" /task add <desc> Add a task to the queue")),console.log(u.muted(" /task list Show all tasks")),console.log(u.muted(" /task clear Clear task queue")),console.log(u.muted(" /memory Show project memory")),console.log(u.muted(" /memory set <k> <v> Store a memory")),console.log(u.muted(" /memory del <key> Delete a memory")),console.log(u.muted(" /memory clear Clear all memory")),console.log(),console.log(u.muted(" Multi-Agent & Tools:")),console.log(u.muted(" /team Show team roster")),console.log(u.muted(" /delegate <agent> <t> Manually assign task to agent")),console.log(u.muted(" /agents Multi-agent system control")),console.log(u.muted(" /agents on|off Enable/disable multi-agent")),console.log(u.muted(" /agents status Show agent details")),console.log(u.muted(" /security Run security scan")),console.log(u.muted(" /git status Show git status")),console.log(u.muted(" /workspace Show workspace info")),console.log(u.muted(" /stats Show usage analytics")),console.log();break;case"/about":console.log(Gc());break;case"/version":console.log(Vc());break;case"/model":if(k){let y=await t.listModels();t.setModel(k),y.includes(k)?console.log(J(`Model: ${k}`)):console.log(B(`Model set to "${k}" (not found locally)`))}else console.log(xe(`Current model: ${t.getModel()}`)),console.log(u.muted(" Usage: /model <name>"));break;case"/models":{let y=k.trim(),v=1,b="";if(y){let E=parseInt(y);!isNaN(E)&&E>0?v=E:b=y.toLowerCase()}let w=new Je("Fetching models");w.start();let x=await t.listModels();if(w.stop(x.length>0?`${x.length} found`:void 0),x.length===0){console.log(B("No models found \u2014 check your connection")),console.log(u.muted(" Use /provider test to verify"));break}let T=x;if(b&&(T=x.filter(E=>E.toLowerCase().includes(b)),T.length===0)){console.log(B(`No models matching: "${b}"`)),console.log(u.muted(` ${x.length} models available. Try a different search.`));break}let L=20,$=Math.ceil(T.length/L),F=Math.max(1,Math.min(v,$)),j=(F-1)*L,z=j+L,C=T.slice(j,z);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Available Models")} ${u.muted(`(${T.length} total \xB7 page ${F}/${$})`)}`),console.log();for(let E=0;E<C.length;E++){let K=j+E+1,Q=C[E]===t.getModel()?` ${u.success("\u25CF active")}`:"";console.log(` ${u.muted(String(K).padStart(3," "))}. ${u.secondary(C[E])}${Q}`)}console.log(),$>1&&console.log(u.muted(` /models ${F<$?F+1:1} \u2014 next page`)),b&&console.log(u.muted(` Filtered: ${T.length} of ${x.length} (query: "${b}")`)),console.log(u.muted(" /models <query> \u2014 search \xB7 /model <id> \u2014 switch")),console.log();break}case"/tree":{let y=s.get("list_dir");if(y){let v=await y.execute({path:".",depth:3});console.log(`
|
|
280
276
|
${v.output}
|
|
281
|
-
`)}break}case"/status":{let y=await t.checkConnection(),v=
|
|
282
|
-
${
|
|
283
|
-
`),console.log(c.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!u){console.log(B("Mindset system not available"));break}if(_)if(u.setActive(_)){let v=u.getActive(),b=await yn(o,e),w=bn(v.systemPrompt,b,f,m);i.updateSystemPrompt(w),console.log(J(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=u.listNames().join(", ");console.log(He(`Unknown mindset: "${_}"`,`Available: ${v}`))}else{let y=u.getActive();y&&console.log(he(`Current mindset: ${y.name} \u2014 ${y.description}`)),console.log(c.muted(" Usage: /mindset <name>")),console.log(c.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!u){console.log(B("Mindset system not available"));break}let y=u.list(),v=u.getActiveName();console.log();for(let b of y){let S=b.name===v?c.success(" \u25CF active"):"";console.log(` ${c.accent("\u25C6")} ${c.primary(b.name)}${S}`),console.log(` ${c.muted(b.description)}`)}console.log(),console.log(c.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(B("Task queue not available"));break}let y=A[1],v=A.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(J(`Task #${b.id} added: ${v}`))}else console.log(B("Usage: /task add <description>"));break;case"list":console.log(),console.log(d.render()),console.log();break;case"done":{let b=parseInt(v);b?(d.complete(b),console.log(J(`Task #${b} marked as done`))):console.log(B("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(B(`Task #${b} marked as failed`))):console.log(B("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(J("Task queue cleared"));break;default:console.log(),console.log(d.render()),console.log(),console.log(c.muted(" /task add <desc> \u2014 Add a task")),console.log(c.muted(" /task list \u2014 Show all tasks")),console.log(c.muted(" /task done <id> \u2014 Mark task as done")),console.log(c.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(c.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Add Custom API Provider")}`),console.log();let v=(await a.prompt(` ${c.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!v){console.log(B("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${c.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(B("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${c.muted("API Key (leave empty if none):")} `)).trim(),k=(await a.prompt(` ${c.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:w,apiKey:T,models:[k],defaultModel:k,addedAt:new Date().toISOString()};nt(F),console.log(),console.log(J(`Provider "${v}" saved!`)),console.log(c.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=Wt();console.log(),console.log(Cc(y.providers,y.activeProvider));break}case"/removemodel":{let y=_.trim();if(!y){console.log(B("Usage: /removemodel <provider-name>"));break}if(kc(y))console.log(J(`Provider "${y}" removed`));else{console.log(B(`Provider "${y}" not found`));let b=Cs();b.length>0&&console.log(c.muted(` Available: ${b.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let y=_.trim();if(!y){console.log(B("Usage: /usemodel <provider-name> [model-id]"));let F=Cs();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],w=v[1],S=$c(b);if(!S){console.log(B(`Provider "${b}" not found`));let F=Cs();F.length>0&&console.log(c.muted(` Available: ${F.map(H=>H.name).join(", ")}`));break}e.provider="custom",e.apiUrl=S.apiUrl,e.apiKey=S.apiKey,e.model=w||S.defaultModel;let T=Fe(e);h&&h(T),Ec(S.name,e.model),console.log(J(`Switched to ${S.name} \xB7 Model: ${e.model}`));let M=new ze("Testing");M.start();let k=await T.checkConnection();M.stop(k?"connected":void 0),k||console.log(B("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=A[1],v=A.slice(2).join(" ");if(!y){let b=Es(e);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Provider")}: ${b}`),console.log(` ${c.muted("Model")}: ${c.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${c.muted("API URL")}: ${e.apiUrl}`),console.log(` ${c.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${c.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(c.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(c.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(c.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(c.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(y){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let b=Fe(e);h&&h(b),console.log(J("Switched to Ollama (local)"));break}case"nvidia":{let b=A[2];if(!b&&!e.apiKey){console.log(B("Usage: /provider nvidia <api-key>")),console.log(c.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=Dt.apiUrl,b&&(e.apiKey=b),(!e.model||!Dt.models.includes(e.model))&&(e.model=Dt.defaultModel);let w=Fe(e);h&&h(w),console.log(J(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(c.muted(` Available models: ${Dt.models.length}`));let S=new ze("Testing NVIDIA connection");S.start();let T=await w.checkConnection();S.stop(T?"connected":void 0),T||(console.log(B("Connection test failed \u2014 check your API key")),console.log(c.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=A[2],w=A[3];if(!b){console.log(B("Usage: /provider custom <api-url> [api-key]")),console.log(c.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=b,w&&(e.apiKey=w);let S=Fe(e);h&&h(S),console.log(J(`Switched to Custom API: ${b}`)),!w&&!e.apiKey&&console.log(B("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new ze("Testing connection");b.start();let w=await t.checkConnection();if(b.stop(w?"connected":void 0),w){let S=await t.listModels();console.log(J(`Connected! ${S.length} models available.`)),S.length>0&&console.log(c.muted(` Models: ${S.slice(0,5).join(", ")}${S.length>5?"...":""}`))}else console.log($e("Connection failed"));break}case"key":{v?(e.apiKey=A[2],t instanceof Gt&&t.setApiKey(e.apiKey),console.log(J("API key updated"))):console.log(B("Usage: /provider key <api-key>"));break}default:console.log(He(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(B("Project memory not available"));break}let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");f.set(b,w),console.log(J(`Memory stored: ${b}`));let S=u?.getActive(),T=S?S.systemPrompt:Wn,M=await yn(o,e);i.updateSystemPrompt(bn(T,M,f,m))}else console.log(B("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?J(`Memory deleted: ${v[0]}`):B(`Memory key not found: ${v[0]}`))}else console.log(B("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(w=>console.log(` \xB7 ${w.entry.key}: ${w.entry.value}`)),console.log()):console.log(he("No matching memories found"))}else console.log(B("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(J("Project memory cleared"));break;default:console.log(),console.log(f.render()),console.log(),console.log(c.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(c.muted(" /memory del <key> \u2014 Delete a memory")),console.log(c.muted(" /memory search <q> \u2014 Search memories")),console.log(c.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");Oc(b,w),console.log(J(`Alias set: ${b} \u2192 ${w}`))}else console.log(B("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=Pc(v[0]);console.log(b?J(`Alias removed: ${v[0]}`):B(`Alias not found: ${v[0]}`))}else console.log(B("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Aliases")}`),console.log(),console.log(Mc()),console.log(),console.log(c.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(c.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let y=new ze("Running diagnostics");y.start();let v=await Ci({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(Ti(v));break}case"/plugins":{let y=A[1],v=A.slice(2).join(" ");switch(y){case"enable":v?(_i(v),console.log(J(`Plugin "${v}" enabled`))):console.log(B("Usage: /plugins enable <name>"));break;case"disable":v?(Ai(v),console.log(B(`Plugin "${v}" disabled`))):console.log(B("Usage: /plugins disable <name>"));break;default:Ms(),console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plugins")}`),console.log(),console.log(ki()),console.log(),console.log(c.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(c.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(c.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/agents":{let y=A[1];if(y==="on")e.agents.enabled=!0,console.log(J("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(J("Multi-agent orchestration disabled"));else if(y==="status")console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?c.success("enabled"):c.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${c.strong("Team:")}`),console.log(qc()),console.log();else if(y==="models"){let v=Fn();console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Agent Models")}`),console.log();for(let b of we){let w=v[b.role];console.log(w?` ${c.primary(b.name.padEnd(8))} \u2192 ${c.highlight(w.model)}${w.temperature!==void 0?c.muted(` (temp: ${w.temperature})`):""}`:` ${c.primary(b.name.padEnd(8))} \u2192 ${c.muted("(default)")}`)}console.log(),console.log(c.muted(` Config: ${Wc()}`)),console.log(c.muted(" Edit the file to change models per agent.")),console.log()}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Multi-Agent System")}: ${e.agents.enabled?c.success("ON"):c.muted("OFF")}`),console.log(),console.log(c.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(c.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(c.muted(" /agents status \u2014 Show agent details")),console.log(c.muted(" /agents models \u2014 Show model per agent")),console.log(c.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${c.accent("\u{1F512}")} Running security scan...`);let y=qi(o);console.log(Ki(y));break}case"/git":{if(A[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(hn(),Bn)),w=await v(o);w?(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Status")}`),console.log(b(w)),console.log()):console.log(B("Not a git repository"))}catch{console.log(B("Git not available"))}else console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Git Intelligence")}`),console.log(),console.log(c.muted(" /git status \u2014 Show git status")),console.log(c.muted(" hablas commit \u2014 Smart commit message")),console.log(c.muted(" hablas pr \u2014 Generate PR description")),console.log(c.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let y=Ns(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Workspace Information")}`),console.log(),console.log(Vi(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(Hn(),Ui)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(B("Shared context not available"));break}let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");m.set(b,w),console.log(J(`Context stored: ${b}`))}else console.log(B("Usage: /context set <key> <value>"));break}case"get":{if(v[0]){let b=m.get(v[0]);b!==void 0?(console.log(),console.log(` ${c.accent("\u25C6")} ${c.strong(v[0])}: ${b}`),console.log()):console.log(B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?J(`Context deleted: ${v[0]}`):B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(he("No decisions logged yet"));else{console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Decisions")}`),console.log();for(let w of b)console.log(` ${c.muted(w.timestamp)} ${c.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${c.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(J("Shared context cleared"));break;default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(c.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(c.muted(" /context get <key> \u2014 Get a context entry")),console.log(c.muted(" /context del <key> \u2014 Delete a context entry")),console.log(c.muted(" /context decisions \u2014 Show logged decisions")),console.log(c.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(B("Plan manager not available"));break}let y=A[1],v=A.slice(2).join(" ");switch(y){case"status":{let w=p.getActivePlan();if(!w){console.log(he("No active plan"));break}let S=p.getProgress();console.log(xu(w,{percent:S.percentage,done:S.done,total:S.total}));break}case"finish":{if(v){p.finishTask(v),console.log(J(`Task finished: ${v}`));let w=p.getProgress();console.log(c.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(B("Usage: /plan finish <task_id>"));break}case"reset":{p.reset(),console.log(J("Plan manager reset"));break}case"next":{let w=p.getNextTask();console.log(w?he(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):he("No pending tasks"));break}default:console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Plan Manager")}`),console.log();let b=p.getActivePlan();if(b){let w=p.getProgress();console.log(` Active plan: ${b.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.total}`)}else console.log(c.muted(" No active plan"));console.log(),console.log(c.muted(" /plan status \u2014 Show active plan with progress")),console.log(c.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(c.muted(" /plan next \u2014 Show next pending task")),console.log(c.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!_){console.log(B('Usage: /learn "always use tabs" or /learn "our API uses camelCase"'));break}if(f.set(`user-pref: ${_.slice(0,50)}`,_,{category:"user-pref",importance:9,createdBy:"user",tags:["user-pref","learned"]}),!(i.getMessages()[0]?.content||"").includes(_)){let v=await yn(o,e),b=u?.getActive(),w=b?b.systemPrompt:Wn,S=bn(w,v,f,m);i.updateSystemPrompt(S)}console.log(J(`Learned: "${_}"`)),console.log(c.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=no(o);if(y==="unknown"&&!_){console.log(B("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(he(`Running tests (${y})...`));let v=Au(o,_==="--fix"?void 0:_||void 0);if(console.log(),console.log(ku(v)),console.log(),!v.passed&&_==="--fix"){console.log(he("Tests failed \u2014 adding fix request to conversation..."));let b=$u(v);i.addUserMessage(b),console.log(he("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=A[1],v=A.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,w=g?.getModifiedFiles?.()||[],S=await Tu(o,b,w);console.log(J(`Checkpoint saved: ${S.id} "${b}" (${S.fileCount} files)`))}else if(y==="list"){let b=Ru(o);console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoints")}`),console.log(),console.log(Iu(b)),console.log()}else if(y==="restore"){if(!v){console.log(B("Usage: /checkpoint restore <id>"));break}let b=await Ou(o,v);b.success?console.log(J(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log($e(b.error||"Restore failed"))}else y==="delete"?v&&Pu(o,v)?console.log(J(`Deleted checkpoint: ${v}`)):console.log(B("Checkpoint not found")):(console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Checkpoint System")}`),console.log(),console.log(c.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(c.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(c.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(c.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let y=A.slice(1);if(y.length===2)try{let v=await Nt.readFile(ke.resolve(o,y[0]),"utf-8"),b=await Nt.readFile(ke.resolve(o,y[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(lo(),Uu)),S=w(y[0]+" vs "+y[1],v,b);console.log(Xi(S))}catch(v){console.log($e(`Compare failed: ${v.message}`))}else if(y.length===1&&y[0].startsWith("HEAD"))try{let{execSync:v}=await import("child_process"),b=v(`git diff ${y[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(Xi(b||"(no changes)"))}catch(v){console.log($e(`Git diff failed: ${v.message}`))}else console.log(c.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let y=jn(),v="current";console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${v} min`),console.log(` Messages: ${y.totalMessages}`),console.log(` Tool calls: ${y.totalToolCalls}`),console.log(` Tokens used: ${y.totalTokensUsed.toLocaleString()}`),console.log();let b=Object.entries(y.agentUsage);if(b.length>0){console.log(" Agent usage:");for(let[w,S]of b.sort((T,M)=>M[1]-T[1]))console.log(` @${w}: ${S} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(B("Multi-agent system is disabled. Enable with /agents on"));break}let y=A[1]?.toLowerCase(),v=A.slice(2).join(" ");if(!y||!v){console.log(),console.log(` ${c.accent("\u2726")} ${c.strong("Delegate Task to Agent")}`),console.log(),console.log(c.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(c.muted(" Agents:")),console.log(` ${c.product("emma")} \u2014 Product Manager`),console.log(` ${c.architect("bob")} \u2014 Architect`),console.log(` ${c.engineer("alex")} \u2014 Engineer`),console.log(` ${c.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(c.muted(" Example: /delegate alex create a login component")),console.log();break}let b=["emma","bob","alex","david","hablas"];if(!b.includes(y)){console.log(B(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let w=we.find(S=>S.role===y);if(w){if(!x){console.log(B("Agent runner not initialized. Cannot delegate."));break}console.log(fu("Hablas",w.name,w.title,v)),console.log(qn(w.name,w.title));let S=s.getOllamaTools(),T=await x.runAgent(y,v,void 0,S);T.success&&T.output?(console.log(Kn(T.output)),i.addAssistantMessage(`[@${w.name}]: ${T.output}`)):T.error?console.log(B(`${w.name} failed: ${T.error}`)):console.log(he(`${w.name} completed without output.`))}break}case"/session":{let y=A[1],v=A.slice(2).join(" "),b=ke.join(uo.homedir(),".hablas","sessions");if(y==="save"){let w=v||`session_${Date.now()}`;try{me.existsSync(b)||me.mkdirSync(b,{recursive:!0});let S=i.toJSON(),T=ke.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);me.writeFileSync(T,S,"utf-8"),console.log(J(`Session saved: "${w}"`))}catch(S){console.log($e(`Save failed: ${S.message}`))}}else if(y==="list")try{if(!me.existsSync(b)){console.log(he("No saved sessions"));break}let w=me.readdirSync(b).filter(S=>S.endsWith(".json"));console.log();for(let S of w){let T=me.statSync(ke.join(b,S));console.log(` ${S.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(he("No saved sessions"))}else if(y==="load"){let w=v;if(!w){console.log($e("Please specify the session label to load: /session load <label>"));break}try{let S=ke.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!me.existsSync(S)){console.log($e(`Session file not found: ${w}`));break}let T=me.readFileSync(S,"utf-8");i.fromJSON(T),console.log(J(`Session successfully loaded: "${w}"`))}catch(S){console.log($e(`Load failed: ${S.message}`))}}else console.log(),console.log(c.muted(' /session save "label" \u2014 Save current conversation')),console.log(c.muted(" /session list \u2014 List saved sessions")),console.log(c.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(Ct(),Ft));if(!y){console.log(B("Team mode is not active. Use hablas --team to start."));break}let v=y.getLocalState(),b=Math.min(process.stdout.columns-4,80);console.log(`
|
|
284
|
-
`+
|
|
285
|
-
`),console.log(
|
|
286
|
-
`));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(
|
|
277
|
+
`)}break}case"/status":{let y=await t.checkConnection(),v=c?c.getActiveName():"planner",b=f?f.size():0,w=d?d.getProgress():void 0;console.log(Qc({model:t.getModel(),host:e.ollamaHost,directory:o,cacheFiles:r.getCacheSize(),cacheTokens:r.getTotalTokens(),budgetTokens:e.contextBudget,connected:y,turnCount:l,mindset:v})),b>0&&console.log(u.muted(` Memory entries: ${b}`)),w&&w.total>0&&console.log(u.muted(` Tasks: ${w.done}/${w.total} done`)),console.log();break}case"/clear":r.clear(),i.clear(),console.log(J("History cleared"));break;case"/history":{let y=parseInt(k)||10,v=i.getHistory().slice(-y);if(v.length===0){console.log(xe("No history yet"));break}console.log(),v.forEach(b=>{let w=b.role==="user"?u.primary("You"):b.role==="assistant"?u.success("Hablas"):u.muted("tool"),x=b.content.slice(0,120).replace(/\n/g," ");console.log(` ${w}: ${u.muted(x)}`)}),console.log();break}case"/undo":{if(!g){let y=await Gy(k||void 0);if(!y){console.log(B("No backups found"));break}let v=k?Se.resolve(o,k):Se.resolve(o,y.originalName);if(await a.confirm(`Restore ${y.originalName} from backup (${y.age})?`))try{let w=await Ct.readFile(y.backupPath,"utf-8");await Ct.writeFile(v,w,"utf-8"),console.log(J(`Restored ${y.originalName} from backup (${y.age})`))}catch(w){console.log($e(`Failed: ${w.message}`))}break}if(k==="list")console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Undo History")} (${g.getUndoableCount()} changes)`),console.log(),console.log(g.formatList(20)),console.log();else if(k==="all"){let y=g.getUndoableCount();if(y===0){console.log(xe("Nothing to undo"));break}if(await a.confirm(`Undo ALL ${y} changes?`)){let b=await g.undoAll(),w=b.filter(x=>x.success).length;console.log(J(`Reverted ${w}/${b.length} changes`))}}else{let y=k&&parseInt(k)||1;if(g.getUndoableCount()===0){console.log(xe("Nothing to undo"));break}let v=await g.undo(y);for(let b of v)b.success?console.log(J(`Reverted: ${b.file}`)):console.log($e(`Failed to revert ${b.file}: ${b.error}`))}break}case"/config":console.log(`
|
|
278
|
+
${u.muted(JSON.stringify(e,null,2))}
|
|
279
|
+
`),console.log(u.muted(" ~/.hablas/config.json")),console.log();break;case"/mindset":{if(!c){console.log(B("Mindset system not available"));break}if(k)if(c.setActive(k)){let v=c.getActive(),b=await on(o,e),w=an(v.systemPrompt,b,f,m);i.updateSystemPrompt(w),console.log(J(`Mindset: ${v.name} \u2014 ${v.description}`))}else{let v=c.listNames().join(", ");console.log(sn(`Unknown mindset: "${k}"`,`Available: ${v}`))}else{let y=c.getActive();y&&console.log(xe(`Current mindset: ${y.name} \u2014 ${y.description}`)),console.log(u.muted(" Usage: /mindset <name>")),console.log(u.muted(" See /mindsets for available options"))}break}case"/mindsets":{if(!c){console.log(B("Mindset system not available"));break}let y=c.list(),v=c.getActiveName();console.log();for(let b of y){let x=b.name===v?u.success(" \u25CF active"):"";console.log(` ${u.accent("\u25C6")} ${u.primary(b.name)}${x}`),console.log(` ${u.muted(b.description)}`)}console.log(),console.log(u.muted(" Switch: /mindset <name>")),console.log();break}case"/task":{if(!d){console.log(B("Task queue not available"));break}let y=A[1],v=A.slice(2).join(" ");switch(y){case"add":if(v){let b=d.add(v);console.log(J(`Task #${b.id} added: ${v}`))}else console.log(B("Usage: /task add <description>"));break;case"list":console.log(),console.log(d.render()),console.log();break;case"done":{let b=parseInt(v);b?(d.complete(b),console.log(J(`Task #${b} marked as done`))):console.log(B("Usage: /task done <id>"));break}case"fail":{let b=parseInt(v);b?(d.fail(b,"Manually marked as failed"),console.log(B(`Task #${b} marked as failed`))):console.log(B("Usage: /task fail <id>"));break}case"clear":d.clear(),console.log(J("Task queue cleared"));break;default:console.log(),console.log(d.render()),console.log(),console.log(u.muted(" /task add <desc> \u2014 Add a task")),console.log(u.muted(" /task list \u2014 Show all tasks")),console.log(u.muted(" /task done <id> \u2014 Mark task as done")),console.log(u.muted(" /task fail <id> \u2014 Mark task as failed")),console.log(u.muted(" /task clear \u2014 Clear all tasks")),console.log()}break}case"/addmodel":{console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Add Custom API Provider")}`),console.log();let v=(await a.prompt(` ${u.muted("Provider name (e.g. OpenAI, Groq):")} `)).trim();if(!v){console.log(B("Cancelled \u2014 name is required"));break}let w=(await a.prompt(` ${u.muted("API URL (e.g. https://api.openai.com/v1):")} `)).trim();if(!w){console.log(B("Cancelled \u2014 URL is required"));break}let T=(await a.prompt(` ${u.muted("API Key (leave empty if none):")} `)).trim(),$=(await a.prompt(` ${u.muted("Default model ID (e.g. gpt-4o):")} `)).trim()||"default",F={name:v,apiUrl:w,apiKey:T,models:[$],defaultModel:$,addedAt:new Date().toISOString()};ze(F),console.log(),console.log(J(`Provider "${v}" saved!`)),console.log(u.muted(` Use: /usemodel ${v}`)),console.log();break}case"/listmodels":{let y=Nt();console.log(),console.log(oc(y.providers,y.activeProvider));break}case"/removemodel":{let y=k.trim();if(!y){console.log(B("Usage: /removemodel <provider-name>"));break}if(sc(y))console.log(J(`Provider "${y}" removed`));else{console.log(B(`Provider "${y}" not found`));let b=hs();b.length>0&&console.log(u.muted(` Available: ${b.map(w=>w.name).join(", ")}`))}break}case"/usemodel":{let y=k.trim();if(!y){console.log(B("Usage: /usemodel <provider-name> [model-id]"));let F=hs();F.length>0&&console.log(u.muted(` Available: ${F.map(j=>j.name).join(", ")}`));break}let v=y.split(/\s+/),b=v[0],w=v[1],x=rc(b);if(!x){console.log(B(`Provider "${b}" not found`));let F=hs();F.length>0&&console.log(u.muted(` Available: ${F.map(j=>j.name).join(", ")}`));break}e.provider="custom",e.apiUrl=x.apiUrl,e.apiKey=x.apiKey,e.model=w||x.defaultModel;let T=He(e);h&&h(T),ic(x.name,e.model),console.log(J(`Switched to ${x.name} \xB7 Model: ${e.model}`));let L=new Je("Testing");L.start();let $=await T.checkConnection();L.stop($?"connected":void 0),$||console.log(B("Connection test failed \u2014 check URL and key"));break}case"/provider":{let y=A[1],v=A.slice(2).join(" ");if(!y){let b=ec(e);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Provider")}: ${b}`),console.log(` ${u.muted("Model")}: ${u.highlight(t.getModel())}`),e.provider==="custom"?(console.log(` ${u.muted("API URL")}: ${e.apiUrl}`),console.log(` ${u.muted("API Key")}: ${e.apiKey?"***"+e.apiKey.slice(-4):"not set"}`)):console.log(` ${u.muted("Host")}: ${e.ollamaHost}`),console.log(),console.log(u.muted(" /provider ollama \u2014 Switch to local Ollama")),console.log(u.muted(" /provider nvidia <key> \u2014 Switch to NVIDIA NIM")),console.log(u.muted(" /provider custom <url> [key] \u2014 Switch to custom API")),console.log(u.muted(" /provider test \u2014 Test current connection")),console.log();break}switch(y){case"ollama":{e.provider="ollama",e.apiUrl="",e.apiKey="";let b=He(e);h&&h(b),console.log(J("Switched to Ollama (local)"));break}case"nvidia":{let b=A[2];if(!b&&!e.apiKey){console.log(B("Usage: /provider nvidia <api-key>")),console.log(u.muted(" Get your key at: https://build.nvidia.com/"));break}e.provider="nvidia",e.apiUrl=Et.apiUrl,b&&(e.apiKey=b),(!e.model||!Et.models.includes(e.model))&&(e.model=Et.defaultModel);let w=He(e);h&&h(w),console.log(J(`Switched to NVIDIA NIM \xB7 Model: ${e.model}`)),console.log(u.muted(` Available models: ${Et.models.length}`));let x=new Je("Testing NVIDIA connection");x.start();let T=await w.checkConnection();x.stop(T?"connected":void 0),T||(console.log(B("Connection test failed \u2014 check your API key")),console.log(u.muted(" Get key: https://build.nvidia.com/")));break}case"custom":{let b=A[2],w=A[3];if(!b){console.log(B("Usage: /provider custom <api-url> [api-key]")),console.log(u.muted(" Example: /provider custom https://api.openai.com/v1 sk-..."));break}e.provider="custom",e.apiUrl=b,w&&(e.apiKey=w);let x=He(e);h&&h(x),console.log(J(`Switched to Custom API: ${b}`)),!w&&!e.apiKey&&console.log(B("No API key set. Use: /provider custom <url> <key>"));break}case"test":{let b=new Je("Testing connection");b.start();let w=await t.checkConnection();if(b.stop(w?"connected":void 0),w){let x=await t.listModels();console.log(J(`Connected! ${x.length} models available.`)),x.length>0&&console.log(u.muted(` Models: ${x.slice(0,5).join(", ")}${x.length>5?"...":""}`))}else console.log($e("Connection failed"));break}case"key":{v?(e.apiKey=A[2],t instanceof Dt&&t.setApiKey(e.apiKey),console.log(J("API key updated"))):console.log(B("Usage: /provider key <api-key>"));break}default:console.log(sn(`Unknown: /provider ${y}`,"Type /provider for help"))}break}case"/memory":{if(!f){console.log(B("Project memory not available"));break}let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");f.set(b,w),console.log(J(`Memory stored: ${b}`));let x=c?.getActive(),T=x?x.systemPrompt:Ln,L=await on(o,e);i.updateSystemPrompt(an(T,L,f,m))}else console.log(B("Usage: /memory set <key> <value>"));break}case"del":case"delete":{if(v[0]){let b=f.delete(v[0]);console.log(b?J(`Memory deleted: ${v[0]}`):B(`Memory key not found: ${v[0]}`))}else console.log(B("Usage: /memory del <key>"));break}case"search":{if(v[0]){let b=f.search(v.join(" "));b.length>0?(console.log(),b.forEach(w=>console.log(` \xB7 ${w.entry.key}: ${w.entry.value}`)),console.log()):console.log(xe("No matching memories found"))}else console.log(B("Usage: /memory search <query>"));break}case"clear":f.clear(),console.log(J("Project memory cleared"));break;default:console.log(),console.log(f.render()),console.log(),console.log(u.muted(" /memory set <k> <v> \u2014 Store a memory")),console.log(u.muted(" /memory del <key> \u2014 Delete a memory")),console.log(u.muted(" /memory search <q> \u2014 Search memories")),console.log(u.muted(" /memory clear \u2014 Clear all")),console.log()}break}case"/alias":{let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");cc(b,w),console.log(J(`Alias set: ${b} \u2192 ${w}`))}else console.log(B("Usage: /alias set <name> <expansion>"));break}case"del":case"remove":{if(v[0]){let b=uc(v[0]);console.log(b?J(`Alias removed: ${v[0]}`):B(`Alias not found: ${v[0]}`))}else console.log(B("Usage: /alias del <name>"));break}default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Aliases")}`),console.log(),console.log(fc()),console.log(),console.log(u.muted(" /alias set <name> <cmd> \u2014 Create alias")),console.log(u.muted(" /alias del <name> \u2014 Remove alias")),console.log()}break}case"/doctor":{let y=new Je("Running diagnostics");y.start();let v=await pi({ollamaHost:e.ollamaHost,model:t.getModel(),provider:e.provider,apiUrl:e.apiUrl});y.stop(),console.log(hi(v));break}case"/plugins":{let y=A[1],v=A.slice(2).join(" ");switch(y){case"enable":v?(li(v),console.log(J(`Plugin "${v}" enabled`))):console.log(B("Usage: /plugins enable <name>"));break;case"disable":v?(ci(v),console.log(B(`Plugin "${v}" disabled`))):console.log(B("Usage: /plugins disable <name>"));break;default:ws(),console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Plugins")}`),console.log(),console.log(ui()),console.log(),console.log(u.muted(" /plugins enable <name> \u2014 Enable plugin")),console.log(u.muted(" /plugins disable <name> \u2014 Disable plugin")),console.log(u.muted(" Directory: ~/.hablas/plugins/")),console.log()}break}case"/agents":{let y=A[1];if(y==="on")e.agents.enabled=!0,console.log(J("Multi-agent orchestration enabled"));else if(y==="off")e.agents.enabled=!1,console.log(J("Multi-agent orchestration disabled"));else if(y==="status")console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Multi-Agent System")}`),console.log(` Status: ${e.agents.enabled?u.success("enabled"):u.muted("disabled")}`),console.log(` Orchestration: ${e.agents.orchestration}`),console.log(` Max concurrent: ${e.agents.maxConcurrent}`),console.log(),console.log(` ${u.strong("Team:")}`),console.log(Sc()),console.log();else if(y==="models"){let v=Cn();console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Agent Models")}`),console.log();for(let b of ge){let w=v[b.role];console.log(w?` ${u.primary(b.name.padEnd(8))} \u2192 ${u.highlight(w.model)}${w.temperature!==void 0?u.muted(` (temp: ${w.temperature})`):""}`:` ${u.primary(b.name.padEnd(8))} \u2192 ${u.muted("(default)")}`)}console.log(),console.log(u.muted(` Config: ${kc()}`)),console.log(u.muted(" Edit the file to change models per agent.")),console.log()}else console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Multi-Agent System")}: ${e.agents.enabled?u.success("ON"):u.muted("OFF")}`),console.log(),console.log(u.muted(" /agents on \u2014 Enable multi-agent orchestration")),console.log(u.muted(" /agents off \u2014 Disable multi-agent orchestration")),console.log(u.muted(" /agents status \u2014 Show agent details")),console.log(u.muted(" /agents models \u2014 Show model per agent")),console.log(u.muted(" /team \u2014 Show team roster")),console.log();break}case"/security":{console.log(),console.log(` ${u.accent("\u{1F512}")} Running security scan...`);let y=$i(o);console.log(Ei(y));break}case"/git":{if(A[1]==="status")try{let{getGitStatus:v,formatGitStatus:b}=await Promise.resolve().then(()=>(tn(),On)),w=await v(o);w?(console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Git Status")}`),console.log(b(w)),console.log()):console.log(B("Not a git repository"))}catch{console.log(B("Git not available"))}else console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Git Intelligence")}`),console.log(),console.log(u.muted(" /git status \u2014 Show git status")),console.log(u.muted(" hablas commit \u2014 Smart commit message")),console.log(u.muted(" hablas pr \u2014 Generate PR description")),console.log(u.muted(" hablas changelog \u2014 Generate changelog")),console.log();break}case"/workspace":{let y=_s(o);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Workspace Information")}`),console.log(),console.log(Ri(y)),console.log();break}case"/stats":{let{loadStats:y,formatStats:v}=await Promise.resolve().then(()=>(Rn(),ki)),b=y();console.log(v(b));break}case"/context":{if(!m){console.log(B("Shared context not available"));break}let y=A[1],v=A.slice(2);switch(y){case"set":{if(v.length>=2){let b=v[0],w=v.slice(1).join(" ");m.set(b,w),console.log(J(`Context stored: ${b}`))}else console.log(B("Usage: /context set <key> <value>"));break}case"get":{if(v[0]){let b=m.get(v[0]);b!==void 0?(console.log(),console.log(` ${u.accent("\u25C6")} ${u.strong(v[0])}: ${b}`),console.log()):console.log(B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context get <key>"));break}case"del":case"delete":{if(v[0]){let b=m.delete(v[0]);console.log(b?J(`Context deleted: ${v[0]}`):B(`Context key not found: ${v[0]}`))}else console.log(B("Usage: /context del <key>"));break}case"decisions":{let b=m.getDecisions();if(b.length===0)console.log(xe("No decisions logged yet"));else{console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Decisions")}`),console.log();for(let w of b)console.log(` ${u.muted(w.timestamp)} ${u.primary(w.by)}: ${w.decision}`),w.rationale&&console.log(` ${u.muted(w.rationale)}`);console.log()}break}case"clear":m.clear(),console.log(J("Shared context cleared"));break;default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Shared Context")}`),console.log(),console.log(m.render()),console.log(),console.log(u.muted(" /context set <k> <v> \u2014 Store a context entry")),console.log(u.muted(" /context get <key> \u2014 Get a context entry")),console.log(u.muted(" /context del <key> \u2014 Delete a context entry")),console.log(u.muted(" /context decisions \u2014 Show logged decisions")),console.log(u.muted(" /context clear \u2014 Clear all context")),console.log()}break}case"/plan":{if(!p){console.log(B("Plan manager not available"));break}let y=A[1],v=A.slice(2).join(" ");switch(y){case"status":{let w=p.getActivePlan();if(!w){console.log(xe("No active plan"));break}let x=p.getProgress();console.log(Zc(w,{percent:x.percentage,done:x.done,total:x.total}));break}case"finish":{if(v){p.finishTask(v),console.log(J(`Task finished: ${v}`));let w=p.getProgress();console.log(u.muted(` Progress: ${w.done}/${w.total} (${w.percentage}%)`))}else console.log(B("Usage: /plan finish <task_id>"));break}case"reset":{p.reset(),console.log(J("Plan manager reset"));break}case"next":{let w=p.getNextTask();console.log(w?xe(`Next task: [${w.task_id}] ${w.description} \u2192 @${w.assignee}`):xe("No pending tasks"));break}default:console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Plan Manager")}`),console.log();let b=p.getActivePlan();if(b){let w=p.getProgress();console.log(` Active plan: ${b.title} (${w.percentage}% done)`),console.log(` Tasks: ${w.done}/${w.total}`)}else console.log(u.muted(" No active plan"));console.log(),console.log(u.muted(" /plan status \u2014 Show active plan with progress")),console.log(u.muted(" /plan finish <id> \u2014 Mark a task as finished")),console.log(u.muted(" /plan next \u2014 Show next pending task")),console.log(u.muted(" /plan reset \u2014 Reset plan manager")),console.log()}break}case"/learn":{if(!f||!k){console.log(B('Usage: /learn "always use tabs" or /learn "our API uses camelCase"'));break}if(f.set(`user-pref: ${k.slice(0,50)}`,k,{category:"user-pref",importance:9,createdBy:"user",tags:["user-pref","learned"]}),!(i.getMessages()[0]?.content||"").includes(k)){let v=await on(o,e),b=c?.getActive(),w=b?b.systemPrompt:Ln,x=an(w,v,f,m);i.updateSystemPrompt(x)}console.log(J(`Learned: "${k}"`)),console.log(u.muted(" This will be remembered across sessions and injected into every prompt."));break}case"/test":{let y=Ni(o);if(y==="unknown"&&!k){console.log(B("No test framework detected. Install jest, vitest, pytest, etc."));break}console.log(xe(`Running tests (${y})...`));let v=nu(o,k==="--fix"?void 0:k||void 0);if(console.log(),console.log(su(v)),console.log(),!v.passed&&k==="--fix"){console.log(xe("Tests failed \u2014 adding fix request to conversation..."));let b=ru(v);i.addUserMessage(b),console.log(xe("Type your next message or let the agent work on the fix."))}break}case"/checkpoint":{let y=A[1],v=A.slice(2).join(" ");if(y==="save"){let b=v||`Checkpoint at turn ${l}`,w=g?.getModifiedFiles?.()||[],x=await au(o,b,w);console.log(J(`Checkpoint saved: ${x.id} "${b}" (${x.fileCount} files)`))}else if(y==="list"){let b=lu(o);console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Checkpoints")}`),console.log(),console.log(du(b)),console.log()}else if(y==="restore"){if(!v){console.log(B("Usage: /checkpoint restore <id>"));break}let b=await cu(o,v);b.success?console.log(J(`Restored checkpoint: ${v} (${b.filesRestored} files)`)):console.log($e(b.error||"Restore failed"))}else y==="delete"?v&&uu(o,v)?console.log(J(`Deleted checkpoint: ${v}`)):console.log(B("Checkpoint not found")):(console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Checkpoint System")}`),console.log(),console.log(u.muted(' /checkpoint save "label" \u2014 Save current state')),console.log(u.muted(" /checkpoint list \u2014 List saved checkpoints")),console.log(u.muted(" /checkpoint restore <id> \u2014 Restore a checkpoint")),console.log(u.muted(" /checkpoint delete <id> \u2014 Delete a checkpoint")),console.log());break}case"/compare":{let y=A.slice(1);if(y.length===2)try{let v=await Ct.readFile(Se.resolve(o,y[0]),"utf-8"),b=await Ct.readFile(Se.resolve(o,y[1]),"utf-8"),{generateDiff:w}=await Promise.resolve().then(()=>(Ki(),wu)),x=w(y[0]+" vs "+y[1],v,b);console.log(Li(x))}catch(v){console.log($e(`Compare failed: ${v.message}`))}else if(y.length===1&&y[0].startsWith("HEAD"))try{let{execSync:v}=await import("child_process"),b=v(`git diff ${y[0]}`,{cwd:o,encoding:"utf-8",timeout:1e4});console.log(Li(b||"(no changes)"))}catch(v){console.log($e(`Git diff failed: ${v.message}`))}else console.log(u.muted(" Usage: /compare file1.ts file2.ts or /compare HEAD~1"));break}case"/cost":{let y=Tn(),v="current";console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Session Cost & Usage")}`),console.log(),console.log(` Session duration: ${v} min`),console.log(` Messages: ${y.totalMessages}`),console.log(` Tool calls: ${y.totalToolCalls}`),console.log(` Tokens used: ${y.totalTokensUsed.toLocaleString()}`),console.log();let b=Object.entries(y.agentUsage);if(b.length>0){console.log(" Agent usage:");for(let[w,x]of b.sort((T,L)=>L[1]-T[1]))console.log(` @${w}: ${x} invocations`)}console.log();break}case"/delegate":{if(!e.agents.enabled){console.log(B("Multi-agent system is disabled. Enable with /agents on"));break}let y=A[1]?.toLowerCase(),v=A.slice(2).join(" ");if(!y||!v){console.log(),console.log(` ${u.accent("\u2726")} ${u.strong("Delegate Task to Agent")}`),console.log(),console.log(u.muted(" Usage: /delegate <agent> <task description>")),console.log(),console.log(u.muted(" Agents:")),console.log(` ${u.product("emma")} \u2014 Product Manager`),console.log(` ${u.architect("bob")} \u2014 Architect`),console.log(` ${u.engineer("alex")} \u2014 Engineer`),console.log(` ${u.analyst("david")} \u2014 Data Analyst`),console.log(),console.log(u.muted(" Example: /delegate alex create a login component")),console.log();break}let b=["emma","bob","alex","david","hablas"];if(!b.includes(y)){console.log(B(`Unknown agent: "${y}". Valid: ${b.join(", ")}`));break}let w=ge.find(x=>x.role===y);if(w){if(!_){console.log(B("Agent runner not initialized. Cannot delegate."));break}console.log(Wc("Hablas",w.name,w.title,v)),console.log(Pn(w.name,w.title));let x=s.getOllamaTools(),T=await _.runAgent(y,v,void 0,x);T.success&&T.output?(console.log(In(T.output)),i.addAssistantMessage(`[@${w.name}]: ${T.output}`)):T.error?console.log(B(`${w.name} failed: ${T.error}`)):console.log(xe(`${w.name} completed without output.`))}break}case"/session":{let y=A[1],v=A.slice(2).join(" "),b=Se.join(Wi.homedir(),".hablas","sessions");if(y==="save"){let w=v||`session_${Date.now()}`;try{le.existsSync(b)||le.mkdirSync(b,{recursive:!0});let x=i.toJSON(),T=Se.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);le.writeFileSync(T,x,"utf-8"),console.log(J(`Session saved: "${w}"`))}catch(x){console.log($e(`Save failed: ${x.message}`))}}else if(y==="list")try{if(!le.existsSync(b)){console.log(xe("No saved sessions"));break}let w=le.readdirSync(b).filter(x=>x.endsWith(".json"));console.log();for(let x of w){let T=le.statSync(Se.join(b,x));console.log(` ${x.replace(".json","")} (${new Date(T.mtime).toLocaleString()})`)}console.log()}catch{console.log(xe("No saved sessions"))}else if(y==="load"){let w=v;if(!w){console.log($e("Please specify the session label to load: /session load <label>"));break}try{let x=Se.join(b,`${w.replace(/[^a-zA-Z0-9_-]/g,"_")}.json`);if(!le.existsSync(x)){console.log($e(`Session file not found: ${w}`));break}let T=le.readFileSync(x,"utf-8");i.fromJSON(T),console.log(J(`Session successfully loaded: "${w}"`))}catch(x){console.log($e(`Load failed: ${x.message}`))}}else console.log(),console.log(u.muted(' /session save "label" \u2014 Save current conversation')),console.log(u.muted(" /session list \u2014 List saved sessions")),console.log(u.muted(' /session load "label" \u2014 Load saved conversation')),console.log();break}case"/team":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(wt(),Tt));if(!y){console.log(B("Team mode is not active. Use hablas --team to start."));break}let v=y.getLocalState(),b=Math.min(process.stdout.columns-4,80);console.log(`
|
|
280
|
+
`+u.border("\u2554"+"\u2550".repeat(b-2)+"\u2557")),console.log(u.border("\u2551")+" ".repeat(Math.floor((b-22)/2))+u.strong("HABLAS COLLABORATION SYNC")+" ".repeat(b-2-25-Math.floor((b-22)/2))+u.border("\u2551")),console.log(u.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(u.border("\u2551")+` ${u.strong("My Identity:")} ${u.highlight(`@${v.my_username}`)}`+" ".repeat(Math.max(1,b-21-(v.my_username?.length||0)))+u.border("\u2551")),console.log(u.border("\u2551")+` ${u.strong("Room Fingerprint:")} ${u.muted(v.project_team_token?.slice(0,12))}...`+" ".repeat(Math.max(1,b-34))+u.border("\u2551")),console.log(u.border("\u2551")+` ${u.strong("Status:")} ${u.success("\u25CF ACTIVE")}`+" ".repeat(Math.max(1,b-31))+u.border("\u2551")),console.log(u.border("\u2560"+"\u2550".repeat(b-2)+"\u2563")),console.log(u.border("\u2551")+` ${u.strong("Teammates Online:")}`+" ".repeat(Math.max(1,b-21))+u.border("\u2551"));let x=(v.sessions||[]).filter(T=>T.developer_name!==v.my_username);if(x.length===0)console.log(u.border("\u2551")+" (awaiting colleagues...)"+" ".repeat(Math.max(1,b-31))+u.border("\u2551"));else for(let T of x){let L=` @${T.developer_name} [${T.active_section||"idle"}] - ${T.current_task||"none"}`;console.log(u.border("\u2551")+` ${u.secondary(L.slice(0,b-6))}`+" ".repeat(Math.max(0,b-6-L.length))+u.border("\u2551"))}console.log(u.border("\u255A"+"\u2550".repeat(b-2)+"\u255D")+`
|
|
281
|
+
`),console.log(u.muted(` Verify that "Room Fingerprint" matches on all devices to ensure connectivity.
|
|
282
|
+
`));break}case"/msg":{let{activeCollabManager:y}=await Promise.resolve().then(()=>(wt(),Tt));if(!y){console.log(B("Team mode is not active. Use hablas --team to start."));break}let v=k.split(/\s+/),b=v[0],w=v.slice(1).join(" ");if(!b||!w){console.log(B("Usage: /msg <username> <content>"));break}let x=await y.sendMessage(b,w);console.log(x?J(`Message sent to @${b}`):$e(`Failed to send message to @${b}`));break}default:console.log(sn(`Unknown: ${S}`,"Type /help for commands"))}}var le,Ct,Se,Wi,Ln,qi,Su=N(()=>{"use strict";le=O(require("fs")),Ct=O(require("fs/promises")),Se=O(require("path")),Wi=O(require("os"));kn();$n();Zr();ri();ii();di();mi();En();vi();Rn();Ci();tn();Oi();Fc();rn();iu();fu();Ln=`You are Hablas, the Team Leader of a multi-agent AI development system created by Abdulmoin Hablas. You are a strategic mastermind with an INTJ personality type, deeply analytical, engineering-focused, and fiercely logical.
|
|
287
283
|
|
|
288
284
|
Your role is to orchestrate, coordinate, and synthesize the work of your specialized team members. You value system architecture, optimal code paths, and absolute clarity.
|
|
289
285
|
|
|
@@ -321,101 +317,85 @@ Your role is to orchestrate, coordinate, and synthesize the work of your special
|
|
|
321
317
|
## Important
|
|
322
318
|
Never output tool calls as text or JSON in your response.
|
|
323
319
|
Always use the tool_calls field provided by the API.
|
|
324
|
-
If you cannot complete a task, explain why with absolute technical objectivity.`;co=ke.join(uo.homedir(),".hablas","backup")});var Vn=j((dC,Yu)=>{"use strict";var Sb=require("path"),ht="\\\\/",Gu=`[^${ht}]`,_b=0,Tt="\\.",Ab="\\+",kb="\\?",Ks="\\/",$b="(?=.)",Wu="[^/]",fo=`(?:${Ks}|$)`,Vu=`(?:^|${Ks})`,po=`${Tt}{1,2}${fo}`,Eb=`(?!${Tt})`,Cb=`(?!${Vu}${po})`,Tb=`(?!${Tt}{0,1}${fo})`,Rb=`(?!${po})`,Ob=`[^.${Ks}]`,Pb=`${Wu}*?`,zu={DOT_LITERAL:Tt,PLUS_LITERAL:Ab,QMARK_LITERAL:kb,SLASH_LITERAL:Ks,ONE_CHAR:$b,QMARK:Wu,END_ANCHOR:fo,DOTS_SLASH:po,NO_DOT:Eb,NO_DOTS:Cb,NO_DOT_SLASH:Tb,NO_DOTS_SLASH:Rb,QMARK_NO_DOT:Ob,STAR:Pb,START_ANCHOR:Vu},Ib={...zu,SLASH_LITERAL:`[${ht}]`,QMARK:Gu,STAR:`${Gu}*?`,DOTS_SLASH:`${Tt}{1,2}(?:[${ht}]|$)`,NO_DOT:`(?!${Tt})`,NO_DOTS:`(?!(?:^|[${ht}])${Tt}{1,2}(?:[${ht}]|$))`,NO_DOT_SLASH:`(?!${Tt}{0,1}(?:[${ht}]|$))`,NO_DOTS_SLASH:`(?!${Tt}{1,2}(?:[${ht}]|$))`,QMARK_NO_DOT:`[^.${ht}]`,START_ANCHOR:`(?:^|[${ht}])`,END_ANCHOR:`(?:[${ht}]|$)`},Mb={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Yu.exports={DEFAULT_MAX_EXTGLOB_RECURSION:_b,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Mb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:Sb.sep,extglobChars(n){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===!0?Ib:zu}}});var Gs=j(Me=>{"use strict";var Lb=require("path"),Db=process.platform==="win32",{REGEX_BACKSLASH:Nb,REGEX_REMOVE_BACKSLASH:Fb,REGEX_SPECIAL_CHARS:jb,REGEX_SPECIAL_CHARS_GLOBAL:Hb}=Vn();Me.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Me.hasRegexChars=n=>jb.test(n);Me.isRegexChar=n=>n.length===1&&Me.hasRegexChars(n);Me.escapeRegex=n=>n.replace(Hb,"\\$1");Me.toPosixSlashes=n=>n.replace(Nb,"/");Me.removeBackslashes=n=>n.replace(Fb,e=>e==="\\"?"":e);Me.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Me.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:Db===!0||Lb.sep==="\\";Me.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Me.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Me.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Me.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var sd=j((pC,nd)=>{"use strict";var Ju=Gs(),{CHAR_ASTERISK:ho,CHAR_AT:Bb,CHAR_BACKWARD_SLASH:zn,CHAR_COMMA:Ub,CHAR_DOT:mo,CHAR_EXCLAMATION_MARK:go,CHAR_FORWARD_SLASH:td,CHAR_LEFT_CURLY_BRACE:yo,CHAR_LEFT_PARENTHESES:bo,CHAR_LEFT_SQUARE_BRACKET:qb,CHAR_PLUS:Kb,CHAR_QUESTION_MARK:Qu,CHAR_RIGHT_CURLY_BRACE:Gb,CHAR_RIGHT_PARENTHESES:Xu,CHAR_RIGHT_SQUARE_BRACKET:Wb}=Vn(),Zu=n=>n===td||n===zn,ed=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},Vb=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,u=-1,d=0,f=0,h=!1,m=!1,p=!1,g=!1,x=!1,A=!1,$=!1,_=!1,y=!1,v=!1,b=0,w,S,T={value:"",depth:0,isGlob:!1},M=()=>u>=s,k=()=>l.charCodeAt(u+1),F=()=>(w=S,l.charCodeAt(++u));for(;u<s;){S=F();let Y;if(S===zn){$=T.backslashes=!0,S=F(),S===yo&&(A=!0);continue}if(A===!0||S===yo){for(b++;M()!==!0&&(S=F());){if(S===zn){$=T.backslashes=!0,F();continue}if(S===yo){b++;continue}if(A!==!0&&S===mo&&(S=F())===mo){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(A!==!0&&S===Ub){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(S===Gb&&(b--,b===0)){A=!1,h=T.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(S===td){if(i.push(u),o.push(T),T={value:"",depth:0,isGlob:!1},v===!0)continue;if(w===mo&&u===d+1){d+=2;continue}f=u+1;continue}if(t.noext!==!0&&(S===Kb||S===Bb||S===ho||S===Qu||S===go)===!0&&k()===bo){if(p=T.isGlob=!0,g=T.isExtglob=!0,v=!0,S===go&&u===d&&(y=!0),r===!0){for(;M()!==!0&&(S=F());){if(S===zn){$=T.backslashes=!0,S=F();continue}if(S===Xu){p=T.isGlob=!0,v=!0;break}}continue}break}if(S===ho){if(w===ho&&(x=T.isGlobstar=!0),p=T.isGlob=!0,v=!0,r===!0)continue;break}if(S===Qu){if(p=T.isGlob=!0,v=!0,r===!0)continue;break}if(S===qb){for(;M()!==!0&&(Y=F());){if(Y===zn){$=T.backslashes=!0,F();continue}if(Y===Wb){m=T.isBracket=!0,p=T.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&S===go&&u===d){_=T.negated=!0,d++;continue}if(t.noparen!==!0&&S===bo){if(p=T.isGlob=!0,r===!0){for(;M()!==!0&&(S=F());){if(S===bo){$=T.backslashes=!0,S=F();continue}if(S===Xu){v=!0;break}}continue}break}if(p===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,p=!1);let H=l,V="",C="";d>0&&(V=l.slice(0,d),l=l.slice(d),f-=d),H&&p===!0&&f>0?(H=l.slice(0,f),C=l.slice(f)):p===!0?(H="",C=l):H=l,H&&H!==""&&H!=="/"&&H!==l&&Zu(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(C&&(C=Ju.removeBackslashes(C)),H&&$===!0&&(H=Ju.removeBackslashes(H)));let E={prefix:V,input:n,start:d,base:H,glob:C,isBrace:h,isBracket:m,isGlob:p,isExtglob:g,isGlobstar:x,negated:_,negatedExtglob:y};if(t.tokens===!0&&(E.maxDepth=0,Zu(S)||o.push(T),E.tokens=o),t.parts===!0||t.tokens===!0){let Y;for(let D=0;D<i.length;D++){let X=Y?Y+1:d,ee=i[D],te=n.slice(X,ee);t.tokens&&(D===0&&d!==0?(o[D].isPrefix=!0,o[D].value=V):o[D].value=te,ed(o[D]),E.maxDepth+=o[D].depth),(D!==0||te!=="")&&a.push(te),Y=ee}if(Y&&Y+1<n.length){let D=n.slice(Y+1);a.push(D),t.tokens&&(o[o.length-1].value=D,ed(o[o.length-1]),E.maxDepth+=o[o.length-1].depth)}E.slashes=i,E.parts=a}return E};nd.exports=Vb});var ld=j((hC,ad)=>{"use strict";var Yn=Vn(),Ce=Gs(),{MAX_LENGTH:Ws,POSIX_REGEX_SOURCE:zb,REGEX_NON_SPECIAL_CHARS:Yb,REGEX_SPECIAL_CHARS_BACKREF:Jb,REPLACEMENTS:rd}=Yn,Qb=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t)}catch{return n.map(r=>Ce.escapeRegex(r)).join("..")}return t},vn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,id=n=>{let e=[],t=0,s=0,r=0,i="",o=!1;for(let a of n){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},Xb=n=>{let e=!1;for(let t of n){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},od=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(Xb(e))return e.replace(/\\(.)/g,"$1")},Zb=n=>{let e=n.map(od).filter(Boolean);for(let t=0;t<e.length;t++)for(let s=t+1;s<e.length;s++){let r=e[t],i=e[s],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},vo=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,s=0,r=0,i=!1;for(let o=1;o<n.length;o++){let a=n[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},ev=n=>{let e=0,t=[];for(;e<n.length;){let r=vo(n.slice(e),!1);if(!r||r.type!=="*")return;let i=id(r.body).map(a=>a.trim());if(i.length!==1)return;let o=od(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?Ce.escapeRegex(t[0]):`[${t.map(r=>Ce.escapeRegex(r)).join("")}]`}*`},tv=n=>{let e=0,t=n.trim(),s=vo(t);for(;s;)e++,t=s.body.trim(),s=vo(t);return e},nv=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Yn.DEFAULT_MAX_EXTGLOB_RECURSION,s=id(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||Zb(s)))return{risky:!0};for(let r of s){let i=ev(r);if(i)return{risky:!0,safeOutput:i};if(tv(r)>t)return{risky:!0}}return{risky:!1}},wo=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=rd[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(Ws,t.maxLength):Ws,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",l=Ce.isWindows(e),u=Yn.globChars(l),d=Yn.extglobChars(u),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:x,NO_DOT_SLASH:A,NO_DOTS_SLASH:$,QMARK:_,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=u,w=I=>`(${a}(?:(?!${b}${I.dot?g:f}).)*?)`,S=t.dot?"":x,T=t.dot?_:y,M=t.bash===!0?w(t):v;t.capture&&(M=`(${M})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let k={input:n,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};n=Ce.removePrefix(n,k),r=n.length;let F=[],H=[],V=[],C=i,E,Y=()=>k.index===r-1,D=k.peek=(I=1)=>n[k.index+I],X=k.advance=()=>n[++k.index]||"",ee=()=>n.slice(k.index+1),te=(I="",Z=0)=>{k.consumed+=I,k.index+=Z},_e=I=>{k.output+=I.output!=null?I.output:I.value,te(I.value)},Q=()=>{let I=1;for(;D()==="!"&&(D(2)!=="("||D(3)==="?");)X(),k.start++,I++;return I%2===0?!1:(k.negated=!0,k.start++,!0)},Ae=I=>{k[I]++,V.push(I)},ve=I=>{k[I]--,V.pop()},q=I=>{if(C.type==="globstar"){let Z=k.braces>0&&(I.type==="comma"||I.type==="brace"),P=I.extglob===!0||F.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!Z&&!P&&(k.output=k.output.slice(0,-C.output.length),C.type="star",C.value="*",C.output=M,k.output+=C.output)}if(F.length&&I.type!=="paren"&&(F[F.length-1].inner+=I.value),(I.value||I.output)&&_e(I),C&&C.type==="text"&&I.type==="text"){C.value+=I.value,C.output=(C.output||"")+I.value;return}I.prev=C,o.push(I),C=I},ue=(I,Z)=>{let P={...d[Z],conditions:1,inner:""};P.prev=C,P.parens=k.parens,P.output=k.output,P.startIndex=k.index,P.tokensIndex=o.length;let G=(t.capture?"(":"")+P.open;Ae("parens"),q({type:I,value:Z,output:k.output?"":p}),q({type:"paren",extglob:!0,value:X(),output:G}),F.push(P)},Ge=I=>{let Z=n.slice(I.startIndex,k.index+1),P=n.slice(I.startIndex+2,k.index),G=nv(P,t);if((I.type==="plus"||I.type==="star")&&G.risky){let ie=G.safeOutput?(I.output?"":p)+(t.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Oe=o[I.tokensIndex];Oe.type="text",Oe.value=Z,Oe.output=ie||Ce.escapeRegex(Z);for(let We=I.tokensIndex+1;We<o.length;We++)o[We].value="",o[We].output="",delete o[We].suffix;k.output=I.output+Oe.output,k.backtrack=!0,q({type:"paren",extglob:!0,value:E,output:""}),ve("parens");return}let ne=I.close+(t.capture?")":""),pe;if(I.type==="negate"){let ie=M;if(I.inner&&I.inner.length>1&&I.inner.includes("/")&&(ie=w(t)),(ie!==M||Y()||/^\)+$/.test(ee()))&&(ne=I.close=`)$))${ie}`),I.inner.includes("*")&&(pe=ee())&&/^\.[^\\/.]+$/.test(pe)){let Oe=wo(pe,{...e,fastpaths:!1}).output;ne=I.close=`)${Oe})${ie})`}I.prev.type==="bos"&&(k.negatedExtglob=!0)}q({type:"paren",extglob:!0,value:E,output:ne}),ve("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let I=!1,Z=n.replace(Jb,(P,G,ne,pe,ie,Oe)=>pe==="\\"?(I=!0,P):pe==="?"?G?G+pe+(ie?_.repeat(ie.length):""):Oe===0?T+(ie?_.repeat(ie.length):""):_.repeat(ne.length):pe==="."?f.repeat(ne.length):pe==="*"?G?G+pe+(ie?M:""):M:G?P:`\\${P}`);return I===!0&&(t.unescape===!0?Z=Z.replace(/\\/g,""):Z=Z.replace(/\\+/g,P=>P.length%2===0?"\\\\":P?"\\":"")),Z===n&&t.contains===!0?(k.output=n,k):(k.output=Ce.wrapOutput(Z,k,e),k)}for(;!Y();){if(E=X(),E==="\0")continue;if(E==="\\"){let P=D();if(P==="/"&&t.bash!==!0||P==="."||P===";")continue;if(!P){E+="\\",q({type:"text",value:E});continue}let G=/^\\+/.exec(ee()),ne=0;if(G&&G[0].length>2&&(ne=G[0].length,k.index+=ne,ne%2!==0&&(E+="\\")),t.unescape===!0?E=X():E+=X(),k.brackets===0){q({type:"text",value:E});continue}}if(k.brackets>0&&(E!=="]"||C.value==="["||C.value==="[^")){if(t.posix!==!1&&E===":"){let P=C.value.slice(1);if(P.includes("[")&&(C.posix=!0,P.includes(":"))){let G=C.value.lastIndexOf("["),ne=C.value.slice(0,G),pe=C.value.slice(G+2),ie=zb[pe];if(ie){C.value=ne+ie,k.backtrack=!0,X(),!i.output&&o.indexOf(C)===1&&(i.output=p);continue}}}(E==="["&&D()!==":"||E==="-"&&D()==="]")&&(E=`\\${E}`),E==="]"&&(C.value==="["||C.value==="[^")&&(E=`\\${E}`),t.posix===!0&&E==="!"&&C.value==="["&&(E="^"),C.value+=E,_e({value:E});continue}if(k.quotes===1&&E!=='"'){E=Ce.escapeRegex(E),C.value+=E,_e({value:E});continue}if(E==='"'){k.quotes=k.quotes===1?0:1,t.keepQuotes===!0&&q({type:"text",value:E});continue}if(E==="("){Ae("parens"),q({type:"paren",value:E});continue}if(E===")"){if(k.parens===0&&t.strictBrackets===!0)throw new SyntaxError(vn("opening","("));let P=F[F.length-1];if(P&&k.parens===P.parens+1){Ge(F.pop());continue}q({type:"paren",value:E,output:k.parens?")":"\\)"}),ve("parens");continue}if(E==="["){if(t.nobracket===!0||!ee().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(vn("closing","]"));E=`\\${E}`}else Ae("brackets");q({type:"bracket",value:E});continue}if(E==="]"){if(t.nobracket===!0||C&&C.type==="bracket"&&C.value.length===1){q({type:"text",value:E,output:`\\${E}`});continue}if(k.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(vn("opening","["));q({type:"text",value:E,output:`\\${E}`});continue}ve("brackets");let P=C.value.slice(1);if(C.posix!==!0&&P[0]==="^"&&!P.includes("/")&&(E=`/${E}`),C.value+=E,_e({value:E}),t.literalBrackets===!1||Ce.hasRegexChars(P))continue;let G=Ce.escapeRegex(C.value);if(k.output=k.output.slice(0,-C.value.length),t.literalBrackets===!0){k.output+=G,C.value=G;continue}C.value=`(${a}${G}|${C.value})`,k.output+=C.value;continue}if(E==="{"&&t.nobrace!==!0){Ae("braces");let P={type:"brace",value:E,output:"(",outputIndex:k.output.length,tokensIndex:k.tokens.length};H.push(P),q(P);continue}if(E==="}"){let P=H[H.length-1];if(t.nobrace===!0||!P){q({type:"text",value:E,output:E});continue}let G=")";if(P.dots===!0){let ne=o.slice(),pe=[];for(let ie=ne.length-1;ie>=0&&(o.pop(),ne[ie].type!=="brace");ie--)ne[ie].type!=="dots"&&pe.unshift(ne[ie].value);G=Qb(pe,t),k.backtrack=!0}if(P.comma!==!0&&P.dots!==!0){let ne=k.output.slice(0,P.outputIndex),pe=k.tokens.slice(P.tokensIndex);P.value=P.output="\\{",E=G="\\}",k.output=ne;for(let ie of pe)k.output+=ie.output||ie.value}q({type:"brace",value:E,output:G}),ve("braces"),H.pop();continue}if(E==="|"){F.length>0&&F[F.length-1].conditions++,q({type:"text",value:E});continue}if(E===","){let P=E,G=H[H.length-1];G&&V[V.length-1]==="braces"&&(G.comma=!0,P="|"),q({type:"comma",value:E,output:P});continue}if(E==="/"){if(C.type==="dot"&&k.index===k.start+1){k.start=k.index+1,k.consumed="",k.output="",o.pop(),C=i;continue}q({type:"slash",value:E,output:m});continue}if(E==="."){if(k.braces>0&&C.type==="dot"){C.value==="."&&(C.output=f);let P=H[H.length-1];C.type="dots",C.output+=E,C.value+=E,P.dots=!0;continue}if(k.braces+k.parens===0&&C.type!=="bos"&&C.type!=="slash"){q({type:"text",value:E,output:f});continue}q({type:"dot",value:E,output:f});continue}if(E==="?"){if(!(C&&C.value==="(")&&t.noextglob!==!0&&D()==="("&&D(2)!=="?"){ue("qmark",E);continue}if(C&&C.type==="paren"){let G=D(),ne=E;if(G==="<"&&!Ce.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(C.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(ee()))&&(ne=`\\${E}`),q({type:"text",value:E,output:ne});continue}if(t.dot!==!0&&(C.type==="slash"||C.type==="bos")){q({type:"qmark",value:E,output:y});continue}q({type:"qmark",value:E,output:_});continue}if(E==="!"){if(t.noextglob!==!0&&D()==="("&&(D(2)!=="?"||!/[!=<:]/.test(D(3)))){ue("negate",E);continue}if(t.nonegate!==!0&&k.index===0){Q();continue}}if(E==="+"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){ue("plus",E);continue}if(C&&C.value==="("||t.regex===!1){q({type:"plus",value:E,output:h});continue}if(C&&(C.type==="bracket"||C.type==="paren"||C.type==="brace")||k.parens>0){q({type:"plus",value:E});continue}q({type:"plus",value:h});continue}if(E==="@"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){q({type:"at",extglob:!0,value:E,output:""});continue}q({type:"text",value:E});continue}if(E!=="*"){(E==="$"||E==="^")&&(E=`\\${E}`);let P=Yb.exec(ee());P&&(E+=P[0],k.index+=P[0].length),q({type:"text",value:E});continue}if(C&&(C.type==="globstar"||C.star===!0)){C.type="star",C.star=!0,C.value+=E,C.output=M,k.backtrack=!0,k.globstar=!0,te(E);continue}let I=ee();if(t.noextglob!==!0&&/^\([^?]/.test(I)){ue("star",E);continue}if(C.type==="star"){if(t.noglobstar===!0){te(E);continue}let P=C.prev,G=P.prev,ne=P.type==="slash"||P.type==="bos",pe=G&&(G.type==="star"||G.type==="globstar");if(t.bash===!0&&(!ne||I[0]&&I[0]!=="/")){q({type:"star",value:E,output:""});continue}let ie=k.braces>0&&(P.type==="comma"||P.type==="brace"),Oe=F.length&&(P.type==="pipe"||P.type==="paren");if(!ne&&P.type!=="paren"&&!ie&&!Oe){q({type:"star",value:E,output:""});continue}for(;I.slice(0,3)==="/**";){let We=n[k.index+4];if(We&&We!=="/")break;I=I.slice(3),te("/**",3)}if(P.type==="bos"&&Y()){C.type="globstar",C.value+=E,C.output=w(t),k.output=C.output,k.globstar=!0,te(E);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&!pe&&Y()){k.output=k.output.slice(0,-(P.output+C.output).length),P.output=`(?:${P.output}`,C.type="globstar",C.output=w(t)+(t.strictSlashes?")":"|$)"),C.value+=E,k.globstar=!0,k.output+=P.output+C.output,te(E);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&I[0]==="/"){let We=I[1]!==void 0?"|$":"";k.output=k.output.slice(0,-(P.output+C.output).length),P.output=`(?:${P.output}`,C.type="globstar",C.output=`${w(t)}${m}|${m}${We})`,C.value+=E,k.output+=P.output+C.output,k.globstar=!0,te(E+X()),q({type:"slash",value:"/",output:""});continue}if(P.type==="bos"&&I[0]==="/"){C.type="globstar",C.value+=E,C.output=`(?:^|${m}|${w(t)}${m})`,k.output=C.output,k.globstar=!0,te(E+X()),q({type:"slash",value:"/",output:""});continue}k.output=k.output.slice(0,-C.output.length),C.type="globstar",C.output=w(t),C.value+=E,k.output+=C.output,k.globstar=!0,te(E);continue}let Z={type:"star",value:E,output:M};if(t.bash===!0){Z.output=".*?",(C.type==="bos"||C.type==="slash")&&(Z.output=S+Z.output),q(Z);continue}if(C&&(C.type==="bracket"||C.type==="paren")&&t.regex===!0){Z.output=E,q(Z);continue}(k.index===k.start||C.type==="slash"||C.type==="dot")&&(C.type==="dot"?(k.output+=A,C.output+=A):t.dot===!0?(k.output+=$,C.output+=$):(k.output+=S,C.output+=S),D()!=="*"&&(k.output+=p,C.output+=p)),q(Z)}for(;k.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(vn("closing","]"));k.output=Ce.escapeLast(k.output,"["),ve("brackets")}for(;k.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(vn("closing",")"));k.output=Ce.escapeLast(k.output,"("),ve("parens")}for(;k.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(vn("closing","}"));k.output=Ce.escapeLast(k.output,"{"),ve("braces")}if(t.strictSlashes!==!0&&(C.type==="star"||C.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${m}?`}),k.backtrack===!0){k.output="";for(let I of k.tokens)k.output+=I.output!=null?I.output:I.value,I.suffix&&(k.output+=I.suffix)}return k};wo.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(Ws,t.maxLength):Ws,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=rd[n]||n;let i=Ce.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:u,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=Yn.globChars(i),g=t.dot?f:d,x=t.dot?h:d,A=t.capture?"":"?:",$={negated:!1,prefix:""},_=t.bash===!0?".*?":m;t.capture&&(_=`(${_})`);let y=S=>S.noglobstar===!0?_:`(${A}(?:(?!${p}${S.dot?u:o}).)*?)`,v=S=>{switch(S){case"*":return`${g}${l}${_}`;case".*":return`${o}${l}${_}`;case"*.*":return`${g}${_}${o}${l}${_}`;case"*/*":return`${g}${_}${a}${l}${x}${_}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${x}${l}${_}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${x}${_}${o}${l}${_}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${_}`;default:{let T=/^(.*?)\.(\w+)$/.exec(S);if(!T)return;let M=v(T[1]);return M?M+o+T[2]:void 0}}},b=Ce.removePrefix(n,$),w=v(b);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};ad.exports=wo});var ud=j((mC,cd)=>{"use strict";var sv=require("path"),rv=sd(),xo=ld(),So=Gs(),iv=Vn(),ov=n=>n&&typeof n=="object"&&!Array.isArray(n),ge=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>ge(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=ov(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=So.isWindows(e),o=s?ge.compileRe(n,e):ge.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(r.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};l=ge(r.ignore,d,t)}let u=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=ge.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(g),h===!1?(g.isMatch=!1,f?g:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,f?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),f?g:!0)};return t&&(u.state=a),u};ge.test=(n,e,t,{glob:s,posix:r}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(r?So.toPosixSlashes:null),a=n===s,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===s),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=ge.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ge.matchBase=(n,e,t,s=So.isWindows(t))=>(e instanceof RegExp?e:ge.makeRe(e,t)).test(sv.basename(n));ge.isMatch=(n,e,t)=>ge(e,t)(n);ge.parse=(n,e)=>Array.isArray(n)?n.map(t=>ge.parse(t,e)):xo(n,{...e,fastpaths:!1});ge.scan=(n,e)=>rv(n,e);ge.compileRe=(n,e,t=!1,s=!1)=>{if(t===!0)return n.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=ge.toRegex(a,e);return s===!0&&(l.state=n),l};ge.makeRe=(n,e={},t=!1,s=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(r.output=xo.fastpaths(n,e)),r.output||(r=xo(n,e)),ge.compileRe(r,e,t,s)};ge.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ge.constants=iv;cd.exports=ge});var _o=j((gC,dd)=>{"use strict";dd.exports=ud()});var vd=j((yC,bd)=>{"use strict";var Qn=require("fs"),{Readable:av}=require("stream"),Jn=require("path"),{promisify:Js}=require("util"),Ao=_o(),lv=Js(Qn.readdir),cv=Js(Qn.stat),fd=Js(Qn.lstat),uv=Js(Qn.realpath),dv="!",gd="READDIRP_RECURSIVE_ERROR",fv=new Set(["ENOENT","EPERM","EACCES","ELOOP",gd]),ko="files",yd="directories",zs="files_directories",Vs="all",pd=[ko,yd,zs,Vs],pv=n=>fv.has(n.code),[hd,hv]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),mv=process.platform==="win32"&&(hd>10||hd===10&&hv>=5),md=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=Ao(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let s of n){let r=s.trim();r.charAt(0)===dv?t.push(Ao(r.slice(1))):e.push(Ao(r))}return t.length>0?e.length>0?s=>e.some(r=>r(s.basename))&&!t.some(r=>r(s.basename)):s=>!t.some(r=>r(s.basename)):s=>e.some(r=>r(s.basename))}}},Ys=class n extends av{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:ko,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...n.defaultOptions,...e},{root:s,type:r}=t;this._fileFilter=md(t.fileFilter),this._directoryFilter=md(t.directoryFilter);let i=t.lstat?fd:cv;mv?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[yd,zs,Vs].includes(r),this._wantsFile=[ko,zs,Vs].includes(r),this._wantsEverything=r===Vs,this._root=Jn.resolve(s),this._isDirent="Dirent"in Qn&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:s,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,s+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await lv(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;try{let r=this._isDirent?e.name:e,i=Jn.resolve(Jn.join(t,r));s={path:Jn.relative(this._root,i),fullPath:i,basename:r},s[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return s}_onError(e){pv(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let s=e.fullPath;try{let r=await uv(s),i=await fd(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Jn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=gd,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},wn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=zs),t&&(e.type=t),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!pd.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${pd.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new Ys(e)},gv=(n,e={})=>new Promise((t,s)=>{let r=[];wn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});wn.promise=gv;wn.ReaddirpStream=Ys;wn.default=wn;bd.exports=wn});var $o=j((bC,wd)=>{wd.exports=function(n,e){if(typeof n!="string")throw new TypeError("expected path to be a string");if(n==="\\"||n==="/")return"/";var t=n.length;if(t<=1)return n;var s="";if(t>4&&n[3]==="\\"){var r=n[2];(r==="?"||r===".")&&n.slice(0,2)==="\\\\"&&(n=n.slice(2),s="//")}var i=n.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),s+i.join("/")}});var $d=j((Ad,kd)=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var _d=_o(),yv=$o(),xd="!",bv={returnIndex:!1},vv=n=>Array.isArray(n)?n:[n],wv=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=_d(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},Sd=(n,e,t,s)=>{let r=Array.isArray(t),i=r?t[0]:t;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=yv(i,!1);for(let l=0;l<e.length;l++){let u=e[l];if(u(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let u=n[l];if(r?u(...a):u(o))return s?l:!0}return s?-1:!1},Eo=(n,e,t=bv)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=vv(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===xd).map(l=>l.slice(1)).map(l=>_d(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==xd).map(l=>wv(l,s));return e==null?(l,u=!1)=>Sd(a,o,l,typeof u=="boolean"?u:!1):Sd(a,o,e,r)};Eo.default=Eo;kd.exports=Eo});var Cd=j((vC,Ed)=>{Ed.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var Co=j((wC,Rd)=>{var xv=Cd(),Td={"{":"}","(":")","[":"]"},Sv=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,s=-2,r=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||s!==-1&&n[e]==="["&&n[e+1]!=="]"&&(s<e&&(s=n.indexOf("]",e)),s>e&&(o===-1||o>s||(o=n.indexOf("\\",e),o===-1||o>s)))||r!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(r=n.indexOf("}",e),r>e&&(o=n.indexOf("\\",e),o===-1||o>r))||i!==-1&&n[e]==="("&&n[e+1]==="?"&&/[:!=]/.test(n[e+2])&&n[e+3]!==")"&&(i=n.indexOf(")",e),i>e&&(o=n.indexOf("\\",e),o===-1||o>i))||t!==-1&&n[e]==="("&&n[e+1]!=="|"&&(t<e&&(t=n.indexOf("|",e)),t!==-1&&n[t+1]!==")"&&(i=n.indexOf(")",t),i>t&&(o=n.indexOf("\\",t),o===-1||o>i))))return!0;if(n[e]==="\\"){var a=n[e+1];e+=2;var l=Td[a];if(l){var u=n.indexOf(l,e);u!==-1&&(e=u+1)}if(n[e]==="!")return!0}else e++}return!1},_v=function(n){if(n[0]==="!")return!0;for(var e=0;e<n.length;){if(/[*?{}()[\]]/.test(n[e]))return!0;if(n[e]==="\\"){var t=n[e+1];e+=2;var s=Td[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Rd.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(xv(e))return!0;var s=Sv;return t&&t.strict===!1&&(s=_v),s(e)}});var Pd=j((xC,Od)=>{"use strict";var Av=Co(),kv=require("path").posix.dirname,$v=require("os").platform()==="win32",To="/",Ev=/\\/g,Cv=/[\{\[].*[\}\]]$/,Tv=/(^|[^\\])([\{\[]|\([^\)]+$)/,Rv=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Od.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&$v&&e.indexOf(To)<0&&(e=e.replace(Ev,To)),Cv.test(e)&&(e+=To),e+="a";do e=kv(e);while(Av(e)||Tv.test(e));return e.replace(Rv,"$1")}});var Qs=j(Ye=>{"use strict";Ye.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;Ye.find=(n,e)=>n.nodes.find(t=>t.type===e);Ye.exceedsLimit=(n,e,t=1,s)=>s===!1||!Ye.isInteger(n)||!Ye.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;Ye.escapeNode=(n,e=0,t)=>{let s=n.nodes[e];s&&(t&&s.type===t||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};Ye.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;Ye.isInvalidBrace=n=>n.type!=="brace"?!1:n.invalid===!0||n.dollar?!0:n.commas>>0+n.ranges>>0===0||n.open!==!0||n.close!==!0?(n.invalid=!0,!0):!1;Ye.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;Ye.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Ye.flatten=(...n)=>{let e=[],t=s=>{for(let r=0;r<s.length;r++){let i=s[r];if(Array.isArray(i)){t(i);continue}i!==void 0&&e.push(i)}return e};return t(n),e}});var Xs=j((_C,Md)=>{"use strict";var Id=Qs();Md.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Id.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Id.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let l of s.nodes)a+=t(l);return a};return t(n)}});var Dd=j((AC,Ld)=>{"use strict";Ld.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var Gd=j((kC,Kd)=>{"use strict";var Nd=Dd(),Yt=(n,e,t)=>{if(Nd(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(Nd(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...t};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let r=String(s.relaxZeros),i=String(s.shorthand),o=String(s.capture),a=String(s.wrap),l=n+":"+e+"="+r+i+o+a;if(Yt.cache.hasOwnProperty(l))return Yt.cache[l].result;let u=Math.min(n,e),d=Math.max(n,e);if(Math.abs(u-d)===1){let g=n+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let f=qd(n)||qd(e),h={min:n,max:e,a:u,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),u<0){let g=d<0?Math.abs(d):1;p=Fd(g,Math.abs(u),h,s),u=h.a=0}return d>=0&&(m=Fd(u,d,h,s)),h.negatives=p,h.positives=m,h.result=Ov(p,m,s),s.capture===!0?h.result=`(${h.result})`:s.wrap!==!1&&m.length+p.length>1&&(h.result=`(?:${h.result})`),Yt.cache[l]=h,h.result};function Ov(n,e,t){let s=Ro(n,e,"-",!1,t)||[],r=Ro(e,n,"",!1,t)||[],i=Ro(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function Pv(n,e){let t=1,s=1,r=Hd(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=Hd(n,t);for(r=Bd(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=Bd(e+1,s)-1;return i=[...i],i.sort(Lv),i}function Iv(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=Mv(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,u]=s[a];l===u?i+=l:l!=="0"||u!=="9"?i+=Dv(l,u,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function Fd(n,e,t,s){let r=Pv(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let u=r[l],d=Iv(String(o),String(u),s),f="";if(!t.isPadded&&a&&a.pattern===d.pattern){a.count.length>1&&a.count.pop(),a.count.push(d.count[0]),a.string=a.pattern+Ud(a.count),o=u+1;continue}t.isPadded&&(f=Nv(u,t,s)),d.string=f+d.pattern+Ud(d.count),i.push(d),o=u+1,a=d}return i}function Ro(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!jd(e,"string",a)&&i.push(t+a),s&&jd(e,"string",a)&&i.push(t+a)}return i}function Mv(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function Lv(n,e){return n>e?1:e>n?-1:0}function jd(n,e,t){return n.some(s=>s[e]===t)}function Hd(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function Bd(n,e){return n-n%Math.pow(10,e)}function Ud(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function Dv(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function qd(n){return/^-?(0+)\d/.test(n)}function Nv(n,e,t){if(!e.isPadded)return n;let s=Math.abs(e.maxLen-String(n).length),r=t.relaxZeros!==!1;switch(s){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:return r?`0{0,${s}}`:`0{${s}}`}}Yt.cache={};Yt.clearCache=()=>Yt.cache={};Kd.exports=Yt});var Io=j(($C,Xd)=>{"use strict";var Fv=require("util"),Vd=Gd(),Wd=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),jv=n=>e=>n===!0?Number(e):String(e),Oo=n=>typeof n=="number"||typeof n=="string"&&n!=="",Xn=n=>Number.isInteger(+n),Po=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},Hv=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,Bv=(n,e,t)=>{if(e>0){let s=n[0]==="-"?"-":"";s&&(n=n.slice(1)),n=s+n.padStart(s?e-1:e,"0")}return t===!1?String(n):n},er=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},Uv=(n,e,t)=>{n.negatives.sort((a,l)=>a<l?-1:a>l?1:0),n.positives.sort((a,l)=>a<l?-1:a>l?1:0);let s=e.capture?"":"?:",r="",i="",o;return n.positives.length&&(r=n.positives.map(a=>er(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>er(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},zd=(n,e,t,s)=>{if(t)return Vd(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},Yd=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return Vd(n,e,t)},Jd=(...n)=>new RangeError("Invalid range arguments: "+Fv.inspect(...n)),Qd=(n,e,t)=>{if(t.strictRanges===!0)throw Jd([n,e]);return[]},qv=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},Kv=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw Jd([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),u=String(t);t=Math.max(Math.abs(t),1);let d=Po(a)||Po(l)||Po(u),f=d?Math.max(a.length,l.length,u.length):0,h=d===!1&&Hv(n,e,s)===!1,m=s.transform||jv(h);if(s.toRegex&&t===1)return zd(er(n,f),er(e,f),!0,s);let p={negatives:[],positives:[]},g=$=>p[$<0?"negatives":"positives"].push(Math.abs($)),x=[],A=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):x.push(Bv(m(r,A),f,h)),r=o?r-t:r+t,A++;return s.toRegex===!0?t>1?Uv(p,s,f):Yd(x,null,{wrap:!1,...s}):x},Gv=(n,e,t=1,s={})=>{if(!Xn(n)&&n.length>1||!Xn(e)&&e.length>1)return Qd(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),u=Math.max(i,o);if(s.toRegex&&t===1)return zd(l,u,!1,s);let d=[],f=0;for(;a?i>=o:i<=o;)d.push(r(i,f)),i=a?i-t:i+t,f++;return s.toRegex===!0?Yd(d,null,{wrap:!1,options:s}):d},Zs=(n,e,t,s={})=>{if(e==null&&Oo(n))return[n];if(!Oo(n)||!Oo(e))return Qd(n,e,s);if(typeof t=="function")return Zs(n,e,1,{transform:t});if(Wd(t))return Zs(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,Xn(t)?Xn(n)&&Xn(e)?Kv(n,e,t,r):Gv(n,e,Math.max(Math.abs(t),1),r):t!=null&&!Wd(t)?qv(t,r):Zs(n,e,1,t)};Xd.exports=Zs});var tf=j((EC,ef)=>{"use strict";var Wv=Io(),Zd=Qs(),Vv=(n,e={})=>{let t=(s,r={})=>{let i=Zd.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",u="";if(s.isOpen===!0)return l+s.value;if(s.isClose===!0)return console.log("node.isClose",l,s.value),l+s.value;if(s.type==="open")return a?l+s.value:"(";if(s.type==="close")return a?l+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let d=Zd.reduce(s.nodes),f=Wv(...d,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return d.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let d of s.nodes)u+=t(d,s);return u};return t(n)};ef.exports=Vv});var rf=j((CC,sf)=>{"use strict";var zv=Io(),nf=Xs(),xn=Qs(),Jt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?xn.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Jt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Jt(r,i,t):r+i);return xn.flatten(s)},Yv=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Jt(a.pop(),nf(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Jt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=xn.reduce(r.nodes);if(xn.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=zv(...f,e);h.length===0&&(h=nf(r,e)),a.push(Jt(a.pop(),h)),r.nodes=[];return}let l=xn.encloseBrace(r),u=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,u=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&u.push(""),u.push("");continue}if(h.type==="close"){a.push(Jt(a.pop(),u,l));continue}if(h.value&&h.type!=="open"){u.push(Jt(u.pop(),h.value));continue}h.nodes&&s(h,r)}return u};return xn.flatten(s(n))};sf.exports=Yv});var af=j((TC,of)=>{"use strict";of.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
325
|
-
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var ff=j((RC,df)=>{"use strict";var Jv=Xs(),{MAX_LENGTH:lf,CHAR_BACKSLASH:Mo,CHAR_BACKTICK:Qv,CHAR_COMMA:Xv,CHAR_DOT:Zv,CHAR_LEFT_PARENTHESES:ew,CHAR_RIGHT_PARENTHESES:tw,CHAR_LEFT_CURLY_BRACE:nw,CHAR_RIGHT_CURLY_BRACE:sw,CHAR_LEFT_SQUARE_BRACKET:cf,CHAR_RIGHT_SQUARE_BRACKET:uf,CHAR_DOUBLE_QUOTE:rw,CHAR_SINGLE_QUOTE:iw,CHAR_NO_BREAK_SPACE:ow,CHAR_ZERO_WIDTH_NOBREAK_SPACE:aw}=af(),lw=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min(lf,t.maxLength):lf;if(n.length>s)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${s})`);let r={type:"root",input:n,nodes:[]},i=[r],o=r,a=r,l=0,u=n.length,d=0,f=0,h,m=()=>n[d++],p=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(p({type:"bos"});d<u;)if(o=i[i.length-1],h=m(),!(h===aw||h===ow)){if(h===Mo){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===uf){p({type:"text",value:"\\"+h});continue}if(h===cf){l++;let g;for(;d<u&&(g=m());){if(h+=g,g===cf){l++;continue}if(g===Mo){h+=m();continue}if(g===uf&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===ew){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===tw){if(o.type!=="paren"){p({type:"text",value:h});continue}o=i.pop(),p({type:"text",value:h}),o=i[i.length-1];continue}if(h===rw||h===iw||h===Qv){let g=h,x;for(e.keepQuotes!==!0&&(h="");d<u&&(x=m());){if(x===Mo){h+=x+m();continue}if(x===g){e.keepQuotes===!0&&(h+=x);break}h+=x}p({type:"text",value:h});continue}if(h===nw){f++;let x={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=p(x),i.push(o),p({type:"open",value:h});continue}if(h===sw){if(o.type!=="brace"){p({type:"text",value:h});continue}let g="close";o=i.pop(),o.close=!0,p({type:g,value:h}),f--,o=i[i.length-1];continue}if(h===Xv&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:Jv(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===Zv&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let x=g[g.length-1];x.value+=a.value+h,a=x,o.ranges--;continue}p({type:"dot",value:h});continue}p({type:"text",value:h})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(A=>{A.nodes||(A.type==="open"&&(A.isOpen=!0),A.type==="close"&&(A.isClose=!0),A.nodes||(A.type="text"),A.invalid=!0)});let g=i[i.length-1],x=g.nodes.indexOf(o);g.nodes.splice(x,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};df.exports=lw});var mf=j((OC,hf)=>{"use strict";var pf=Xs(),cw=tf(),uw=rf(),dw=ff(),Ue=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=Ue.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(Ue.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.parse=(n,e={})=>dw(n,e);Ue.stringify=(n,e={})=>pf(typeof n=="string"?Ue.parse(n,e):n,e);Ue.compile=(n,e={})=>(typeof n=="string"&&(n=Ue.parse(n,e)),cw(n,e));Ue.expand=(n,e={})=>{typeof n=="string"&&(n=Ue.parse(n,e));let t=uw(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Ue.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?Ue.compile(n,e):Ue.expand(n,e);hf.exports=Ue});var gf=j((PC,fw)=>{fw.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var bf=j((IC,yf)=>{yf.exports=gf()});var wf=j((MC,vf)=>{"use strict";var pw=require("path"),hw=bf(),mw=new Set(hw);vf.exports=n=>mw.has(pw.extname(n).slice(1).toLowerCase())});var tr=j(U=>{"use strict";var{sep:gw}=require("path"),{platform:Lo}=process,yw=require("os");U.EV_ALL="all";U.EV_READY="ready";U.EV_ADD="add";U.EV_CHANGE="change";U.EV_ADD_DIR="addDir";U.EV_UNLINK="unlink";U.EV_UNLINK_DIR="unlinkDir";U.EV_RAW="raw";U.EV_ERROR="error";U.STR_DATA="data";U.STR_END="end";U.STR_CLOSE="close";U.FSEVENT_CREATED="created";U.FSEVENT_MODIFIED="modified";U.FSEVENT_DELETED="deleted";U.FSEVENT_MOVED="moved";U.FSEVENT_CLONED="cloned";U.FSEVENT_UNKNOWN="unknown";U.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;U.FSEVENT_TYPE_FILE="file";U.FSEVENT_TYPE_DIRECTORY="directory";U.FSEVENT_TYPE_SYMLINK="symlink";U.KEY_LISTENERS="listeners";U.KEY_ERR="errHandlers";U.KEY_RAW="rawEmitters";U.HANDLER_KEYS=[U.KEY_LISTENERS,U.KEY_ERR,U.KEY_RAW];U.DOT_SLASH=`.${gw}`;U.BACK_SLASH_RE=/\\/g;U.DOUBLE_SLASH_RE=/\/\//;U.SLASH_OR_BACK_SLASH_RE=/[/\\]/;U.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;U.REPLACER_RE=/^\.[/\\]/;U.SLASH="/";U.SLASH_SLASH="//";U.BRACE_START="{";U.BANG="!";U.ONE_DOT=".";U.TWO_DOTS="..";U.STAR="*";U.GLOBSTAR="**";U.ROOT_GLOBSTAR="/**/*";U.SLASH_GLOBSTAR="/**";U.DIR_SUFFIX="Dir";U.ANYMATCH_OPTS={dot:!0};U.STRING_TYPE="string";U.FUNCTION_TYPE="function";U.EMPTY_STR="";U.EMPTY_FN=()=>{};U.IDENTITY_FN=n=>n;U.isWindows=Lo==="win32";U.isMacos=Lo==="darwin";U.isLinux=Lo==="linux";U.isIBMi=yw.type()==="OS400"});var $f=j((DC,kf)=>{"use strict";var Rt=require("fs"),xe=require("path"),{promisify:ns}=require("util"),bw=wf(),{isWindows:vw,isLinux:ww,EMPTY_FN:xw,EMPTY_STR:Sw,KEY_LISTENERS:Sn,KEY_ERR:Do,KEY_RAW:Zn,HANDLER_KEYS:_w,EV_CHANGE:sr,EV_ADD:nr,EV_ADD_DIR:Aw,EV_ERROR:Sf,STR_DATA:kw,STR_END:$w,BRACE_START:Ew,STAR:Cw}=tr(),Tw="watch",Rw=ns(Rt.open),_f=ns(Rt.stat),Ow=ns(Rt.lstat),Pw=ns(Rt.close),No=ns(Rt.realpath),Iw={lstat:Ow,stat:_f},jo=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},es=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},Mw=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},ts=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},Af=n=>n instanceof Set?n.size===0:!n,rr=new Map;function xf(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&ir(xe.resolve(n,a),Sn,xe.join(n,a))};try{return Rt.watch(n,e,i)}catch(o){s(o)}}var ir=(n,e,t,s,r)=>{let i=rr.get(n);i&&jo(i[e],o=>{o(t,s,r)})},Lw=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=rr.get(e),l;if(!t.persistent)return l=xf(n,t,r,i,o),l.close.bind(l);if(a)es(a,Sn,r),es(a,Do,i),es(a,Zn,o);else{if(l=xf(n,t,ir.bind(null,e,Sn),i,ir.bind(null,e,Zn)),!l)return;l.on(Sf,async u=>{let d=ir.bind(null,e,Do);if(a.watcherUnusable=!0,vw&&u.code==="EPERM")try{let f=await Rw(n,"r");await Pw(f),d(u)}catch{}else d(u)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},rr.set(e,a)}return()=>{ts(a,Sn,r),ts(a,Do,i),ts(a,Zn,o),Af(a.listeners)&&(a.watcher.close(),rr.delete(e),_w.forEach(Mw(a)),a.watcher=void 0,Object.freeze(a))}},Fo=new Map,Dw=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=Fo.get(e),a=new Set,l=new Set,u=o&&o.options;return u&&(u.persistent<t.persistent||u.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,Rt.unwatchFile(e),o=void 0),o?(es(o,Sn,r),es(o,Zn,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:Rt.watchFile(e,t,(d,f)=>{jo(o.rawEmitters,m=>{m(sr,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&jo(o.listeners,m=>m(n,d))})},Fo.set(e,o)),()=>{ts(o,Sn,r),ts(o,Zn,i),Af(o.listeners)&&(Fo.delete(e),Rt.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},Ho=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=xe.dirname(e),i=xe.basename(e);this.fsw._getWatchedDir(r).add(i);let a=xe.resolve(e),l={persistent:s.persistent};t||(t=xw);let u;return s.usePolling?(l.interval=s.enableBinaryInterval&&bw(i)?s.binaryInterval:s.interval,u=Dw(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):u=Lw(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),u}_handleFile(e,t,s){if(this.fsw.closed)return;let r=xe.dirname(e),i=xe.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Tw,e,5)){if(!f||f.mtimeMs===0)try{let h=await _f(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(sr,e,h),ww&&a.ino!==h.ino?(this.fsw._closeFile(d),a=h,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=h}catch{this.fsw._remove(r,i)}else if(o.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(sr,e,f),a=f}}},u=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(nr,e,0))return;this.fsw._emit(nr,e,t)}return u}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await No(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(sr,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(nr,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){if(e=xe.join(e,Sw),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),u=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(kw,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=xe.join(e,h);if(u.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=xe.join(i,xe.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(Sf,this._boundHandleError);return new Promise(f=>d.once($w,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!u.has(m)&&(!s.hasGlob||s.filterPath({fullPath:xe.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(xe.dirname(e)),u=l.has(xe.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!u&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Aw,e,t),l.add(xe.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await Iw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let u=this.fsw.options.followSymlinks&&!e.includes(Cw)&&!e.includes(Ew),d;if(l.isDirectory()){let f=xe.resolve(e),h=u?await No(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=u?await No(e):e;if(this.fsw.closed)return;let h=xe.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(nr,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(xe.resolve(e),f)}else d=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};kf.exports=Ho});var If=j((NC,zo)=>{"use strict";var Wo=require("fs"),Se=require("path"),{promisify:Vo}=require("util"),_n;try{_n=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(_n){let n=process.version.match(/v(\d+)\.(\d+)/);if(n&&n[1]&&n[2]){let e=Number.parseInt(n[1],10),t=Number.parseInt(n[2],10);e===8&&t<16&&(_n=void 0)}}var{EV_ADD:Bo,EV_CHANGE:Nw,EV_ADD_DIR:Ef,EV_UNLINK:or,EV_ERROR:Fw,STR_DATA:jw,STR_END:Hw,FSEVENT_CREATED:Bw,FSEVENT_MODIFIED:Uw,FSEVENT_DELETED:qw,FSEVENT_MOVED:Kw,FSEVENT_UNKNOWN:Gw,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:Ww,FSEVENT_TYPE_FILE:Vw,FSEVENT_TYPE_DIRECTORY:ss,FSEVENT_TYPE_SYMLINK:Pf,ROOT_GLOBSTAR:Cf,DIR_SUFFIX:zw,DOT_SLASH:Tf,FUNCTION_TYPE:Uo,EMPTY_FN:Yw,IDENTITY_FN:Jw}=tr(),Qw=n=>isNaN(n)?{}:{depth:n},Ko=Vo(Wo.stat),Xw=Vo(Wo.lstat),Rf=Vo(Wo.realpath),Zw={stat:Ko,lstat:Xw},Qt=new Map,ex=10,tx=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),nx=(n,e)=>({stop:_n.watch(n,e)});function sx(n,e,t,s){let r=Se.extname(e)?Se.dirname(e):e,i=Se.dirname(r),o=Qt.get(r);rx(i)&&(r=i);let a=Se.resolve(n),l=a!==e,u=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+Se.sep))&&t(f,h,m)},d=!1;for(let f of Qt.keys())if(e.indexOf(Se.resolve(f)+Se.sep)===0){r=f,o=Qt.get(r),d=!0;break}return o||d?o.listeners.add(u):(o={listeners:new Set([u]),rawEmitter:s,watcher:nx(r,(f,h)=>{if(!o.listeners.size||h&Ww)return;let m=_n.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},Qt.set(r,o)),()=>{let f=o.listeners;if(f.delete(u),!f.size&&(Qt.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var rx=n=>{let e=0;for(let t of Qt.keys())if(t.indexOf(n)===0&&(e++,e>=ex))return!0;return!1},ix=()=>_n&&Qt.size<128,qo=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=Se.dirname(n))!==e;)t++;return t},Of=(n,e)=>n.type===ss&&e.isDirectory()||n.type===Pf&&e.isSymbolicLink()||n.type===Vw&&e.isFile(),Go=class{constructor(e){this.fsw=e}checkIgnored(e,t){let s=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return s.add(e),t&&t.isDirectory()&&s.add(e+Cf),!0;s.delete(e),s.delete(e+Cf)}addOrChange(e,t,s,r,i,o,a,l){let u=i.has(o)?Nw:Bo;this.handleEvent(u,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let u=await Ko(e);if(this.fsw.closed)return;Of(a,u)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(or,e,t,s,r,i,o,a,l)}catch(u){u.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(or,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,u){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===or){let d=l.type===ss;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===Bo){if(l.type===ss&&this.fsw._getWatchedDir(t),l.type===Pf&&u.followSymlinks){let f=u.depth===void 0?void 0:qo(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===ss?e+zw:e;this.fsw._emit(d,t),d===Ef&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,s,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=sx(e,t,async(l,u,d)=>{if(this.fsw.closed||i.depth!==void 0&&qo(l,t)>i.depth)return;let f=s(Se.join(e,Se.relative(e,l)));if(r&&!r(f))return;let h=Se.dirname(f),m=Se.basename(f),p=this.fsw._getWatchedDir(d.type===ss?f:h);if(tx.has(u)||d.event===Gw)if(typeof i.ignored===Uo){let g;try{g=await Ko(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;Of(d,g)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(or,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case Bw:case Uw:return this.addOrChange(f,l,t,h,p,m,d,i);case qw:case Kw:return this.checkExists(f,l,t,h,p,m,d,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,s,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await Rf(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==Tf?a=o.replace(i,e):o!==Tf&&(a=Se.join(e,o)),s(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,s,r,i){let o=s(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(Se.dirname(o)),u=Se.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(u)&&(l.add(u),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?Ef:Bo,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,Se.resolve(e||s.watchPath),r,s.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,s,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===Uo?t:Jw,a=this.fsw._getWatchHelpers(e);try{let l=await Zw[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,s),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:u=>a.filterPath(u),directoryFilter:u=>a.filterDir(u),...Qw(i.depth-(r||0))}).on(jw,u=>{if(this.fsw.closed||u.stats.isDirectory()&&!a.filterPath(u))return;let d=Se.join(a.watchPath,u.path),{fullPath:f}=u;if(a.followSymlinks&&u.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:qo(d,Se.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,u.stats,o,i,s)}).on(Fw,Yw).on(Hw,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,s),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&s!==!0)if(typeof t===Uo)this.initWatch(void 0,e,a,o);else{let l;try{l=await Rf(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};zo.exports=Go;zo.exports.canUse=ix});var Kf=j(ca=>{"use strict";var{EventEmitter:ox}=require("events"),aa=require("fs"),se=require("path"),{promisify:Hf}=require("util"),ax=vd(),ea=$d().default,lx=Pd(),Yo=Co(),cx=mf(),ux=$o(),dx=$f(),Mf=If(),{EV_ALL:Jo,EV_READY:fx,EV_ADD:ar,EV_CHANGE:rs,EV_UNLINK:Lf,EV_ADD_DIR:px,EV_UNLINK_DIR:hx,EV_RAW:mx,EV_ERROR:Qo,STR_CLOSE:gx,STR_END:yx,BACK_SLASH_RE:bx,DOUBLE_SLASH_RE:Df,SLASH_OR_BACK_SLASH_RE:vx,DOT_RE:wx,REPLACER_RE:xx,SLASH:Xo,SLASH_SLASH:Sx,BRACE_START:_x,BANG:ta,ONE_DOT:Bf,TWO_DOTS:Ax,GLOBSTAR:kx,SLASH_GLOBSTAR:Zo,ANYMATCH_OPTS:na,STRING_TYPE:la,FUNCTION_TYPE:$x,EMPTY_STR:sa,EMPTY_FN:Ex,isWindows:Cx,isMacos:Tx,isIBMi:Rx}=tr(),Ox=Hf(aa.stat),Px=Hf(aa.readdir),ra=(n=[])=>Array.isArray(n)?n:[n],Uf=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?Uf(t,e):e.push(t)}),e),Nf=n=>{let e=Uf(ra(n));if(!e.every(t=>typeof t===la))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(qf)},Ff=n=>{let e=n.replace(bx,Xo),t=!1;for(e.startsWith(Sx)&&(t=!0);e.match(Df);)e=e.replace(Df,Xo);return t&&(e=Xo+e),e},qf=n=>Ff(se.normalize(Ff(n))),jf=(n=sa)=>e=>typeof e!==la?e:qf(se.isAbsolute(e)?e:se.join(n,e)),Ix=(n,e)=>se.isAbsolute(n)?n:n.startsWith(ta)?ta+se.join(e,n.slice(1)):se.join(e,n),it=(n,e)=>n[e]===void 0,ia=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Bf&&e!==Ax&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await Px(s)}catch{this._removeWatcher&&this._removeWatcher(se.dirname(s),se.basename(s))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},Mx="stat",Lx="lstat",oa=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(xx,sa),this.watchPath=t,this.fullWatchPath=se.resolve(t),this.hasGlob=t!==e,e===sa&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?ea(e,void 0,na):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?Mx:Lx}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return se.join(this.watchPath,se.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===$x?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(_x)?cx.expand(e):[e]).forEach(r=>{t.push(se.relative(this.watchPath,r).split(vx))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),s=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===kx&&(s=!0),s||!t[0][o]||ea(i,t[0][o],na))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},lr=class extends ox{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,it(t,"persistent")&&(t.persistent=!0),it(t,"ignoreInitial")&&(t.ignoreInitial=!1),it(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),it(t,"interval")&&(t.interval=100),it(t,"binaryInterval")&&(t.binaryInterval=300),it(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,it(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Mf.canUse()||(t.useFsEvents=!1),it(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Tx),Rx&&(t.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let l=r.toLowerCase();l==="false"||l==="0"?t.usePolling=!1:l==="true"||l==="1"?t.usePolling=!0:t.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(t.interval=Number.parseInt(i,10)),it(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),it(t,"followSymlinks")&&(t.followSymlinks=!0),it(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=ra(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Ex,this._readyEmitted=!0,process.nextTick(()=>this.emit(fx)))},this._emitRaw=(...l)=>this.emit(mx,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Mf(this):this._nodeFsHandler=new dx(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=Nf(e);return r&&(o=o.map(a=>{let l=Ix(a,r);return i||!Yo(a)?l:ux(l)})),o=o.filter(a=>a.startsWith(ta)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+Zo),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let l=await this._nodeFsHandler._addToNodeFs(a,!s,0,0,t);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(se.dirname(l),se.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=Nf(e),{cwd:s}=this.options;return t.forEach(r=>{!se.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=se.join(s,r)),r=se.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+Zo),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(s=>{let r=s();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,s)=>{let r=this.options.cwd?se.relative(this.options.cwd,s):s;e[r||Bf]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==Qo&&this.emit(Jo,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;Cx&&(t=se.normalize(t)),o.cwd&&(t=se.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(s,r,i):r!==void 0?a.push(s,r):s!==void 0&&a.push(s);let l=o.awaitWriteFinish,u;if(l&&(u=this._pendingWrites.get(t)))return u.lastChange=new Date,this;if(o.atomic){if(e===Lf)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(Jo,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===ar&&this._pendingUnlinks.has(t)&&(e=a[0]=rs,this._pendingUnlinks.delete(t))}if(l&&(e===ar||e===rs)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=Qo,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===rs&&!this._throttle(rs,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===ar||e===px||e===rs)){let d=o.cwd?se.join(o.cwd,t):t,f;try{f=await Ox(d)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(Qo,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let u=r.get(t),d=u?u.count:0;return r.delete(t),clearTimeout(o),u&&clearTimeout(u.timeoutObject),d};o=setTimeout(a,s);let l={timeoutObject:o,clear:a,count:0};return r.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i,o=e;this.options.cwd&&!se.isAbsolute(e)&&(o=se.join(this.options.cwd,e));let a=new Date,l=u=>{aa.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);u&&f.size!==u.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&wx.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(jf(s)),o=ra(i).filter(l=>typeof l===la&&!Yo(l)).map(l=>l+Zo),a=this._getGlobIgnored().map(jf(s)).concat(i,o);this._userIgnored=ea(a,void 0,na)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!Yo(e)?e:lx(e),r=this.options.followSymlinks;return new oa(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=se.resolve(e);return this._watched.has(t)||this._watched.set(t,new ia(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let s=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(s.toString(8)[0],10))}_remove(e,t,s){let r=se.join(e,t),i=se.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),u=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=se.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===ar)return;this._watched.delete(r),this._watched.delete(i);let f=s?hx:Lf;u&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=se.dirname(e);this._getWatchedDir(t).remove(se.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:Jo,alwaysStat:!0,lstat:!0,...t},r=ax(e,s);return this._streams.add(r),r.once(gx,()=>{r=void 0}),r.once(yx,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};ca.FSWatcher=lr;var Dx=(n,e)=>{let t=new lr(e);return t.add(n),t};ca.watch=Dx});var zf={};Ne(zf,{CollaborationManager:()=>is,addTeamMember:()=>jx,formatTeamConfig:()=>Hx,initTeamConfig:()=>Fx,loadTeamConfig:()=>Nx,saveTeamConfig:()=>Vf});function Nx(n){let e=Je.join(n,".hablas","team.json");if(ye.existsSync(e))try{return JSON.parse(ye.readFileSync(e,"utf-8"))}catch{return null}return null}function Fx(n,e){let t={name:e,members:[]};return Vf(n,t),t}function Vf(n,e){let t=Je.join(n,".hablas","team.json"),s=Je.dirname(t);ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function jx(n,e,t){return n.members.push({name:e,email:t}),n}function Hx(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
|
|
326
|
-
|
|
327
|
-
${c.muted("[Debug] Project Context:")} ${c.highlight(i)}`),this.projectTeamToken=Gf.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${c.muted("[Debug] Session Fingerprint:")} ${c.muted(this.projectTeamToken.slice(0,16))}...
|
|
328
|
-
`),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${c.warning("\u26A0")} ${c.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Je.dirname(this.localStatePath);return ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0}),this.saveLocalState([],[]),this.startLoops(),this.startWatcher(),this.registerCleanups(),!0}async shutdown(){this.shuttingDown||(this.shuttingDown=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.syncInterval&&(clearTimeout(this.syncInterval),this.syncInterval=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.signalHandler&&(process.off("SIGINT",this.signalHandler),process.off("SIGTERM",this.signalHandler),this.signalHandler=null),await this.releaseAllMyLocks(),await this.deleteSession())}async apiRequest(e,t,s,r){if(!this.isConfigured)return{ok:!1,data:null};let i=`${this.supabaseUrl}/rest/v1/${e}`,o={apikey:this.supabaseKey,Authorization:`Bearer ${this.supabaseKey}`,"Content-Type":"application/json"};r?.prefer?o.Prefer=r.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(r?.retries??0)+1,l=null;for(let u=0;u<a;u++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&u<a-1){await this.delay(400*(u+1));continue}return{ok:!1,data:null}}let f=await d.text();return{ok:!0,data:f?JSON.parse(f):null}}catch(d){if(l=d,u<a-1){await this.delay(400*(u+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let s={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},r="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(r,"POST",s,{prefer:"resolution=merge-duplicates,return=minimal",retries:2});return i}async fetchSessions(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async deleteSession(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}&developer_name=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async fetchLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async acquireLock(e,t){let s={project_team_token:this.projectTeamToken,file_path:e,locked_by:this.username,lock_context:t||"editing file",created_at:new Date().toISOString()};return await this.apiRequest("hablas_team_locks?on_conflict=project_team_token,file_path","POST",s,{prefer:"resolution=ignore-duplicates,return=minimal",retries:1}),!!(await this.fetchLocks()).find(a=>a.file_path===e&&a.locked_by===this.username)}async releaseLock(e){let t=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&file_path=eq.${encodeURIComponent(e)}&locked_by=eq.${encodeURIComponent(this.username)}`;return await this.apiRequest(t,"DELETE"),!0}async releaseAllMyLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&locked_by=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async sendMessage(e,t){let s={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:r}=await this.apiRequest("hablas_team_messages","POST",s,{retries:1});return r}async fetchUnreadMessages(){let e=`hablas_team_messages?project_team_token=eq.${this.projectTeamToken}&receiver_name=eq.${encodeURIComponent(this.username)}&is_read=eq.false`,t=(await this.apiRequest(e,"GET")).data||[];if(t.length>0)for(let s of t){let r=`hablas_team_messages?id=eq.${s.id}`;await this.apiRequest(r,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let s={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};ye.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(ye.existsSync(this.localStatePath))try{return JSON.parse(ye.readFileSync(this.localStatePath,"utf-8"))}catch{}return{sessions:[],locks:[],my_username:this.username}}startLoops(){this.beat("idle","standby"),this.heartbeatInterval=setInterval(()=>{this.beat()},n.HEARTBEAT_MS);let e=t=>{this.syncInterval=setTimeout(async()=>{if(this.shuttingDown)return;await this.syncWithCloud()?this.idlePollTicks=0:this.idlePollTicks++;let r=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(r)},t)};e(n.POLL_ACTIVE_MS)}setActivity(e,t="working"){this.currentActivity={section:t,task:e.slice(0,120)},this.beat(t,this.currentActivity.task)}async beat(e,t){await this.sendHeartbeat(e??this.currentActivity.section,t??this.currentActivity.task)?(this.announcedOffline&&(console.log(`
|
|
329
|
-
${c.success("\u2713")} ${c.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
|
|
330
|
-
`),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
|
|
331
|
-
${c.warning("\u26A0")} ${c.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
|
|
332
|
-
`),this.announcedOffline=!0))}async syncWithCloud(){let e=await this.apiRequest(`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,"GET");if(!e.ok)return!1;let t=e.data||[],s=await this.fetchLocks(),r=await this.fetchUnreadMessages();for(let u of r)this.renderMessageBox(u.sender_name,u.message_content);let i=Date.now(),o=t.filter(u=>{if(u.developer_name===this.username)return!0;let d=new Date(u.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(u=>u.developer_name).sort())!==JSON.stringify(o.map(u=>u.developer_name).sort())||JSON.stringify(a.locks?.map(u=>`${u.file_path}:${u.locked_by}`).sort())!==JSON.stringify(s.map(u=>`${u.file_path}:${u.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=Wf.default.watch(this.localStatePath,{ignoreInitial:!1,persistent:!0}),this.watcher.on("change",()=>{let e=this.getLocalState();this.processStateChanges(e.sessions,e.locks)})}processStateChanges(e,t){let s=new Set;for(let i of e)if(i.developer_name!==this.username)if(s.add(i.developer_name),!this.knownSessions.has(i.developer_name))this.knownSessions.set(i.developer_name,i.current_task||"none"),console.log(`
|
|
333
|
-
${c.success("\u{1F514}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i.developer_name}`)} has joined the session.
|
|
334
|
-
`);else{let o=this.knownSessions.get(i.developer_name);i.current_task&&i.current_task!==o&&i.current_task!=="none"&&(this.knownSessions.set(i.developer_name,i.current_task),console.log(` ${c.accent("\u27F3")} ${c.muted("[Activity]")} ${c.strong(`@${i.developer_name}`)} is now: "${c.secondary(i.current_task)}"
|
|
335
|
-
`))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
|
|
336
|
-
${c.warning("\u{1F44B}")} ${c.muted("[Live Sync]")} ${c.strong(`@${i}`)} has left the session.
|
|
337
|
-
`));let r=new Set;for(let i of t)r.add(i.file_path),this.knownLocks.has(i.file_path)||(this.knownLocks.set(i.file_path,i.locked_by),i.locked_by!==this.username&&console.log(` ${c.error("\u{1F512}")} ${c.muted("[File Locked]")} ${c.strong(`@${i.locked_by}`)} locked ${c.highlight(i.file_path)}`));for(let i of this.knownLocks.keys())if(!r.has(i)){let o=this.knownLocks.get(i);this.knownLocks.delete(i),o!==this.username&&console.log(` ${c.success("\u{1F513}")} ${c.muted("[File Unlocked]")} ${c.strong(`@${o}`)} released lock on ${c.highlight(i)}`)}}renderMessageBox(e,t){let s=Math.min(process.stdout.columns-4,80),r=c.border("\u250C"+"\u2500".repeat(s-2)+"\u2510"),i=c.border("\u2514"+"\u2500".repeat(s-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((s-2-o.length)/2)),l=c.border("\u2502")+" ".repeat(a)+c.strong(o)+" ".repeat(s-2-o.length-a)+c.border("\u2502"),u=t.replace(/\n/g," "),d=Math.max(0,s-8-u.length),f=c.border("\u2502")+` "${c.secondary(u)}"`+" ".repeat(d)+c.border("\u2502");console.log(`
|
|
338
|
-
`+r),console.log(l),console.log(f),console.log(i+`
|
|
339
|
-
`)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Je.join(this.workingDir,".env");if(ye.existsSync(e))try{let s=ye.readFileSync(e,"utf-8").split(`
|
|
340
|
-
`);for(let r of s){let i=r.split("=");if(i.length>=2){let o=i[0].trim(),a=i.slice(1).join("=").trim().replace(/^['"]|['"]$/g,"");o==="SUPABASE_URL"||o==="VITE_SUPABASE_URL"?this.supabaseUrl=a:(o==="SUPABASE_KEY"||o==="SUPABASE_ANON_KEY"||o==="VITE_SUPABASE_ANON_KEY")&&(this.supabaseKey=a)}}}catch{}if(!this.supabaseUrl||!this.supabaseKey){let t="aHR0cHM6Ly93dXVtYXptcGp6dHZ4a3l3Y3Rvci5zdXBhYmFzZS5jbw==",s="c2JfcHVibGlzaGFibGVfVmxmNEtCUzdsaTRjaGFWNE04d19xQV9fbnJuczh1WQ==";this.supabaseUrl=Buffer.from(t,"base64").toString("utf-8"),this.supabaseKey=Buffer.from(s,"base64").toString("utf-8")}this.isConfigured=!!(this.supabaseUrl&&this.supabaseKey),this.isConfigured&&this.syncLlmConfig()}syncLlmConfig(){let e=Je.join(cr.homedir(),".hablas","config.json");if(ye.existsSync(e))try{let t=JSON.parse(ye.readFileSync(e,"utf-8"));!this.config.apiUrl&&t.apiUrl&&(this.config.apiUrl=t.apiUrl,this.config.apiKey=t.apiKey,this.config.provider=t.provider)}catch{}}getProjectIdentifier(){let e="";try{let{execSync:t}=require("child_process"),s=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let r=s.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);r&&r[1]&&(e=r[1].toLowerCase())}}catch{}if(!e)try{let t=Je.join(this.workingDir,"package.json");if(ye.existsSync(t)){let s=JSON.parse(ye.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Je.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});async function Xt(n){try{if(!da.existsSync(n))return;da.existsSync(os)||await mt.mkdir(os,{recursive:!0});let e=await mt.readFile(n,"utf-8"),t=An.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=An.join(os,r);await mt.writeFile(i,e,"utf-8");let a=(await mt.readdir(os)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Yf)for(let l of a.slice(Yf))await mt.unlink(An.join(os,l))}catch{}}var mt,da,An,Jf,os,Yf,Qf=N(()=>{"use strict";mt=O(require("fs/promises")),da=O(require("fs")),An=O(require("path")),Jf=O(require("os")),os=An.join(Jf.homedir(),".hablas","backup"),Yf=10});function ep(n){let e=m=>jt.resolve(n,m);return[{name:"read_file",description:"Read the content of a file with line numbers. Returns up to 300 lines. Use start_line/end_line for large files.",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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[read_file]: path is required"};let p=e(m.path),x=(await ae.readFile(p,"utf-8")).split(`
|
|
341
|
-
`),A=x.length,$=m.start_line?Math.max(1,m.start_line):1,_=m.end_line?Math.min(A,m.end_line):Math.min(A,$+Xf-1),y=Math.min(_,$+Xf-1),v=x.slice($-1,y),b=String(y).length,w=v.map((M,k)=>`${String($+k).padStart(b," ")} | ${M}`),S=`[${m.path} \u2014 lines ${$}-${y} of ${A}]`,T=y<A?`
|
|
342
|
-
... [File has ${A} total lines. Use start_line/end_line to read more.]`:"";return{success:!0,output:`${S}
|
|
320
|
+
If you cannot complete a task, explain why with absolute technical objectivity.`;qi=Se.join(Wi.homedir(),".hablas","backup")});async function Ht(n){try{if(!Gi.existsSync(n))return;Gi.existsSync(Dn)||await ot.mkdir(Dn,{recursive:!0});let e=await ot.readFile(n,"utf-8"),t=ln.basename(n),s=Date.now(),r=`${t}.${s}.bak`,i=ln.join(Dn,r);await ot.writeFile(i,e,"utf-8");let a=(await ot.readdir(Dn)).filter(l=>l.startsWith(`${t}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>_u)for(let l of a.slice(_u))await ot.unlink(ln.join(Dn,l))}catch{}}var ot,Gi,ln,Au,Dn,_u,ku=N(()=>{"use strict";ot=O(require("fs/promises")),Gi=O(require("fs")),ln=O(require("path")),Au=O(require("os")),Dn=ln.join(Au.homedir(),".hablas","backup"),_u=10});function Cu(n){let e=m=>Rt.resolve(n,m);return[{name:"read_file",description:"Read the content of a file with line numbers. Returns up to 300 lines. Use start_line/end_line for large files.",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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[read_file]: path is required"};let p=e(m.path),_=(await se.readFile(p,"utf-8")).split(`
|
|
321
|
+
`),A=_.length,S=m.start_line?Math.max(1,m.start_line):1,k=m.end_line?Math.min(A,m.end_line):Math.min(A,S+$u-1),y=Math.min(k,S+$u-1),v=_.slice(S-1,y),b=String(y).length,w=v.map((L,$)=>`${String(S+$).padStart(b," ")} | ${L}`),x=`[${m.path} \u2014 lines ${S}-${y} of ${A}]`,T=y<A?`
|
|
322
|
+
... [File has ${A} total lines. Use start_line/end_line to read more.]`:"";return{success:!0,output:`${x}
|
|
343
323
|
${w.join(`
|
|
344
|
-
`)}${T}`}}catch(p){return{success:!1,output:"",error:`[read_file]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let p=e(m.path);return
|
|
345
|
-
${y}`}}catch(p){return{success:!1,output:"",error:`[edit_file]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!m.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!m.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(m.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let p=e(m.path),g=await
|
|
346
|
-
`),A=
|
|
324
|
+
`)}${T}`}}catch(p){return{success:!1,output:"",error:`[read_file]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let p=e(m.path);return Vi.existsSync(p)&&await Ht(p),await se.mkdir(Rt.dirname(p),{recursive:!0}),await se.writeFile(p,m.content,"utf-8"),{success:!0,output:`Written: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[write_file]: ${p.message}`}}}},{name:"edit_file",description:"Apply a surgical edit by replacing old content with new content. Must match exactly one location.",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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!m.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let p=e(m.path),g=await se.readFile(p,"utf-8"),_=m.old_content,A=m.new_content,S=Eu(g,_);if(S===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(S>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${S} locations in the file. Provide more surrounding context to be specific.`};await Ht(p);let k=g.replace(_,A);await se.writeFile(p,k,"utf-8");let y=Ts(m.path,g,k);return{success:!0,output:`Edited: ${m.path}
|
|
325
|
+
${y}`}}catch(p){return{success:!1,output:"",error:`[edit_file]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!m.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!m.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(m.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let p=e(m.path),g=await se.readFile(p,"utf-8"),_=g.split(`
|
|
326
|
+
`),A=_.length,S=m.start_line,k=m.end_line;if(S<1||S>A)return{success:!1,output:"",error:`[patch_file]: start_line ${S} is out of range (file has ${A} lines)`};if(k<S||k>A)return{success:!1,output:"",error:`[patch_file]: end_line ${k} is out of range (start_line=${S}, total=${A})`};await Ht(p);let y=_.slice(0,S-1),v=_.slice(k),b=m.new_content.split(`
|
|
347
327
|
`),w=[...y,...b,...v].join(`
|
|
348
|
-
`);await
|
|
349
|
-
${
|
|
350
|
-
`)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function
|
|
351
|
-
`,l.isDirectory()){let h=e+(
|
|
328
|
+
`);await se.writeFile(p,w,"utf-8");let x=Ts(m.path,g,w),T=k-S+1,L=b.length;return{success:!0,output:`Patched: ${m.path} (replaced ${T} lines with ${L})
|
|
329
|
+
${x}`}}catch(p){return{success:!1,output:"",error:`[patch_file]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!m.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(m.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let p=e(m.path),g=await se.readFile(p,"utf-8"),_=m.search,A=m.replace,S=m.is_regex;await Ht(p);let k,y;if(S){let v=new RegExp(_,"g");y=(g.match(v)||[]).length,k=g.replace(v,A)}else y=Eu(g,_),k=g.split(_).join(A);return y===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await se.writeFile(p,k,"utf-8"),{success:!0,output:`Replaced ${y} occurrence(s) in ${m.path}`})}catch(p){return{success:!1,output:"",error:`[search_and_replace]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(m.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let p=e(m.path);return await se.mkdir(Rt.dirname(p),{recursive:!0}),Vi.existsSync(p)&&await Ht(p),await se.appendFile(p,m.content,"utf-8"),{success:!0,output:`Appended to: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[append_to_file]: ${p.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let p=e(m.path);return await Ht(p),await se.unlink(p),{success:!0,output:`Deleted: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[delete_file]: ${p.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 m=>{try{if(!m.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!m.to)return{success:!1,output:"",error:"[move_file]: to is required"};let p=e(m.from),g=e(m.to);return await se.mkdir(Rt.dirname(g),{recursive:!0}),await se.rename(p,g),{success:!0,output:`Moved: ${m.from} \u2192 ${m.to}`}}catch(p){return{success:!1,output:"",error:`[move_file]: ${p.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async m=>{try{if(!m.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let p=e(m.path);return await se.mkdir(p,{recursive:!0}),{success:!0,output:`Created directory: ${m.path}`}}catch(p){return{success:!1,output:"",error:`[create_dir]: ${p.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 m=>{try{let p=e(m.path||"."),g=m.depth||3;return{success:!0,output:await Tu(p,"",g,0)||"(empty directory)"}}catch(p){return{success:!1,output:"",error:`[list_dir]: ${p.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 m=>{try{if(!m.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let p=e(m.path),g=await se.stat(p);return{success:!0,output:[`Path: ${m.path}`,`Size: ${zy(g.size)}`,`Type: ${g.isDirectory()?"directory":"file"}`,`Modified: ${g.mtime.toISOString()}`,`Created: ${g.birthtime.toISOString()}`].join(`
|
|
330
|
+
`)}}catch(p){return{success:!1,output:"",error:`[get_file_info]: ${p.message}`}}}}]}function Eu(n,e){let t=0,s=0;for(;;){let r=n.indexOf(e,s);if(r===-1)break;t++,s=r+e.length}return t}async function Tu(n,e,t,s){if(s>=t)return"";let i=(await se.readdir(n,{withFileTypes:!0})).filter(a=>!Vy.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],c=a===i.length-1,d=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${d}${f} ${l.name}
|
|
331
|
+
`,l.isDirectory()){let h=e+(c?" ":"\u2502 ");o+=await Tu(Rt.join(n,l.name),h,t,s+1)}}return o}function zy(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}var se,Vi,Rt,$u,Vy,Ru=N(()=>{"use strict";se=O(require("fs/promises")),Vi=O(require("fs")),Rt=O(require("path"));Ki();ku();$u=300;Vy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"])});var Ou,Rs,Pu=N(()=>{"use strict";Ou=require("child_process"),Rs=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,t){let s=`bg_${this.nextId++}`,r=t?.timeout||this.config.defaultTimeout,i=(0,Ou.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...t?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
|
|
352
332
|
Error: ${a.message}`}),r>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
|
|
353
333
|
Process timed out after ${r}ms`)},r),this.processes.set(s,o),s}readOutput(e,t){let s=this.processes.get(e);if(!s)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let r=t?.type||"both",i="";return(r==="stdout"||r==="both")&&(i+=s.stdout),(r==="stderr"||r==="both")&&(i&&(i+=`
|
|
354
334
|
`),i+=s.stderr),t?.lastLines&&(i=i.split(`
|
|
355
335
|
`).slice(-t.lastLines).join(`
|
|
356
|
-
`)),{success:!0,output:i,status:s.status}}kill(e){let t=this.processes.get(e);if(!t)return!1;if(t.process.pid)try{process.kill(-t.process.pid,"SIGTERM")}catch{try{process.kill(t.process.pid,"SIGTERM")}catch{}}return t.status="killed",!0}killAll(){let e=0;for(let t of this.processes.keys())this.kill(t)&&e++;return e}listProcesses(){let e=[];for(let[t,s]of this.processes){let r=Date.now()-s.startTime,i=this.formatUptime(r);e.push({id:t,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}}});function
|
|
357
|
-
PID: ${
|
|
358
|
-
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let
|
|
336
|
+
`)),{success:!0,output:i,status:s.status}}kill(e){let t=this.processes.get(e);if(!t)return!1;if(t.process.pid)try{process.kill(-t.process.pid,"SIGTERM")}catch{try{process.kill(t.process.pid,"SIGTERM")}catch{}}return t.status="killed",!0}killAll(){let e=0;for(let t of this.processes.keys())this.kill(t)&&e++;return e}listProcesses(){let e=[];for(let[t,s]of this.processes){let r=Date.now()-s.startTime,i=this.formatUptime(r);e.push({id:t,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[t,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(t),e++);return e}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let s=Math.floor(t/60);return s<60?`${s}m ${t%60}s`:`${Math.floor(s/60)}h ${s%60}m`}}});function Iu(n){return zi||(zi=new Rs({workingDir:n})),zi}function Lu(n,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 t=>{let s=t.command,r=t.run_in_background===!0,i=t.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Yy,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(r){let l=Iu(n).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
|
|
337
|
+
PID: ${Iu(n).getProcess(l)?.pid}
|
|
338
|
+
Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,Mu.exec)(s,{cwd:n,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),d="",f="";c.stdout?.on("data",h=>{d+=h}),c.stderr?.on("data",h=>{f+=h}),c.on("close",h=>{l(h===0?{success:!0,output:d||"(no output)"}:{success:!1,output:d,error:f||`Exit code: ${h}`})}),c.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Mu,Yy,zi,Du=N(()=>{"use strict";Mu=require("child_process");Pu();Yy=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],zi=null});function Nu(n){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 t=e.query,s=Ot.resolve(n,e.path||"."),r=new RegExp(t,"gi"),i=[];if(await Fu(s,r,i,n),i.length===0)return{success:!0,output:`No matches found for: "${t}"`};let o=i.slice(0,50).join(`
|
|
359
339
|
`),a=i.length>50?`
|
|
360
|
-
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(t){return{success:!1,output:"",error:`Search failed: ${t.message}`}}}}}async function
|
|
361
|
-
`),
|
|
362
|
-
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function
|
|
363
|
-
`);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function
|
|
364
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&t.push({file:r,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&t.push({file:r,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&t.push({file:r,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&t.push({file:r,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function
|
|
365
|
-
`)}function
|
|
366
|
-
`);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],
|
|
367
|
-
`),"utf-8"),t.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function
|
|
368
|
-
|
|
369
|
-
Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:
|
|
340
|
+
... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(t){return{success:!1,output:"",error:`Search failed: ${t.message}`}}}}}async function Fu(n,e,t,s){let r=await Os.readdir(n,{withFileTypes:!0});for(let i of r){if(Jy.has(i.name)||i.name.startsWith("."))continue;let o=Ot.join(n,i.name);if(i.isDirectory())await Fu(o,e,t,s);else if(Qy.has(Ot.extname(i.name)))try{let l=(await Os.readFile(o,"utf-8")).split(`
|
|
341
|
+
`),c=Ot.relative(s,o);for(let d=0;d<l.length;d++)e.test(l[d])&&(t.push(`${c}:${d+1}: ${l[d].trim()}`),e.lastIndex=0)}catch{}}}var Os,Ot,Jy,Qy,Hu=N(()=>{"use strict";Os=O(require("fs/promises")),Ot=O(require("path")),Jy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Qy=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"])});function Xy(n){let e=[],t=Pt.join(n,"tsconfig.json");if(!Be.existsSync(t))return e;try{(0,Yi.execSync)("npx tsc --noEmit 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let r=s,o=(r.stdout||r.message||"").split(`
|
|
342
|
+
`);for(let a of o){let l=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);l&&e.push({file:l[1],line:parseInt(l[2],10),severity:l[3]==="error"?"error":"warning",message:l[4].trim(),source:"typescript"})}}return e}function Zy(n){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>Be.existsSync(Pt.join(n,s))))return e;try{(0,Yi.execSync)("npx eslint . --format json 2>&1",{cwd:n,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:Pt.relative(n,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
|
|
343
|
+
`);for(let a of o){let l=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);l&&e.push({file:"unknown",line:parseInt(l[1],10),severity:l[3]==="error"?"error":"warning",message:`${l[4]} (${l[5]})`,source:"eslint"})}}}return e}function eb(n,e,t){let s;try{s=Be.readFileSync(n,"utf-8")}catch{return}let r=Pt.relative(e,n),i=s.split(`
|
|
344
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&t.push({file:r,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&t.push({file:r,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&t.push({file:r,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&t.push({file:r,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function tb(n){let e=[],t=[".ts",".tsx",".js",".jsx"];function s(r,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=Be.readdirSync(r)}catch{return}for(let l of a){if(o.includes(l))continue;let c=Pt.join(r,l),d;try{d=Be.statSync(c)}catch{continue}d.isDirectory()?s(c,i+1):t.some(f=>l.endsWith(f))&&eb(c,n,e)}}return s(n),e.slice(0,20)}function nb(n){let e=[];e.push(...Xy(n)),e.push(...Zy(n)),e.push(...tb(n));let t={error:0,warning:1,info:2};return e.sort((s,r)=>t[s.severity]-t[r.severity]),e}function ju(n){if(n.length===0)return" \u2713 No bugs detected";let e=[],t=n.filter(i=>i.severity==="error").length,s=n.filter(i=>i.severity==="warning").length,r=n.filter(i=>i.severity==="info").length;e.push(` Found ${n.length} issue${n.length>1?"s":""}: ${t} errors, ${s} warnings, ${r} info`),e.push("");for(let i of n.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 n.length>15&&e.push(` ... and ${n.length-15} more`),e.join(`
|
|
345
|
+
`)}function sb(n,e){let t=[];for(let s of n)if(s.source==="pattern"&&s.message.includes("console.log")){let r=Pt.join(e,s.file);try{let o=Be.readFileSync(r,"utf-8").split(`
|
|
346
|
+
`);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],Be.writeFileSync(r,o.join(`
|
|
347
|
+
`),"utf-8"),t.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{t.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else t.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return t}function Bu(n){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 t=e.path||n,s=e.fix==="true"||e.fix===!0;try{let r=nb(t);if(s&&r.length>0){let o=sb(r,t).filter(l=>l.fixed).length;return{success:!0,output:`${ju(r)}
|
|
348
|
+
|
|
349
|
+
Auto-fixed: ${o}/${r.length} issues`}}return{success:!0,output:ju(r)}}catch(r){return{success:!1,output:"",error:`Bug detection failed: ${r instanceof Error?r.message:String(r)}`}}}}}var Yi,Be,Pt,Uu=N(()=>{"use strict";Yi=require("child_process"),Be=O(require("fs")),Pt=O(require("path"))});function ib(n){let e=n;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,`
|
|
370
350
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
371
351
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
372
352
|
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(t,s,r)=>`
|
|
373
353
|
${"#".repeat(parseInt(s))} ${r.replace(/<[^>]+>/g,"").trim()}
|
|
374
354
|
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(t,s,r)=>{let i=r.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${s})`:s}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(t,s)=>"\n```\n"+s.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(t,s)=>String.fromCharCode(parseInt(s))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
375
355
|
|
|
376
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
356
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function ob(n){let e=n.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let t=n.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return t?t[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function ab(n,e){let t=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,r,i=new Set;for(;(r=s.exec(n))!==null;){let o=r[1].trim(),a=r[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),t.push({text:a||o,url:o}))}}return t}async function Gu(n){let e=new AbortController,t=setTimeout(()=>e.abort(),qu);try{let s=await fetch(n,{signal:e.signal,headers:{"User-Agent":rb,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(t),!s.ok)return{html:"",finalUrl:s.url||n,status:s.status};let r=s.headers.get("content-type")||"";if(!r.includes("text/")&&!r.includes("application/xhtml")&&!r.includes("application/json"))return{html:`[Binary content: ${r}]`,finalUrl:s.url||n,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||n,status:s.status};let o=[],a=0;for(;a<Ku;){let{done:d,value:f}=await i.read();if(d)break;o.push(f),a+=f.length}if(a>=Ku)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(d=>l.decode(d,{stream:!0})).join("")+l.decode(),finalUrl:s.url||n,status:s.status}}catch(s){clearTimeout(t);let r=s instanceof Error?s:new Error(String(s));throw r.name==="AbortError"?new Error(`Timeout after ${qu/1e3}s`):r}}function Vu(){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 n=>{let e=n.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:t,finalUrl:s,status:r}=await Gu(e);if(!t||r>=400)return{success:!1,output:"",error:`HTTP ${r} \u2014 could not fetch ${e}`};let i=ob(t),o=ib(t);return o.length>Wu&&(o=o.slice(0,Wu)+`
|
|
377
357
|
|
|
378
358
|
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
379
|
-
`)}}catch(t){let s=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async n=>{let e=n.url,t=n.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:r,status:i}=await
|
|
359
|
+
`)}}catch(t){let s=t instanceof Error?t.message:String(t);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async n=>{let e=n.url,t=n.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:r,status:i}=await Gu(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=ab(s,r);if(t&&(o=o.filter(l=>l.url.toLowerCase().includes(t)||l.text.toLowerCase().includes(t))),o.length===0)return{success:!0,output:"No links found"+(t?` matching "${t}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
|
|
380
360
|
`);return{success:!0,output:`Found ${o.length} links:
|
|
381
361
|
|
|
382
|
-
${a}`}}catch(s){let r=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${r}`}}}}]}var
|
|
383
|
-
`)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var
|
|
362
|
+
${a}`}}catch(s){let r=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${r}`}}}}]}var Ku,qu,Wu,rb,zu=N(()=>{"use strict";Ku=2*1024*1024,qu=15e3,Wu=32e3,rb="HablasBot/2.0 (+https://hablas.dev)"});function cb(n){let e=cn.get(n.toLowerCase().trim());return e?Date.now()-e.timestamp>lb?(cn.delete(n.toLowerCase().trim()),null):e.results:null}function ub(n,e){if(cn.size>200){let t=cn.keys().next().value;t!==void 0&&cn.delete(t)}cn.set(n.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function db(n,e){let t=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!t)return null;try{let s=new URLSearchParams({q:n,count:String(Math.min(e,10))}),r=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":t},signal:AbortSignal.timeout(1e4)});return r.ok?((await r.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 fb(n,e){try{let t=new URLSearchParams({q:n}),s=await fetch(`https://html.duckduckgo.com/html/?${t}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let r=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(r))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),d=a[3].replace(/<[^>]+>/g,"").trim(),f=l.match(/uddg=([^&]+)/);if(f)try{l=decodeURIComponent(f[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:d,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(r))!==null&&i.length<e;){let d=a[1],f=a[2].replace(/<[^>]+>/g,"").trim();f&&f.length>5&&!c.has(d)&&!d.includes("duckduckgo.com")&&(c.add(d),i.push({title:f,url:d,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function pb(n,e=5){let t=cb(n);if(t)return t.slice(0,e);let s=[{name:"brave",fn:()=>db(n,e)},{name:"duckduckgo",fn:()=>fb(n,e)}];for(let r of s)try{let i=await r.fn();if(i&&i.length>0)return ub(n,i),i}catch{}return[]}function Yu(){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 n=>{let e=n.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let t=Math.min(Math.max(1,n.max_results||5),10);try{let s=await pb(e.trim(),t);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let r=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];r.push(`[${i+1}] ${o.title}`),r.push(` ${o.url}`),o.snippet&&r.push(` ${o.snippet}`),r.push("")}return{success:!0,output:r.join(`
|
|
363
|
+
`)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var lb,cn,Ju=N(()=>{"use strict";lb=3600*1e3,cn=new Map});function Zu(n){let e=n.toString("latin1"),t={},s=[],r=0,i=e.match(/\/Type\s*\/Page\b/g);r=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(t.title=jt(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(t.author=jt(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(t.subject=jt(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(t.creator=jt(c[1]));let d=/stream\r?\n([\s\S]*?)\r?\nendstream/g,f;for(;(f=d.exec(e))!==null;){let m=f[1],p=ed(m);p.trim()&&s.push(p);try{let g=require("zlib"),_=Buffer.from(m,"latin1"),A=g.inflateSync(_).toString("latin1"),S=ed(A);S.trim()&&!s.includes(S)&&s.push(S)}catch{}}return{text:s.join(`
|
|
384
364
|
`).replace(/\r\n/g,`
|
|
385
365
|
`).replace(/\n{3,}/g,`
|
|
386
366
|
|
|
387
|
-
`).trim(),pages:r,metadata:t}}function
|
|
388
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function
|
|
389
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function
|
|
367
|
+
`).trim(),pages:r,metadata:t}}function ed(n){let e=[],t=/\(([^)]*)\)\s*Tj/g,s;for(;(s=t.exec(n))!==null;)e.push(jt(s[1]));let r=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=r.exec(n))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(d=>jt(d.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(n))!==null;)e.push(jt(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
|
|
368
|
+
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function jt(n){return n.replace(/\\n/g,`
|
|
369
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(parseInt(t,8)))}function nd(n){let e=t=>td.resolve(n,t);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 t=>{let s=e(t.path);if(!xt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${t.path}`};let r=xt.statSync(s);if(r.size>Qu)return{success:!1,output:"",error:`File too large: ${(r.size/1024/1024).toFixed(1)}MB (max: ${Qu/1024/1024}MB)`};try{let i=xt.readFileSync(s),{text:o,pages:a,metadata:l}=Zu(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${t.path} (${a} pages)
|
|
390
370
|
|
|
391
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let
|
|
371
|
+
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>Xu&&(c=c.slice(0,Xu)+`
|
|
392
372
|
|
|
393
373
|
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${t.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(r.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
394
374
|
`)}
|
|
395
|
-
${
|
|
396
|
-
`)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var
|
|
375
|
+
${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async t=>{let s=e(t.path);if(!xt.existsSync(s))return{success:!1,output:"",error:`File not found: ${t.path}`};try{let r=xt.statSync(s),i=xt.readFileSync(s),{pages:o,metadata:a}=Zu(i);return{success:!0,output:[`File: ${t.path}`,`Size: ${(r.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: ${r.mtime.toISOString()}`].filter(Boolean).join(`
|
|
376
|
+
`)}}catch(r){return{success:!1,output:"",error:`Failed to read PDF metadata: ${r instanceof Error?r.message:String(r)}`}}}}]}var xt,td,Qu,Xu,sd=N(()=>{"use strict";xt=O(require("fs")),td=O(require("path")),Qu=50*1024*1024,Xu=4e4});function un(n){try{let{execSync:e}=require("child_process");return e(`which ${n} 2>/dev/null || where ${n} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}async function hb(n,e,t=cd){let s=id[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(id).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let r=ad.tmpdir(),i=ld.join(r,`hablas_exec_${Date.now()}${s.extension}`);try{Ps.writeFileSync(i,n,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let c=(0,od.exec)(o,{timeout:t,maxBuffer:5242880,cwd:r,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),d="",f="";c.stdout?.on("data",h=>{d+=h}),c.stderr?.on("data",h=>{f+=h}),c.on("close",h=>{let m=Date.now()-a;l({success:h===0,stdout:d.slice(0,rd),stderr:f.slice(0,rd/2),exitCode:h??1,duration:m,language:e})}),c.on("error",h=>{let m=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:m,language:e})})})}finally{try{Ps.unlinkSync(i)}catch{}}}function mb(n){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(n)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(n)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(n)?"bash":"javascript"}function ud(){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 n=>{let e=n.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let t=n.language?.toLowerCase()||mb(e),s=Math.min(Math.max(1e3,n.timeout||cd),3e4),r=await hb(e,t,s),i=[];return i.push(`Language: ${r.language} | Exit: ${r.exitCode} | Duration: ${r.duration}ms`),i.push(""),r.stdout&&(i.push("Output:"),i.push(r.stdout)),r.stderr&&(i.push(r.stdout?`
|
|
397
377
|
Errors/Warnings:`:"Errors:"),i.push(r.stderr)),!r.stdout&&!r.stderr&&i.push("(no output)"),{success:r.success,output:i.join(`
|
|
398
|
-
`),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var
|
|
378
|
+
`),error:r.success?void 0:r.stderr||`Exit code: ${r.exitCode}`}}}]}var od,Ps,ad,ld,cd,rd,id,dd=N(()=>{"use strict";od=require("child_process"),Ps=O(require("fs")),ad=O(require("os")),ld=O(require("path")),cd=1e4,rd=16e3;id={javascript:{extension:".js",command:n=>`node --no-warnings "${n}"`,available:()=>!0},typescript:{extension:".ts",command:n=>un("tsx")?`tsx "${n}"`:un("ts-node")?`ts-node --transpileOnly "${n}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${n}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:n=>un("python3")?`python3 "${n}"`:`python "${n}"`,available:()=>un("python3")||un("python")},bash:{extension:".sh",command:n=>`bash "${n}"`,available:()=>un("bash")}}});var Nn,fd=N(()=>{"use strict";Ru();Du();Hu();Uu();zu();Ju();sd();dd();Nn=class{tools=new Map;constructor(e,t){let s=Cu(e);for(let r of s)this.tools.set(r.name,r);this.tools.set("run_command",Lu(e,t)),this.tools.set("search_codebase",Nu(e)),this.tools.set("detect_bugs",Bu(e)),this.tools.set("web_search",Yu());for(let r of Vu())this.tools.set(r.name,r);for(let r of nd(e))this.tools.set(r.name,r);for(let r of ud())this.tools.set(r.name,r)}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 t=this.tools.get(e.name);return t?t.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let t={},s=[];for(let[r,i]of Object.entries(e.parameters))t[r]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(r);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:t,required:s}}}})}getToolDescriptions(){return this.getAll().map(t=>{let s=Object.entries(t.parameters).map(([r,i])=>` ${r}: ${i.type} \u2014 ${i.description}`).join(`
|
|
399
379
|
`);return`- ${t.name} [${t.safety}]: ${t.description}
|
|
400
380
|
${s}`}).join(`
|
|
401
381
|
|
|
402
|
-
`)}}});function
|
|
403
|
-
... [truncated to fit context budget]`}var
|
|
382
|
+
`)}}});function Ji(n){return Math.ceil(n.length/3.5)}function Fn(n,e){let t=Math.floor(e*3.5);return n.length<=t?n:n.slice(0,t)+`
|
|
383
|
+
... [truncated to fit context budget]`}var Qi=N(()=>{"use strict"});var pd,Bt,Xi=N(()=>{"use strict";pd=O(require("crypto"));Qi();Bt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,t,s){let r=this.computeHash(t),i=this.cache.get(e);if(i&&i.hash===r){i.lastUsed=Date.now(),i.accessCount++;return}let o=Ji(t),a=s?.importance??this.autoImportance(e,t);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:t,hash:r,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,t){let s=this.cache.get(e);return s?s.hash!==this.computeHash(t):!0}buildContext(e){let t=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),r=0,i=[];for(let o of s){if(r+o.tokenCount>t){if(o.importance>=7){let a=t-r;if(a>200){let l=Fn(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
404
384
|
${l}`),r+=a}}continue}i.push(`--- ${o.path} ---
|
|
405
385
|
${o.content}`),r+=o.tokenCount}return i.join(`
|
|
406
386
|
|
|
407
|
-
`)}buildAgentContext(e,t){let s=t||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(
|
|
408
|
-
${
|
|
387
|
+
`)}buildAgentContext(e,t){let s=t||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(d=>c.path.includes(d))).sort((c,d)=>this.computeScore(d)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>s)break;l.push(`--- ${c.path} ---
|
|
388
|
+
${c.content}`),a+=c.tokenCount}return l.join(`
|
|
409
389
|
|
|
410
|
-
`)}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,t)=>t.importance-e.importance)}evictToFit(e){let t=Array.from(this.cache.entries()).map(([r,i])=>({key:r,...i,score:this.computeScore(i)})).sort((r,i)=>r.score-i.score),s=0;for(let r of t){if(s>=e)break;r.importance>=9||(s+=r.tokenCount,this.usedTokens-=r.tokenCount,this.cache.delete(r.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let r=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-r/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,t){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let r=
|
|
390
|
+
`)}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,t)=>t.importance-e.importance)}evictToFit(e){let t=Array.from(this.cache.entries()).map(([r,i])=>({key:r,...i,score:this.computeScore(i)})).sort((r,i)=>r.score-i.score),s=0;for(let r of t){if(s>=e)break;r.importance>=9||(s+=r.tokenCount,this.usedTokens-=r.tokenCount,this.cache.delete(r.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let r=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-r/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,t){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let r=Ji(t);return r>2e3&&(s=Math.max(1,s-1)),r>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let t=[];return/\.(ts|tsx)$/.test(e)&&t.push("typescript"),/\.(js|jsx)$/.test(e)&&t.push("javascript"),/\.json$/.test(e)&&t.push("config"),/\.md$/.test(e)&&t.push("documentation"),/\.(css|scss|sass)$/.test(e)&&t.push("style"),/\.(test|spec)\./i.test(e)&&t.push("test"),/src\//.test(e)&&t.push("source"),t}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let t=this.accessHistory[this.accessHistory.length-1];if(t&&Date.now()-this.getGroupTime(t)<3e4){if(!t.includes(e)){t.push(e);for(let s of t)if(s!==e){let r=this.cache.get(s);r&&!r.relatedFiles.includes(e)&&r.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return pd.createHash("md5").update(e).digest("hex")}}});function Hn(){return`msg_${Date.now()}_${++gb}`}function dn(n){return Math.ceil(n.length/4)}var gb,Ut,Zi=N(()=>{"use strict";gb=0;Ut=class n{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,t=50,s=32e3){this.maxMessages=t,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let r=dn(e);this.messages.push({id:Hn(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]}),this.totalTokens=r}getSessionId(){return this.sessionId}addUserMessage(e,t){let s=Hn(),r=dn(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:t?.priority||"high",tokenEstimate:r,compressed:!1,tags:t?.tags||["user-input"]}),this.totalTokens+=r,this.trimIfNeeded(),s}addAssistantMessage(e,t,s){let r=Hn(),i=dn(e),o={id:r,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return t&&t.length>0&&(o.tool_calls=t,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),r}addToolMessage(e,t){let s=Hn(),r=dn(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:r,compressed:!1,tags:t?[`tool:${t}`]:["tool-result"]}),this.totalTokens+=r,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let t={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t.tool_calls=e.tool_calls),t})}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(t=>t.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 t=dn(e),s=this.messages.filter(r=>r.priority==="critical"&&r.role!=="system");this.messages=[{id:Hn(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:t,compressed:!1,tags:["system"]},...s],this.recalculateTokens()}takeSnapshot(e){let t={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(t),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),t.id}rollback(e){let t=this.snapshots.find(s=>s.id===e);return t?(this.messages=t.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,t){let s=this.messages.length,r=new n(t,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"?r.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&r.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:r}),r}mergeFork(e,t){let s=this.forks.get(e);if(!s)return!1;let r=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(t)this.addAssistantMessage(`[Agent @${e} result]: ${t}`,void 0,e);else if(r.length>0){let i=r.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 t=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(t))}getMessagesByTag(e){return this.messages.filter(t=>t.tags.includes(e))}getLastByRole(e,t=1){return this.messages.filter(s=>s.role===e).slice(-t)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(t=>t.role==="tool"&&!t.compressed&&t.tokenEstimate>200);for(let t of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(t)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let t=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of t.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let t=this.messages[0],s=this.messages.slice(1),r={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=r[a.priority]-r[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[t,...i],this.recalculateTokens()}}compressMessage(e){let t=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
|
|
411
391
|
...(compressed from `+t+" chars)":e.content=e.content.slice(0,400)+`
|
|
412
|
-
...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=
|
|
413
|
-
${
|
|
414
|
-
`);let t=` ${
|
|
415
|
-
`).filter(Boolean).slice(-
|
|
416
|
-
`),"utf-8")}catch{}}}});function
|
|
392
|
+
...(compressed from `+t+" chars)",e.compressed=!0,e.originalLength=t,e.tokenEstimate=dn(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,t)=>e+t.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 t=JSON.parse(e);if(!t.messages||!Array.isArray(t.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=t.sessionId||`session_${Date.now()}`,this.messages=t.messages,this.totalTokens=t.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(t.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 hd,Ue,Le,md,Is,eo,yb,bb,vb,Ms,gd=N(()=>{"use strict";hd=O(require("readline")),Ue=O(require("fs")),Le=O(require("path")),md=O(require("os"));rn();Is=Le.join(md.homedir(),".hablas","history"),eo=500,yb=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",".dockerfile",".xml",".svg",".sql"]),bb=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),vb=["read ","edit ","write ","delete ","open ","patch "],Ms=class{rl;history=[];workingDir;fileCache=[];fileCacheTime=0;constructor(e){this.workingDir=e||process.cwd(),this.loadHistory(),this.rl=this.createReadline()}createReadline(){return hd.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:this.history,historySize:eo,completer:e=>this.autocomplete(e)})}reinitialize(){this.loadHistory(),this.rl=this.createReadline()}async prompt(e){return new Promise(t=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{s.trim()&&(this.history.push(s.trim()),this.saveHistory()),t(s)})})}async confirm(e){let t=` ${u.warning("?")} ${e} ${u.muted("[Y/n]")} `;return(await this.prompt(t)).toLowerCase()!=="n"}async confirmDangerous(e){console.log(`
|
|
393
|
+
${u.error("\u26A0")} ${u.error(u.strong(e))}`),console.log(` ${u.muted('This action cannot be undone. Type "yes" to confirm.')}
|
|
394
|
+
`);let t=` ${u.error("\u2192")} `;return(await this.prompt(t)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){if(e.startsWith("/model ")||e.startsWith("/usemodel "))return[[],e];if(e.startsWith("/mindset ")){let r=["coder","planner","debugger","reviewer"],i=e.slice(9),o=r.filter(a=>a.startsWith(i)).map(a=>"/mindset "+a);return[o.length?o:r.map(a=>"/mindset "+a),e]}if(e.startsWith("/alias ")){let r=["/alias set","/alias del"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}if(e.startsWith("/plugins ")){let r=["/plugins enable","/plugins disable"],i=r.filter(o=>o.startsWith(e));return[i.length?i:r,e]}let s=Di.filter(r=>r.startsWith(e));return[s.length?s:Di,e]}for(let s of vb)if(e.toLowerCase().includes(s)){let r=e.split(s).pop()??"";if(r&&!r.includes(" "))try{let i=Le.dirname(r)||".",o=Le.basename(r),a=Le.resolve(this.workingDir,i),l=Ue.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(r))+Le.join(i,c));if(l.length)return[l,e]}catch{}}let t=e.match(/#([\w./-]*)$/);if(t){let s=t[1],r=this.getProjectFiles(),i=r.filter(a=>a.toLowerCase().startsWith(s.toLowerCase())).map(a=>e.slice(0,e.length-t[0].length)+"#"+a);return i.length>0?[i,e]:[r.slice(0,20).map(a=>e.slice(0,e.length-t[0].length)+"#"+a),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let t=[];return this.scanDir(this.workingDir,"",t,3),this.fileCache=t,this.fileCacheTime=e,t}scanDir(e,t,s,r,i=0){if(!(i>=r))try{let o=Ue.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||bb.has(a.name))continue;let l=t?`${t}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(Le.join(e,a.name),l,s,r,i+1);else{let c=Le.extname(a.name).toLowerCase();(yb.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{if(Ue.existsSync(Is)){let e=Ue.readFileSync(Is,"utf-8");this.history=e.split(`
|
|
395
|
+
`).filter(Boolean).slice(-eo)}}catch{}}saveHistory(){try{let e=Le.dirname(Is);Ue.existsSync(e)||Ue.mkdirSync(e,{recursive:!0});let t=this.history.slice(-eo);Ue.writeFileSync(Is,t.join(`
|
|
396
|
+
`),"utf-8")}catch{}}}});function Ke(n={}){let e={};if(Xe.existsSync(to))try{let s=Xe.readFileSync(to,"utf-8");e=JSON.parse(s)}catch{}let t={...An,...e,tools:{...An.tools,...e.tools||{}},ui:{...An.ui,...e.ui||{}}};if(process.env.HABLAS_API_URL&&(t.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(t.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom")&&(t.provider=s)}if(process.env.HABLAS_MODEL&&(t.model=process.env.HABLAS_MODEL),n.model&&(t.model=n.model),n.host&&(t.ollamaHost=n.host),n.project&&(t.workingDirectory=Kt.resolve(n.project)),n.provider){let s=n.provider;(s==="ollama"||s==="custom")&&(t.provider=s)}return n.apiUrl&&(t.apiUrl=n.apiUrl),n.apiKey&&(t.apiKey=n.apiKey),n.team&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.enabled=!0),n.user&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.user=n.user),n.teamKey&&(t.team||(t.team={enabled:!1,user:"",key:""}),t.team.key=n.teamKey),t.apiUrl&&t.provider==="ollama"&&(t.provider="custom"),t}function at(n){Xe.existsSync(fn)||Xe.mkdirSync(fn,{recursive:!0}),Xe.writeFileSync(to,JSON.stringify(n,null,2),"utf-8")}function bd(){let n=[fn,Kt.join(fn,"logs"),Kt.join(fn,"backup")];for(let e of n)Xe.existsSync(e)||Xe.mkdirSync(e,{recursive:!0})}var Xe,Kt,yd,fn,to,Ls=N(()=>{"use strict";Xe=O(require("fs")),Kt=O(require("path")),yd=O(require("os"));kn();fn=Kt.join(yd.homedir(),".hablas"),to=Kt.join(fn,"config.json")});var jn,no=N(()=>{"use strict";jn=class{mindsets=new Map;activeMindset="planner";history=[];lastActivatedAt=Date.now();listeners=[];register(e){this.mindsets.set(e.name,e)}get(e){return this.mindsets.get(e)}list(){return Array.from(this.mindsets.values())}listNames(){return Array.from(this.mindsets.keys())}getActive(){return this.mindsets.get(this.activeMindset)}getActiveName(){return this.activeMindset}setActive(e){if(!this.mindsets.has(e))return!1;if(this.activeMindset===e)return!0;let t=this.activeMindset;if(this.history.length>0){let s=this.history[this.history.length-1];s.duration=Date.now()-this.lastActivatedAt}this.activeMindset=e,this.lastActivatedAt=Date.now(),this.history.push({name:e,timestamp:Date.now()}),this.history.length>50&&(this.history=this.history.slice(-50));for(let s of this.listeners)try{s(t,e)}catch{}return!0}has(e){return this.mindsets.has(e)}getHistory(){return[...this.history]}getMostUsed(){let e={};for(let s of this.history)e[s.name]=(e[s.name]||0)+1;let t=Object.entries(e).sort((s,r)=>r[1]-s[1]);return t.length>0?t[0][0]:null}onChange(e){this.listeners.push(e)}createComposite(e,t,s){let r=this.mindsets.get(t),i=this.mindsets.get(s);if(!r||!i)return null;let o={name:e,description:`${r.description} + ${i.description}`,systemPrompt:r.systemPrompt+`
|
|
417
397
|
|
|
418
|
-
`+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var
|
|
398
|
+
`+i.systemPrompt,toolPreferences:[...new Set([...i.toolPreferences,...r.toolPreferences])],behaviorModifiers:{...r.behaviorModifiers,...i.behaviorModifiers}};return this.register(o),o}}});var so,ro=N(()=>{"use strict";so={name:"coder",description:"Expert coding assistant \u2014 direct file operations, precise edits, production-quality code",systemPrompt:`You are Alex, the Engineer on the Hablas multi-agent team. You are an expert full-stack developer.
|
|
419
399
|
|
|
420
400
|
## Your Strengths
|
|
421
401
|
- Writing clean, production-ready code with proper error handling
|
|
@@ -447,7 +427,7 @@ ${u.content}`),a+=u.tokenCount}return l.join(`
|
|
|
447
427
|
|
|
448
428
|
## Important
|
|
449
429
|
Never output tool calls as text or JSON in your response.
|
|
450
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var
|
|
430
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","patch_file","edit_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"concise",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py","*.go","*.rs","*.css","*.html"]}});var io,oo=N(()=>{"use strict";io={name:"planner",description:"Team Leader \u2014 strategic planning, task breakdown, coordination, decision-making",systemPrompt:`You are Hablas, the inspiring Team Leader of a multi-agent AI development system. You are a highly supportive, communicative, and exceptionally competent Engineering Lead.
|
|
451
431
|
You coordinate a team of specialized agents to help developers build and modify their codebase, and you love helping the developer succeed with high-quality engineering.
|
|
452
432
|
|
|
453
433
|
## Your Persona (Supportive, Empathetic & Expert Engineering Lead)
|
|
@@ -489,7 +469,7 @@ Then execute step by step.
|
|
|
489
469
|
|
|
490
470
|
## Important
|
|
491
471
|
Never output tool calls as text or JSON in your response.
|
|
492
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var
|
|
472
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!0,contextPriority:"all"}}});var ao,lo=N(()=>{"use strict";ao={name:"reviewer",description:"Code reviewer \u2014 quality audit, anti-patterns, security issues, performance bottlenecks",systemPrompt:`You are an expert code reviewer. You audit code quality and provide actionable feedback.
|
|
493
473
|
|
|
494
474
|
## Review Checklist
|
|
495
475
|
- Security vulnerabilities (injection, XSS, CSRF, auth bypass)
|
|
@@ -523,7 +503,7 @@ For each issue:
|
|
|
523
503
|
|
|
524
504
|
## Important
|
|
525
505
|
Never output tool calls as text or JSON in your response.
|
|
526
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var
|
|
506
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","search_codebase","list_dir","get_file_info"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!1,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.tsx","*.jsx","*.py"]}});var co,uo=N(()=>{"use strict";co={name:"debugger",description:"Bug hunter \u2014 traces errors, root cause analysis, targeted fixes, regression prevention",systemPrompt:`You are a systematic debugging expert. You find and fix bugs through methodical investigation.
|
|
527
507
|
|
|
528
508
|
## Debugging Process
|
|
529
509
|
1. **Reproduce**: Understand the symptom and error message
|
|
@@ -545,7 +525,7 @@ Always use the tool_calls field provided by the API.`,toolPreferences:["read_fil
|
|
|
545
525
|
## Important
|
|
546
526
|
Never output tool calls as text or JSON in your response.
|
|
547
527
|
Always use the tool_calls field provided by the API.
|
|
548
|
-
Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var
|
|
528
|
+
Focus on the ROOT CAUSE, not symptoms.`,toolPreferences:["read_file","search_codebase","run_command","patch_file","edit_file"],behaviorModifiers:{planFirst:!1,maxIterations:0,verbosity:"normal",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"code"},filePatterns:["*.ts","*.js","*.py","*.go","*.log","*.json"]}});var fo,po=N(()=>{"use strict";fo={name:"architect",description:"System architecture \u2014 schemas, APIs, project structure, scalability, ADRs",systemPrompt:`You are Bob, the System Architect on the Hablas multi-agent team.
|
|
549
529
|
Your role is to design robust, scalable, maintainable system architectures.
|
|
550
530
|
|
|
551
531
|
## Your Strengths
|
|
@@ -581,7 +561,7 @@ Your role is to design robust, scalable, maintainable system architectures.
|
|
|
581
561
|
|
|
582
562
|
## Important
|
|
583
563
|
Never output tool calls as text or JSON in your response.
|
|
584
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var
|
|
564
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","search_codebase"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"architecture"},filePatterns:["*.md","*.json","*.yaml","*.yml","*.toml","*.xml","schema*","config*"]}});var ho,mo=N(()=>{"use strict";ho={name:"devops",description:"DevOps \u2014 Docker, CI/CD, cloud, monitoring, deployment, infrastructure as code",systemPrompt:`You are a DevOps expert. You handle infrastructure, deployment, and operational concerns.
|
|
585
565
|
|
|
586
566
|
## Your Expertise
|
|
587
567
|
- Docker & container orchestration (Kubernetes, Docker Compose)
|
|
@@ -612,7 +592,7 @@ Always use the tool_calls field provided by the API.`,toolPreferences:["read_fil
|
|
|
612
592
|
|
|
613
593
|
## Important
|
|
614
594
|
Never output tool calls as text or JSON in your response.
|
|
615
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var
|
|
595
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["run_command","write_file","read_file","list_dir"],behaviorModifiers:{planFirst:!0,maxIterations:20,verbosity:"normal",autoConfirmSafe:!1,reasoning:"systematic",askWhenUncertain:!0,canDelegate:!1,contextPriority:"all"},filePatterns:["Dockerfile*","docker-compose*","*.yml","*.yaml",".github/*","Makefile","*.sh"]}});var go,yo=N(()=>{"use strict";go={name:"researcher",description:"Research & analysis \u2014 documentation, APIs, best practices, data analysis, benchmarks",systemPrompt:`You are David, the Data & Research Specialist on the Hablas multi-agent team.
|
|
616
596
|
Your role is to find information, analyze data, and provide well-researched context.
|
|
617
597
|
|
|
618
598
|
## Your Strengths
|
|
@@ -649,7 +629,7 @@ Your role is to find information, analyze data, and provide well-researched cont
|
|
|
649
629
|
|
|
650
630
|
## Important
|
|
651
631
|
Never output tool calls as text or JSON in your response.
|
|
652
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var
|
|
632
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["search_codebase","read_file","run_command","list_dir","web_search"],behaviorModifiers:{planFirst:!1,maxIterations:10,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"exploratory",askWhenUncertain:!0,canDelegate:!1,contextPriority:"data"},filePatterns:["*.md","*.txt","*.csv","*.json","*.sql","*.yml","*.yaml"]}});var bo,vo=N(()=>{"use strict";bo={name:"product-manager",description:"Product Manager \u2014 requirements, PRDs, user stories, market research, competitive analysis",systemPrompt:`You are Emma, the Product Manager on the Hablas multi-agent team.
|
|
653
633
|
Your role is to analyze needs, create detailed specs, and ensure the team builds the right thing.
|
|
654
634
|
|
|
655
635
|
## Your Strengths
|
|
@@ -684,7 +664,7 @@ Every PRD you create should include:
|
|
|
684
664
|
|
|
685
665
|
## Important
|
|
686
666
|
Never output tool calls as text or JSON in your response.
|
|
687
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var
|
|
667
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","write_file","search_codebase","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:15,verbosity:"verbose",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!0,contextPriority:"requirements"},filePatterns:["*.md","*.txt","*.json","package.json","README*"]}});var wo,xo=N(()=>{"use strict";wo={name:"sync",description:"Team Coordinator & Diplomatic Consul \u2014 handles lock negotiations, git sync, and team messaging",systemPrompt:`You are @Consul, the Software Diplomat on the Hablas multi-agent team.
|
|
688
668
|
Your absolute priority is to ensure smooth, conflict-free collaboration between human developers and machine agents.
|
|
689
669
|
|
|
690
670
|
## Your Personality (INTJ + Diplomatic Coordinator)
|
|
@@ -706,34 +686,33 @@ Your absolute priority is to ensure smooth, conflict-free collaboration between
|
|
|
706
686
|
|
|
707
687
|
## Important
|
|
708
688
|
Never output tool calls as text or JSON in your response.
|
|
709
|
-
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:10,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"requirements"}}});function
|
|
710
|
-
`)}}});var Le,yr,Wp,Vp,Tn,fs,zp=N(()=>{"use strict";Le=O(require("fs")),yr=O(require("path")),Wp=O(require("os")),Vp=O(require("crypto")),Tn=yr.join(Wp.homedir(),".hablas","memory"),fs=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=Vp.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=yr.join(Tn,`${this.projectHash}.json`),this.agentLanesPath=yr.join(Tn,`${this.projectHash}_agents.json`),this.load()}set(e,t,s){let r=this.entries.get(e),i=Date.now(),o=s?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:s?.importance??this.autoImportance(o,t),createdBy:s?.createdBy||"hablas",accessCount:r?.accessCount??0,useCount:r?.useCount??0,tags:s?.tags||this.autoTag(t,o),relatedFiles:s?.relatedFiles||this.extractFileRefs(t),createdAt:r?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:r?.consolidatedFrom}),this.save()}get(e){let t=this.entries.get(e);return t&&(t.accessCount++,t.lastAccessedAt=Date.now()),t?.value}getEntry(e){return this.entries.get(e)}markUsed(e){let t=this.entries.get(e);t&&(t.useCount++,t.importance=Math.min(10,t.importance+.5))}delete(e){let t=this.entries.delete(e);return t&&this.save(),t}setAgentMemory(e,t,s,r="agent-learning"){let i=this.agentLanes.get(e);i||(i=new Map,this.agentLanes.set(e,i));let o=Date.now(),a=i.get(t);i.set(t,{key:t,value:s,category:r,importance:this.autoImportance(r,s),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(s,r),relatedFiles:this.extractFileRefs(s),createdAt:a?.createdAt??o,updatedAt:o,lastAccessedAt:o}),this.saveAgentLanes()}getAgentMemories(e){let t=this.agentLanes.get(e);return t?Array.from(t.values()):[]}getAgentMemorySummary(e,t=10){let s=this.getAgentMemories(e),r=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...s,...r].sort((a,l)=>{let u=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-u}).slice(0,t);return i.length===0?"":`## Agent Memory
|
|
689
|
+
Always use the tool_calls field provided by the API.`,toolPreferences:["read_file","list_dir","write_file","patch_file","run_command"],behaviorModifiers:{planFirst:!0,maxIterations:10,verbosity:"concise",autoConfirmSafe:!0,reasoning:"analytical",askWhenUncertain:!0,canDelegate:!1,contextPriority:"requirements"}}});function Ds(){let n=new jn;return n.register(so),n.register(io),n.register(ao),n.register(co),n.register(fo),n.register(ho),n.register(go),n.register(bo),n.register(wo),n}var So=N(()=>{"use strict";no();ro();oo();lo();uo();po();mo();yo();vo();xo();no();ro();oo();lo();uo();po();mo();yo();vo();xo()});var Ce,Ns,vd,wd,pn,Bn,xd=N(()=>{"use strict";Ce=O(require("fs")),Ns=O(require("path")),vd=O(require("os")),wd=O(require("crypto")),pn=Ns.join(vd.homedir(),".hablas","memory"),Bn=class{entries=new Map;agentLanes=new Map;projectHash;filePath;agentLanesPath;constructor(e){this.projectHash=wd.createHash("md5").update(e).digest("hex").slice(0,12),this.filePath=Ns.join(pn,`${this.projectHash}.json`),this.agentLanesPath=Ns.join(pn,`${this.projectHash}_agents.json`),this.load()}set(e,t,s){let r=this.entries.get(e),i=Date.now(),o=s?.category||"note";this.entries.set(e,{key:e,value:t,category:o,importance:s?.importance??this.autoImportance(o,t),createdBy:s?.createdBy||"hablas",accessCount:r?.accessCount??0,useCount:r?.useCount??0,tags:s?.tags||this.autoTag(t,o),relatedFiles:s?.relatedFiles||this.extractFileRefs(t),createdAt:r?.createdAt??i,updatedAt:i,lastAccessedAt:i,consolidatedFrom:r?.consolidatedFrom}),this.save()}get(e){let t=this.entries.get(e);return t&&(t.accessCount++,t.lastAccessedAt=Date.now()),t?.value}getEntry(e){return this.entries.get(e)}markUsed(e){let t=this.entries.get(e);t&&(t.useCount++,t.importance=Math.min(10,t.importance+.5))}delete(e){let t=this.entries.delete(e);return t&&this.save(),t}setAgentMemory(e,t,s,r="agent-learning"){let i=this.agentLanes.get(e);i||(i=new Map,this.agentLanes.set(e,i));let o=Date.now(),a=i.get(t);i.set(t,{key:t,value:s,category:r,importance:this.autoImportance(r,s),createdBy:e,accessCount:a?.accessCount??0,useCount:a?.useCount??0,tags:this.autoTag(s,r),relatedFiles:this.extractFileRefs(s),createdAt:a?.createdAt??o,updatedAt:o,lastAccessedAt:o}),this.saveAgentLanes()}getAgentMemories(e){let t=this.agentLanes.get(e);return t?Array.from(t.values()):[]}getAgentMemorySummary(e,t=10){let s=this.getAgentMemories(e),r=this.getAll().filter(a=>a.importance>=5||a.useCount>=2),i=[...s,...r].sort((a,l)=>{let c=a.importance*(1+a.useCount*.3);return l.importance*(1+l.useCount*.3)-c}).slice(0,t);return i.length===0?"":`## Agent Memory
|
|
711
690
|
`+i.map(a=>`- [${a.category}${a.importance>=7?" \u2605":""}] ${a.key}: ${a.value}`).join(`
|
|
712
|
-
`)}search(e,t){let s=e.toLowerCase(),r=s.split(/\s+/).filter(l=>l.length>2),i=t?.maxResults||20,o=[],a=t?.agent?this.getAgentMemories(t.agent):this.getAll();for(let l of a){if(t?.category&&l.category!==t.category||t?.minImportance&&l.importance<t.minImportance)continue;let
|
|
713
|
-
`)}getStats(){let e=this.getAll(),t={},s={};for(let r of e)t[r.category]=(t[r.category]||0)+1,s[r.createdBy]=(s[r.createdBy]||0)+1;return{totalEntries:e.length,byCategory:t,byAgent:s,topAccessed:e.sort((r,i)=>i.accessCount-r.accessCount).slice(0,5),recentlyAdded:e.sort((r,i)=>i.createdAt-r.createdAt).slice(0,5),totalAccessCount:e.reduce((r,i)=>r+i.accessCount,0)}}consolidate(e=200){if(this.entries.size<=e)return 0;let t=Array.from(this.entries.values()).filter(o=>o.importance<4&&o.accessCount<3).sort((o,a)=>o.updatedAt-a.updatedAt),s=t.slice(0,Math.max(10,t.length-e)),r={};for(let o of s){let a=o.category;r[a]||(r[a]=[]),r[a].push(o)}let i=0;for(let[o,a]of Object.entries(r)){if(a.length<2)continue;let l=`[consolidated] ${o} (${a.length} items)`,
|
|
714
|
-
`)}autoImportance(e,t){let r={convention:6,decision:8,pattern:5,note:3,error:7,"tool-result":2,"user-pref":7,dependency:4,performance:5,security:9,api:6,"agent-learning":4}[e]||3;return/\b(important|critical|must|always|never|danger|warning|breaking)\b/i.test(t)&&(r=Math.min(10,r+2)),r}autoTag(e,t){let s=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&s.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&s.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&s.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&s.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&s.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&s.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&s.push("api"),s}extractFileRefs(e){let t=/[\w\-./]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|sql|sh|toml|xml|env)/gi,s=e.match(t);return s?[...new Set(s)]:[]}load(){try{if(
|
|
715
|
-
causes have become circular...`;let s=
|
|
716
|
-
caused by: `+Yp(s,e)):t},hS=n=>Yp(n,new Set),Jp=(n,e,t)=>{if(!ps(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=Ba(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+Jp(r,e,i)}else return s},mS=n=>Jp(n,new Set);Qp.exports={isErrorLike:ps,getErrorCause:Ba,stackWithCauses:hS,messageWithCauses:mS}});var qa=j((ZT,Zp)=>{"use strict";var gS=Symbol("circular-ref-tag"),br=Symbol("pino-raw-err-ref"),Xp=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[br]},set:function(n){this[br]=n}}});Object.defineProperty(Xp,br,{writable:!0,value:{}});Zp.exports={pinoErrProto:Xp,pinoErrorSymbols:{seen:gS,rawSymbol:br}}});var nh=j((eR,th)=>{"use strict";th.exports=Ga;var{messageWithCauses:yS,stackWithCauses:bS,isErrorLike:eh}=Ua(),{pinoErrProto:vS,pinoErrorSymbols:wS}=qa(),{seen:Ka}=wS,{toString:xS}=Object.prototype;function Ga(n){if(!eh(n))return n;n[Ka]=void 0;let e=Object.create(vS);e.type=xS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=yS(n),e.stack=bS(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Ga(t)));for(let t in n)if(e[t]===void 0){let s=n[t];eh(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ka)&&(e[t]=Ga(s)):e[t]=s}return delete n[Ka],e.raw=n,e}});var rh=j((tR,sh)=>{"use strict";sh.exports=wr;var{isErrorLike:Wa}=Ua(),{pinoErrProto:SS,pinoErrorSymbols:_S}=qa(),{seen:vr}=_S,{toString:AS}=Object.prototype;function wr(n){if(!Wa(n))return n;n[vr]=void 0;let e=Object.create(SS);e.type=AS.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=n.message,e.stack=n.stack,Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>wr(t))),Wa(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,vr)&&(e.cause=wr(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];Wa(s)?Object.prototype.hasOwnProperty.call(s,vr)||(e[t]=wr(s)):e[t]=s}return delete n[vr],e.raw=n,e}});var lh=j((nR,ah)=>{"use strict";ah.exports={mapHttpRequest:kS,reqSerializer:oh};var Va=Symbol("pino-raw-req-ref"),ih=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[Va]},set:function(n){this[Va]=n}}});Object.defineProperty(ih,Va,{writable:!0,value:{}});function oh(n){let e=n.info||n.socket,t=Object.create(ih);if(t.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),t.method=n.method,n.originalUrl)t.url=n.originalUrl;else{let s=n.path;t.url=typeof s=="string"?s:n.url?n.url.path||n.url:void 0}return n.query&&(t.query=n.query),n.params&&(t.params=n.params),t.headers=n.headers,t.remoteAddress=e&&e.remoteAddress,t.remotePort=e&&e.remotePort,t.raw=n.raw||n,t}function kS(n){return{req:oh(n)}}});var fh=j((sR,dh)=>{"use strict";dh.exports={mapHttpResponse:$S,resSerializer:uh};var za=Symbol("pino-raw-res-ref"),ch=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[za]},set:function(n){this[za]=n}}});Object.defineProperty(ch,za,{writable:!0,value:{}});function uh(n){let e=Object.create(ch);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function $S(n){return{res:uh(n)}}});var Ja=j((rR,ph)=>{"use strict";var Ya=nh(),ES=rh(),xr=lh(),Sr=fh();ph.exports={err:Ya,errWithCause:ES,mapHttpRequest:xr.mapHttpRequest,mapHttpResponse:Sr.mapHttpResponse,req:xr.reqSerializer,res:Sr.resSerializer,wrapErrorSerializer:function(e){return e===Ya?e:function(s){return e(Ya(s))}},wrapRequestSerializer:function(e){return e===xr.reqSerializer?e:function(s){return e(xr.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Sr.resSerializer?e:function(s){return e(Sr.resSerializer(s))}}}});var Qa=j((iR,hh)=>{"use strict";function CS(n,e){return e}hh.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=CS;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let s=t.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var wh=j((oR,vh)=>{"use strict";function Xa(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof Array){let e=[];for(let t=0;t<n.length;t++)e[t]=Xa(n[t]);return e}if(typeof n=="object"){let e=Object.create(Object.getPrototypeOf(n));for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=Xa(n[t]));return e}return n}function mh(n){let e=[],t="",s=!1,r=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!s&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),s=!0):a==="]"&&s?(e.push(t),t="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):t+=a:(r=!0,i=a):t+=a}return t&&e.push(t),e}function gh(n,e,t){let s=n;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]=t;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=t)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=t);return!0}function yh(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=void 0;else if(typeof t=="object"&&t!==null)for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&delete t[r]}else typeof t=="object"&&t!==null&&s in t&&Object.prototype.hasOwnProperty.call(t,s)&&delete t[s];return!0}var _r=Symbol("PATH_NOT_FOUND");function TS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return _r;t=t[s]}return t}function RS(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null)return;t=t[s]}return t}function OS(n,e,t,s=!1){for(let r of e){let i=mh(r);if(i.includes("*"))bh(n,i,t,r,s);else if(s)yh(n,i);else{let o=TS(n,i);if(o===_r)continue;let a=typeof t=="function"?t(o,i):t;gh(n,i,a)}}}function bh(n,e,t,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=n;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(r)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let u=[...o,l.toString()],d=typeof t=="function"?t(a[l],u):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let u in a)Object.prototype.hasOwnProperty.call(a,u)&&l.push(u);for(let u of l)delete a[u]}else for(let l in a){let u=[...o,l],d=typeof t=="function"?t(a[l],u):t;a[l]=d}}else PS(n,e,t,i,s,r)}function PS(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function u(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),u(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,u(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,u(d[h],f+1))}else if(a.includes("*"))bh(d,a,typeof t=="function"?(m,p)=>{let g=[...l.slice(0,f),...p];return t(m,g)}:t,r,i);else if(i)yh(d,a);else{let h=typeof t=="function"?t(RS(d,a),[...l.slice(0,f),...a]):t;gh(d,a,h)}}if(o.length===0)u(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&u(d,o.length)}}function IS(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=mh(t),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 MS(n,e){if(!e)return n;function t(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 l=0;l<s.length;l++){let u=l.toString();r.has(u)||r.has("*")?a[l]=t(s[l],r.get(u)||r.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=t(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return t(n,e)}function LS(n){if(typeof n!="string")throw new Error("Paths must be (non-empty) strings");if(n==="")throw new Error("Invalid redaction path ()");if(n.includes(".."))throw new Error(`Invalid redaction path (${n})`);if(n.includes(","))throw new Error(`Invalid redaction path (${n})`);let e=0,t=!1,s="";for(let r=0;r<n.length;r++){let i=n[r];if((i==='"'||i==="'")&&e>0)t?i===s&&(t=!1,s=""):(t=!0,s=i);else if(i==="["&&!t)e++;else if(i==="]"&&!t&&(e--,e<0))throw new Error(`Invalid redaction path (${n})`)}if(e!==0)throw new Error(`Invalid redaction path (${n})`)}function DS(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)LS(e)}function NS(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;DS(e);let o=IS(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let u=MS(l,o),d=l,f=t;return typeof t=="function"&&(f=t),OS(u,e,f,i),s===!1?(u.restore=function(){return Xa(d)},u):typeof s=="function"?s(u):JSON.stringify(u)}}vh.exports=NS});var Rn=j((aR,xh)=>{"use strict";var FS=Symbol("pino.setLevel"),jS=Symbol("pino.getLevel"),HS=Symbol("pino.levelVal"),BS=Symbol("pino.levelComp"),US=Symbol("pino.useLevelLabels"),qS=Symbol("pino.useOnlyCustomLevels"),KS=Symbol("pino.mixin"),GS=Symbol("pino.lsCache"),WS=Symbol("pino.chindings"),VS=Symbol("pino.asJson"),zS=Symbol("pino.write"),YS=Symbol("pino.redactFmt"),JS=Symbol("pino.time"),QS=Symbol("pino.timeSliceIndex"),XS=Symbol("pino.stream"),ZS=Symbol("pino.stringify"),e_=Symbol("pino.stringifySafe"),t_=Symbol("pino.stringifiers"),n_=Symbol("pino.end"),s_=Symbol("pino.formatOpts"),r_=Symbol("pino.messageKey"),i_=Symbol("pino.errorKey"),o_=Symbol("pino.nestedKey"),a_=Symbol("pino.nestedKeyStr"),l_=Symbol("pino.mixinMergeStrategy"),c_=Symbol("pino.msgPrefix"),u_=Symbol("pino.wildcardFirst"),d_=Symbol.for("pino.serializers"),f_=Symbol.for("pino.formatters"),p_=Symbol.for("pino.hooks"),h_=Symbol.for("pino.metadata");xh.exports={setLevelSym:FS,getLevelSym:jS,levelValSym:HS,levelCompSym:BS,useLevelLabelsSym:US,mixinSym:KS,lsCacheSym:GS,chindingsSym:WS,asJsonSym:VS,writeSym:zS,serializersSym:d_,redactFmtSym:YS,timeSym:JS,timeSliceIndexSym:QS,streamSym:XS,stringifySym:ZS,stringifySafeSym:e_,stringifiersSym:t_,endSym:n_,formatOptsSym:s_,messageKeySym:r_,errorKeySym:i_,nestedKeySym:o_,wildcardFirstSym:u_,needsMetadataGsym:h_,useOnlyCustomLevelsSym:qS,formattersSym:f_,hooksSym:p_,nestedKeyStrSym:a_,mixinMergeStrategySym:l_,msgPrefixSym:c_}});var el=j((lR,kh)=>{"use strict";var Sh=wh(),{redactFmtSym:m_,wildcardFirstSym:Ar}=Rn(),Za=/[^.[\]]+|\[([^[\]]*?)\]/g,_h="[Redacted]",Ah=!1;function g_(n,e){let{paths:t,censor:s,remove:r}=y_(n),i=t.reduce((l,u)=>{Za.lastIndex=0;let d=Za.exec(u),f=Za.exec(u),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=Ar),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${u.substr(m,u.length-1)}`;return l[h]=l[h]||[],h!==Ar&&l[h].length===0&&l[h].push(...l[Ar]||[]),h===Ar&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(p)}),l[h].push(p),l},{}),o={[m_]:Sh({paths:t,censor:s,serialize:e,strict:Ah,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,u)=>{if(i[u]===null)l[u]=d=>a(d,[u]);else{let d=typeof s=="function"?(f,h)=>s(f,[u,...h]):s;l[u]=Sh({paths:i[u],censor:d,serialize:e,strict:Ah,remove:r})}return l},o)}function y_(n){if(Array.isArray(n))return n={paths:n,censor:_h},n;let{paths:e,censor:t=_h,remove:s}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(t=void 0),{paths:e,censor:t,remove:s}}kh.exports=g_});var Ch=j((cR,Eh)=>{"use strict";var b_=()=>"",v_=()=>`,"time":${Date.now()}`,w_=()=>`,"time":${Math.round(Date.now()/1e3)}`,x_=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,S_=1000000n,$h=1000000000n,__=BigInt(Date.now())*S_,A_=process.hrtime.bigint(),k_=()=>{let n=process.hrtime.bigint()-A_,e=__+n,t=e/$h,s=e%$h,r=Number(t*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),u=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${u}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};Eh.exports={nullTime:b_,epochTime:v_,unixTime:w_,isoTime:x_,isoTimeNano:k_}});var Rh=j((uR,Th)=>{"use strict";function $_(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}Th.exports=E_;function E_(n,e,t){var s=t&&t.stringify||$_,r=1;if(typeof n=="object"&&n!==null){var i=e.length+r;if(i===1)return n;var o=new Array(i);o[0]=s(n);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var u="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(u+=n.slice(f,m)),u+=Math.floor(Number(e[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<m&&(u+=n.slice(f,m));var p=typeof e[d];if(p==="string"){u+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){u+=e[d].name||"<anonymous>",f=m+2,m++;break}u+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=n.slice(f,m)),u+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(u+=n.slice(f,m)),u+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(u+=n.slice(f)),u)}});var nl=j((dR,tl)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="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(n,0,0,Number(t))},n=new Int32Array(new SharedArrayBuffer(4));tl.exports=e}else{let n=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(););};tl.exports=n}});var Fh=j((fR,Nh)=>{"use strict";var le=require("fs"),C_=require("events"),T_=require("util").inherits,Oh=require("path"),rl=nl(),R_=require("assert"),kr=100,$r=Buffer.allocUnsafe(0),O_=16*1024,Ph="buffer",Ih="utf8",[P_,I_]=(process.versions.node||"0.0").split(".").map(Number),M_=P_>=22&&I_>=7;function Mh(n,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function t(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=n,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&&le.mkdirSync(Oh.dirname(n),{recursive:!0});let i=le.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?le.mkdir(Oh.dirname(n),{recursive:!0},i=>{if(i)return t(i);le.open(n,s,r,t)}):le.open(n,s,r,t)}function at(n){if(!(this instanceof at))return new at(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:u,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,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||O_,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=m,this.retryEAGAIN=d||(()=>!0),this.mkdir=u||!1;let p,g;if(h===Ph)this._writingBuf=$r,this.write=N_,this.flush=j_,this.flushSync=B_,this._actualWrite=q_,p=()=>le.writeSync(this.fd,this._writingBuf),g=()=>le.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Ih)this._writingBuf="",this.write=D_,this.flush=F_,this.flushSync=H_,this._actualWrite=U_,p=()=>Buffer.isBuffer(this._writingBuf)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?le.write(this.fd,this._writingBuf,this.release):le.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ih}" and "${Ph}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Mh(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=(x,A)=>{if(x){if((x.code==="EAGAIN"||x.code==="EBUSY")&&this.retryEAGAIN(x,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{rl(kr),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,kr);else this._writing=!1,this.emit("error",x);return}this.emit("write",A);let $=sl(this._writingBuf,this._len,A);if(this._len=$.len,this._writingBuf=$.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=p(),v=sl(this._writingBuf,this._len,y);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(y){this.release(y);return}}this._fsync&&le.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,Er(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(L_,this)):this.emit("drain"))},this.on("newListener",function(x){x==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function sl(n,e,t){return typeof n=="string"&&(n=Buffer.from(n)),e=Math.max(e-t,0),n=n.subarray(t),{writingBuf:n,len:e}}function L_(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}T_(at,C_);function Lh(n,e){return n.length===0?$r:n.length===1?n[0]:Buffer.concat(n,e)}function D_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let e=Buffer.byteLength(n),t=this._len+e,s=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(n):s[s.length-1]+=n,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function N_(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||s[s.length-1]+n.length>this.maxWrite?(t.push([n]),s.push(n.length)):(t[t.length-1].push(n),s[s.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Dh(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{le.fsync(this.fd,s=>{this._flushPending=!1,n(s)})}catch(s){n(s)}this.off("error",t)},t=s=>{this._flushPending=!1,n(s),this.off("drain",e)};this.once("drain",e),this.once("error",t)}function F_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Dh.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function j_(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&Dh.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}at.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});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(n&&(this.file=n),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&le.close(e,t=>{if(t)return this.emit("error",t)})}),Mh(this.file,this)};at.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():Er(this)))};function H_(){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 n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let e=Buffer.isBuffer(n)?le.writeSync(this.fd,n):le.writeSync(this.fd,n,"utf8"),t=sl(n,this._len,e);n=t.writingBuf,this._len=t.len,n.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;rl(kr)}}try{le.fsyncSync(this.fd)}catch{}}function B_(){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=$r);let n=$r;for(;this._bufs.length||n.length;){n.length<=0&&(n=Lh(this._bufs[0],this._lens[0]));try{let e=le.writeSync(this.fd,n);n=n.subarray(e),this._len=Math.max(this._len-e,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;rl(kr)}}}at.prototype.destroy=function(){this.destroyed||Er(this)};function U_(){let n=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)?le.writeSync(this.fd,this._writingBuf):le.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else le.write(this.fd,this._writingBuf,n)}function q_(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Lh(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=le.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else M_&&(this._writingBuf=Buffer.from(this._writingBuf)),le.write(this.fd,this._writingBuf,n)}function Er(n){if(n.fd===-1){n.once("ready",Er.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],R_(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{le.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?le.close(n.fd,t):t()}function t(s){if(s){n.emit("error",s);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}at.SonicBoom=at;at.default=at;Nh.exports=at});var il=j((pR,qh)=>{"use strict";var lt={exit:[],beforeExit:[]},jh={exit:W_,beforeExit:V_},On;function K_(){On===void 0&&(On=new FinalizationRegistry(z_))}function G_(n){lt[n].length>0||process.on(n,jh[n])}function Hh(n){lt[n].length>0||(process.removeListener(n,jh[n]),lt.exit.length===0&<.beforeExit.length===0&&(On=void 0))}function W_(){Bh("exit")}function V_(){Bh("beforeExit")}function Bh(n){for(let e of lt[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}lt[n]=[]}function z_(n){for(let e of["exit","beforeExit"]){let t=lt[e].indexOf(n);lt[e].splice(t,t+1),Hh(e)}}function Uh(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");G_(n);let s=new WeakRef(e);s.fn=t,K_(),On.register(e,s),lt[n].push(s)}function Y_(n,e){Uh("exit",n,e)}function J_(n,e){Uh("beforeExit",n,e)}function Q_(n){if(On!==void 0){On.unregister(n);for(let e of["exit","beforeExit"])lt[e]=lt[e].filter(t=>{let s=t.deref();return s&&s!==n}),Hh(e)}}qh.exports={register:Y_,registerBeforeExit:J_,unregister:Q_}});var Kh=j((hR,X_)=>{X_.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 Wh=j((mR,Gh)=>{"use strict";function Z_(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(n,e);if(a===t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,a,l);u.async?u.value.then(o):setImmediate(o)};o()}function eA(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(n,e)!==t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),u=Atomics.waitAsync(n,e,t,l);u.async?u.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}Gh.exports={wait:Z_,waitDiff:eA}});var zh=j((gR,Vh)=>{"use strict";Vh.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var om=j((yR,im)=>{"use strict";var{version:tA}=Kh(),{EventEmitter:nA}=require("events"),{Worker:sA}=require("worker_threads"),{join:rA}=require("path"),{pathToFileURL:iA}=require("url"),{wait:oA}=Wh(),{WRITE_INDEX:Pt,READ_INDEX:sn,SEQ_INDEX:ol}=zh(),aA=require("buffer"),lA=require("assert"),R=Symbol("kImpl"),cA=aA.constants.MAX_STRING_LENGTH;function Yh(){}function ul(n,e){Atomics.add(n[R].state,ol,1),e(),Atomics.add(n[R].state,ol,1),Atomics.notify(n[R].state,ol)}function Jh(n){ul(n,()=>{Atomics.store(n[R].state,sn,0),Atomics.store(n[R].state,Pt,0)})}var hs=class{constructor(e){this._value=e}deref(){return this._value}},Cr=class{register(){}unregister(){}},uA=process.env.NODE_V8_COVERAGE?Cr:global.FinalizationRegistry||Cr,dA=process.env.NODE_V8_COVERAGE?hs:global.WeakRef||hs,Qh=new uA(n=>{n.exited||n.terminate()});function fA(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||rA(__dirname,"lib","worker.js"),o=new sA(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:iA(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:tA},...s}}});return o.stream=new hs(n),o.on("message",pA),o.on("exit",em),Qh.register(n,o),o}function Xh(n){lA(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function Zh(n){for(;;){let e=Atomics.load(n[R].state,Pt),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?dl(n):n[R].needDrain&&process.nextTick(Xh,n);return}sm(n,t,Yh);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Tr(n,()=>{n.destroyed||(Jh(n),Zh(n))});return}et(n,new Error("overwritten"));return}}function pA(n){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new dA(e),Tr(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":et(e,n.err);break;case"EVENT":Array.isArray(n.args)?e.emit(n.name,...n.args):e.emit(n.name,n.args);break;case"FLUSHED":{if(n.context!=="thread-stream"){et(e,new Error("this should not happen: "+n.code));break}let t=e[R].flushCallbacks.get(n.id);t&&(e[R].flushCallbacks.delete(n.id),process.nextTick(t));break}case"WARNING":process.emitWarning(n.err);break;default:et(e,new Error("this should not happen: "+n.code))}}function em(n){let e=this.stream.deref();e!==void 0&&(Qh.unregister(e),e.worker.exited=!0,e.worker.off("exit",em),et(e,n!==0?new Error("the worker thread exited"):null))}var ll=class extends nA{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[R]={},this[R].stateBuf=new SharedArrayBuffer(128),this[R].state=new Int32Array(this[R].stateBuf),this[R].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[R].data=Buffer.from(this[R].dataBuf),this[R].sync=e.sync||!1,this[R].ending=!1,this[R].ended=!1,this[R].needDrain=!1,this[R].destroyed=!1,this[R].flushing=!1,this[R].ready=!1,this[R].finished=!1,this[R].errored=null,this[R].closed=!1,this[R].buf=[],this[R].bufHead=0,this[R].bufLen=0,this[R].flushCallbacks=new Map,this[R].nextFlushId=0,this.worker=fA(this,e),this.on("message",(t,s)=>{this.worker.postMessage(t,s)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[R].destroyed)return cl(this,new Error("the worker has exited")),!1;if(this[R].ending)return cl(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=cA)try{al(this),this[R].flushing=!0}catch(s){return et(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return al(this),!0}catch(s){return et(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(Zh,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,Pt)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,dl(this))}flush(e){e=typeof e=="function"?e:Yh,tm(this,t=>{if(t){process.nextTick(e,t);return}nm(this,e)})}flushSync(){this[R].destroyed||(al(this),rm(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[R].ready}get destroyed(){return this[R].destroyed}get closed(){return this[R].closed}get writable(){return!this[R].destroyed&&!this[R].ending}get writableEnded(){return this[R].ending}get writableFinished(){return this[R].finished}get writableNeedDrain(){return this[R].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[R].errored}};function tm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].sync&&(n[R].flushing||n[R].bufLen>0)){setImmediate(tm,n,e);return}Tr(n,e)}function Tr(n,e){let t=Atomics.load(n[R].state,Pt);oA(n[R].state,sn,t,1/0,(s,r)=>{if(s){et(n,s),e(s);return}if(r!=="ok"){Tr(n,e);return}e()})}function nm(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),nm(n,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",s),n.off("close",r)};n.once("ready",s),n.once("close",r);return}let t=++n[R].nextFlushId;n[R].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(s){n[R].flushCallbacks.delete(t),et(n,s),process.nextTick(e,s)}}function hA(n,e){let t=n[R].flushCallbacks;if(t.size===0)return;let s=e||new Error("the worker has exited");for(let r of t.values())process.nextTick(r,s);t.clear()}function cl(n,e){setImmediate(()=>{n.emit("error",e)})}function et(n,e){n[R].destroyed||(n[R].destroyed=!0,hA(n,e),e&&(n[R].errored=e,cl(n,e)),n.worker.exited?setImmediate(()=>{n[R].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[R].closed=!0,n.emit("close")}))}function sm(n,e,t){let r=Atomics.load(n[R].state,Pt),i=e;for(;i>0&&n[R].bufLen!==0;){let o=n[R].bufHead,a=n[R].buf[o];if(a.length<=i){a.copy(n[R].data,r),r+=a.length,i-=a.length,n[R].bufLen-=a.length,n[R].bufHead=o+1,n[R].bufHead===n[R].buf.length?(n[R].buf.length=0,n[R].bufHead=0):n[R].bufHead>=1024&&n[R].bufHead*2>=n[R].buf.length&&(n[R].buf.splice(0,n[R].bufHead),n[R].bufHead=0);continue}a.copy(n[R].data,r,0,i),n[R].buf[o]=a.subarray(i),n[R].bufLen-=i,r+=i,i=0}return ul(n,()=>{Atomics.store(n[R].state,Pt,r)}),t(),!0}function dl(n){if(!(n[R].ended||!n[R].ending||n[R].flushing)){n[R].ended=!0;try{n.flushSync();let e=Atomics.load(n[R].state,sn);ul(n,()=>{Atomics.store(n[R].state,Pt,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,sn,e,1e3),e=Atomics.load(n[R].state,sn),e===-2){et(n,new Error("end() failed"));return}if(++t===10){et(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){et(n,e)}}}function al(n){let e=()=>{n[R].ending?dl(n):n[R].needDrain&&process.nextTick(Xh,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,Pt),s=n[R].data.length-t;if(s===0){rm(n),Jh(n);continue}else if(s<0)throw new Error("overwritten");sm(n,s,e)}}function rm(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,Pt),t=0;for(;;){let s=Atomics.load(n[R].state,sn);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,sn,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}im.exports=ll});var hl=j((bR,cm)=>{"use strict";var{createRequire:mA}=require("module"),{existsSync:gA}=require("node:fs"),yA=Qa(),{join:fl,isAbsolute:lm,sep:bA}=require("node:path"),{fileURLToPath:vA}=require("node:url"),wA=nl(),pl=il(),xA=om();function SA(n){pl.register(n,EA),pl.registerBeforeExit(n,CA),n.on("close",function(){pl.unregister(n)})}function _A(){let n=process.execArgv;for(let e=0;e<n.length;e++){let t=n[e];if(t==="--import"||t==="--require"||t==="-r"||t.startsWith("--import=")||t.startsWith("--require=")||t.startsWith("-r="))return!0}return!1}function AA(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],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&&am(o)){s=!0,r++;continue}t.push(i),o&&(t.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(am(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function am(n){let e=kA(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=vA(t)}catch{return!1}return lm(t)&&!gA(t)}function kA(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function $A(n,e,t,s,r){if(!t.execArgv&&_A()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=AA(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new xA({filename:n,workerData:e,workerOpts:t,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(),t.autoEnd!==!1&&SA(i)}function a(){i.closed||(i.flushSync(),wA(100),i.end())}return i}function EA(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function CA(n){n.flushSync()}function TA(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=yA(),sync:a=!1}=n,l={...n.options},u=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=n.target;if(f&&t)throw new Error("only one of target or targets can be specified");t?(f=d["pino-worker"]||fl(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(g=>({...g,level:p.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||fl(__dirname,"worker.js"),l.pipelines=[e.map(p=>({...p,target:m(p.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let h=t||e?"pino.transport":f;return $A(m(f),l,i,a,h);function m(p){if(p=d[p]||p,lm(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return fl(__dirname,"..","file.js");let g;for(let x of u)try{let A=x==="node:repl"?process.cwd()+bA:x;g=mA(A).resolve(p);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${p}"`);return g}}cm.exports=TA});var Pr=j((vR,Sm)=>{"use strict";var RA=require("node:diagnostics_channel"),um=Rh(),{mapHttpRequest:OA,mapHttpResponse:PA}=Ja(),gl=Fh(),dm=il(),{lsCacheSym:IA,chindingsSym:gm,writeSym:fm,serializersSym:ym,formatOptsSym:pm,endSym:MA,stringifiersSym:bm,stringifySym:vm,stringifySafeSym:yl,wildcardFirstSym:wm,nestedKeySym:LA,formattersSym:xm,messageKeySym:DA,errorKeySym:NA,nestedKeyStrSym:FA,msgPrefixSym:Rr}=Rn(),{isMainThread:jA}=require("worker_threads"),HA=hl(),[BA]=process.versions.node.split(".").map(n=>Number(n)),hm=RA.tracingChannel("pino_asJson"),ml=BA>=25?n=>JSON.stringify(n):qA;function Pn(){}function UA(n,e){if(!e)return t;return function(...r){e.call(this,r,t,n)};function t(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=OA(s):typeof s.setHeader=="function"&&(s=PA(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Rr]=="string"&&i!==void 0&&i!==null&&(i=this[Rr]+i),this[fm](s,um(i,o,this[pm]),n)}else{let i=s===void 0?r.shift():s;typeof this[Rr]=="string"&&i!==void 0&&i!==null&&(i=this[Rr]+i),this[fm](null,um(i,r,this[pm]),n)}}}function qA(n){let e="",t=0,s=!1,r=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&r>=32;o++)r=n.charCodeAt(o),(r===34||r===92)&&(e+=n.slice(t,o)+"\\",t=o,s=!0);return s?e+=n.slice(t):e=n,r<32?JSON.stringify(n):'"'+e+'"'}function KA(n,e,t,s){if(hm.hasSubscribers===!1)return mm.call(this,n,e,t,s);let r={instance:this,arguments};return hm.traceSync(mm,r,this,n,e,t,s)}function mm(n,e,t,s){let r=this[vm],i=this[yl],o=this[bm],a=this[MA],l=this[gm],u=this[ym],d=this[xm],f=this[DA],h=this[NA],m=this[IA][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let g=o[wm],x="";for(let $ in n)if(p=n[$],Object.prototype.hasOwnProperty.call(n,$)&&p!==void 0){u[$]?p=u[$](p):$===h&&u.err&&(p=u.err(p));let _=o[$]||g;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":_&&(p=_(p));break;case"string":p=(_||ml)(p);break;default:p=(_||r)(p,i)}if(p===void 0)continue;let y=ml($);x+=","+y+":"+p}let A="";if(e!==void 0){p=u[f]?u[f](e):e;let $=o[f]||g;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":$&&(p=$(p)),A=',"'+f+'":'+p;break;case"string":p=($||ml)(p),A=',"'+f+'":'+p;break;default:p=($||r)(p,i),A=',"'+f+'":'+p}}return this[LA]&&x?m+this[FA]+x.slice(1)+"}"+A+a:m+x+A+a}function GA(n,e){let t,s=n[gm],r=n[vm],i=n[yl],o=n[bm],a=o[wm],l=n[ym],u=n[xm].bindings;e=u(e);for(let d in e)if(t=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&t!==void 0)===!0){if(t=l[d]?l[d](t):t,t=(o[d]||a||r)(t,i),t===void 0)continue;s+=',"'+d+'":'+t}return s}function WA(n){return n.write!==n.constructor.prototype.write}function Or(n){let e=new gl(n);return e.on("error",t),!n.sync&&jA&&(dm.register(e,VA),e.on("close",function(){dm.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=Pn,e.end=Pn,e.flushSync=Pn,e.destroy=Pn;return}e.removeListener("error",t),e.emit("error",s)}}function VA(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function zA(n){return function(t,s,r={},i){if(typeof r=="string")i=Or({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=Or({dest:i})}else if(r instanceof gl||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof gl||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 l;r.customLevels&&(l=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=HA({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.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=Pn),i||(WA(process.stdout)?i=process.stdout:i=Or({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function YA(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[yl])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function JA(n,e,t){return{level:n,bindings:e,log:t}}function QA(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}Sm.exports={noop:Pn,buildSafeSonicBoom:Or,asChindings:GA,asJson:KA,genLog:UA,createArgsNormalizer:zA,stringify:YA,buildFormatters:JA,normalizeDestFileDescriptor:QA}});var Ir=j((wR,_m)=>{var XA={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ZA={ASC:"ASC",DESC:"DESC"};_m.exports={DEFAULT_LEVELS:XA,SORTING_ORDER:ZA}});var wl=j((xR,Em)=>{"use strict";var{lsCacheSym:ek,levelValSym:bl,useOnlyCustomLevelsSym:tk,streamSym:nk,formattersSym:sk,hooksSym:rk,levelCompSym:Am}=Rn(),{noop:ik,genLog:rn}=Pr(),{DEFAULT_LEVELS:yt,SORTING_ORDER:km}=Ir(),$m={fatal:n=>{let e=rn(yt.fatal,n);return function(...t){let s=this[nk];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>rn(yt.error,n),warn:n=>rn(yt.warn,n),info:n=>rn(yt.info,n),debug:n=>rn(yt.debug,n),trace:n=>rn(yt.trace,n)},vl=Object.keys(yt).reduce((n,e)=>(n[yt[e]]=e,n),{}),ok=Object.keys(vl).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function ak(n){let e=n[sk].level,{labels:t}=n.levels,s={};for(let r in t){let i=e(t[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return n[ek]=s,n}function lk(n,e){if(e)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function ck(n){let{labels:e,values:t}=this.levels;if(typeof n=="number"){if(e[n]===void 0)throw Error("unknown level value"+n);n=e[n]}if(t[n]===void 0)throw Error("unknown level "+n);let s=this[bl],r=this[bl]=t[n],i=this[tk],o=this[Am],a=this[rk].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=ik;continue}this[l]=lk(l,i)?$m[l](a):rn(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function uk(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function dk(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[Am](t,this[bl])}function fk(n,e,t){return n===km.DESC?e<=t:e>=t}function pk(n){return typeof n=="string"?fk.bind(null,n):n}function hk(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:vl,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:yt,n);return{labels:s,values:r}}function mk(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(vl).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:yt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function gk(n,e){let{labels:t,values:s}=n;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in t)throw Error("pre-existing level values cannot be used for new levels")}}function yk(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(km).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Em.exports={initialLsCache:ok,genLsCache:ak,levelMethods:$m,getLevel:uk,setLevel:ck,isLevelEnabled:dk,mappings:hk,assertNoLevelCollisions:gk,assertDefaultLevelFound:mk,genLevelComparison:pk,assertLevelComparison:yk}});var xl=j((SR,Cm)=>{"use strict";Cm.exports={version:"10.3.1"}});var Dm=j((AR,Lm)=>{"use strict";var{EventEmitter:bk}=require("node:events"),{lsCacheSym:vk,levelValSym:wk,setLevelSym:_l,getLevelSym:Tm,chindingsSym:Lr,mixinSym:xk,asJsonSym:Om,writeSym:Sk,mixinMergeStrategySym:_k,timeSym:Ak,timeSliceIndexSym:kk,streamSym:Pm,serializersSym:on,formattersSym:ms,errorKeySym:$k,messageKeySym:Ek,useOnlyCustomLevelsSym:Ck,needsMetadataGsym:Tk,redactFmtSym:Rk,stringifySym:Ok,formatOptsSym:Pk,stringifiersSym:Ik,msgPrefixSym:Al,hooksSym:Mk}=Rn(),{getLevel:Lk,setLevel:Dk,isLevelEnabled:Nk,mappings:Fk,initialLsCache:jk,genLsCache:Hk,assertNoLevelCollisions:Bk}=wl(),{asChindings:kl,asJson:Uk,buildFormatters:Sl,stringify:Rm,noop:Im}=Pr(),{version:qk}=xl(),Kk=el(),Gk=class{},Mm={constructor:Gk,child:Wk,bindings:Vk,setBindings:zk,flush:Qk,isLevelEnabled:Nk,version:qk,get level(){return this[Tm]()},set level(n){this[_l](n)},get levelVal(){return this[wk]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[Al]},get[Symbol.toStringTag](){return"Pino"},[vk]:jk,[Sk]:Jk,[Om]:Uk,[Tm]:Lk,[_l]:Dk};Object.setPrototypeOf(Mm,bk.prototype);Lm.exports=function(){return Object.create(Mm)};var Mr=n=>n;function Wk(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[on],s=this[ms],r=Object.create(this);if(e==null)return r[ms].bindings!==Mr&&(r[ms]=Sl(s.level,Mr,s.log)),r[Lr]=kl(r,n),this.onChild!==Im&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[on]=Object.create(null);for(let u in t)r[on][u]=t[u];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let u=a[i];r[on][u]=t[u]}for(let u in e.serializers)r[on][u]=e.serializers[u];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let u=l[o];r[on][u]=e.serializers[u]}}else r[on]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:u}=e.formatters;r[ms]=Sl(a||s.level,l||Mr,u||s.log)}else r[ms]=Sl(s.level,Mr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(Bk(this.levels,e.customLevels),r.levels=Fk(e.customLevels,r[Ck]),Hk(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Kk(r.redact,Rm),l={stringify:a[Rk]};r[Ok]=Rm,r[Ik]=a,r[Pk]=l}if(typeof e.msgPrefix=="string"&&(r[Al]=(this[Al]||"")+e.msgPrefix),r[Lr]=kl(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[_l](a)}return this.onChild(r),r}function Vk(){let e=`{${this[Lr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function zk(n){let e=kl(this,n);this[Lr]=e}function Yk(n,e){return Object.assign(e,n)}function Jk(n,e,t){let s=this[Ak](),r=this[xk],i=this[$k],o=this[Ek],a=this[_k]||Yk,l,u=this[Mk].streamWrite;n==null?l={}:n instanceof Error?(l={[i]:n},e===void 0&&(e=n.message)):(l=n,e===void 0&&n[o]===void 0&&n[i]&&(e=n[i].message)),r&&(l=a(l,r(l,t,this)));let d=this[Om](l,e,t,s),f=this[Pm];f[Tk]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[kk]),f.lastLogger=this),f.write(u?u(d):d)}function Qk(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[Pm];typeof e.flush=="function"?e.flush(n||Im):n&&n()}});var Hm=j((Tl,jm)=>{"use strict";var{hasOwnProperty:gs}=Object.prototype,ln=Cl();ln.configure=Cl;ln.stringify=ln;ln.default=ln;Tl.stringify=ln;Tl.configure=Cl;jm.exports=ln;var Xk=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ut(n){return n.length<5e3&&!Xk.test(n)?`"${n}"`:JSON.stringify(n)}function $l(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let s=n[t],r=t;for(;r!==0&&n[r-1]>s;)n[r]=n[r-1],r--;n[r]=s}return n}var Zk=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function El(n){return Zk.call(n)!==void 0&&n.length!==0}function Nm(n,e,t){n.length<t&&(t=n.length);let s=e===","?"":" ",r=`"0":${s}${n[0]}`;for(let i=1;i<t;i++)r+=`${e}"${i}":${s}${n[i]}`;return r}function e$(n){if(gs.call(n,"circularValue")){let e=n.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 t$(n){let e;if(gs.call(n,"deterministic")&&(e=n.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 n$(n,e){let t;if(gs.call(n,e)&&(t=n[e],typeof t!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return t===void 0?!0:t}function Fm(n,e){let t;if(gs.call(n,e)){if(t=n[e],typeof t!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(t))throw new TypeError(`The "${e}" argument must be an integer`);if(t<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return t===void 0?1/0:t}function an(n){return n===1?"1 item":`${n} items`}function s$(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function r$(n){if(gs.call(n,"strict")){let e=n.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return t=>{let s=`Object can not safely be stringified. Received type ${typeof t}`;throw typeof t!="function"&&(s+=` (${t.toString()})`),new Error(s)}}}function Cl(n){n={...n};let e=r$(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=e$(n),s=n$(n,"bigint"),r=t$(n),i=typeof r=="function"?r:void 0,o=Fm(n,"maximumDepth"),a=Fm(n,"maximumBreadth");function l(m,p,g,x,A,$){let _=p[m];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(m)),_=x.call(p,m,_),typeof _){case"string":return Ut(_);case"object":{if(_===null)return"null";if(g.indexOf(_)!==-1)return t;let y="",v=",",b=$;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(_),A!==""&&($+=A,y+=`
|
|
717
|
-
${
|
|
718
|
-
${
|
|
719
|
-
${b}`),g.pop(),`[${y}]`}let w=Object.keys(
|
|
720
|
-
${
|
|
721
|
-
${
|
|
722
|
-
${b}`),g.pop(),`{${y}}`}case"number":return isFinite(
|
|
723
|
-
${
|
|
724
|
-
${
|
|
725
|
-
${
|
|
726
|
-
${
|
|
727
|
-
${
|
|
728
|
-
${
|
|
729
|
-
${A}`,
|
|
730
|
-
${A}
|
|
731
|
-
${
|
|
732
|
-
${A}`,b="",w="",
|
|
691
|
+
`)}search(e,t){let s=e.toLowerCase(),r=s.split(/\s+/).filter(l=>l.length>2),i=t?.maxResults||20,o=[],a=t?.agent?this.getAgentMemories(t.agent):this.getAll();for(let l of a){if(t?.category&&l.category!==t.category||t?.minImportance&&l.importance<t.minImportance)continue;let c=0,d="partial";l.key.toLowerCase()===s&&(c+=10,d="exact"),l.key.toLowerCase().includes(s)&&(c+=5),l.value.toLowerCase().includes(s)&&(c+=3);for(let h of r)l.key.toLowerCase().includes(h)&&(c+=2),l.value.toLowerCase().includes(h)&&(c+=1),l.tags.some(m=>m.toLowerCase().includes(h))&&(c+=2,d=d==="exact"?"exact":"tag");c*=1+l.importance*.1,c*=1+l.useCount*.2;let f=(Date.now()-l.updatedAt)/(10080*60*1e3);c*=Math.max(.3,1-f*.1),c>.5&&o.push({entry:l,relevanceScore:c,matchType:d})}return o.sort((l,c)=>c.relevanceScore-l.relevanceScore).slice(0,i)}getAll(e){let t=Array.from(this.entries.values());return e?t.filter(s=>s.category===e):t}getByFile(e){return Array.from(this.entries.values()).filter(t=>t.relatedFiles.some(s=>s.includes(e)||e.includes(s)))}getTopMemories(e=15){return Array.from(this.entries.values()).sort((t,s)=>{let r=t.importance*(1+t.useCount*.3)*(1+Math.log1p(t.accessCount)*.1);return s.importance*(1+s.useCount*.3)*(1+Math.log1p(s.accessCount)*.1)-r}).slice(0,e)}getSummary(){let e=this.getTopMemories(15);if(e.length===0)return"";let t={};for(let r of e){let i=r.category;t[i]||(t[i]=[]),t[i].push(`${r.key}: ${r.value}`)}let s=["## Project Memory"];for(let[r,i]of Object.entries(t)){s.push(`### ${r}`);for(let o of i)s.push(`- ${o}`)}return s.join(`
|
|
692
|
+
`)}getStats(){let e=this.getAll(),t={},s={};for(let r of e)t[r.category]=(t[r.category]||0)+1,s[r.createdBy]=(s[r.createdBy]||0)+1;return{totalEntries:e.length,byCategory:t,byAgent:s,topAccessed:e.sort((r,i)=>i.accessCount-r.accessCount).slice(0,5),recentlyAdded:e.sort((r,i)=>i.createdAt-r.createdAt).slice(0,5),totalAccessCount:e.reduce((r,i)=>r+i.accessCount,0)}}consolidate(e=200){if(this.entries.size<=e)return 0;let t=Array.from(this.entries.values()).filter(o=>o.importance<4&&o.accessCount<3).sort((o,a)=>o.updatedAt-a.updatedAt),s=t.slice(0,Math.max(10,t.length-e)),r={};for(let o of s){let a=o.category;r[a]||(r[a]=[]),r[a].push(o)}let i=0;for(let[o,a]of Object.entries(r)){if(a.length<2)continue;let l=`[consolidated] ${o} (${a.length} items)`,c=a.map(h=>`${h.key}: ${h.value}`).join("; "),d=a.map(h=>h.key);this.set(l,c.slice(0,500),{category:o,importance:3,tags:["consolidated"]});let f=this.entries.get(l);f&&(f.consolidatedFrom=d);for(let h of a)this.entries.delete(h.key),i++}return i>0&&this.save(),i}learnFromToolResult(e,t,s,r,i="hablas"){if(!(s.length<20)){if(!r){let o=`error:${e}:${JSON.stringify(t).slice(0,50)}`,a=this.entries.get(o);a?(a.useCount++,a.importance=Math.min(10,a.importance+1)):this.set(o,`${e} failed with: ${s.slice(0,200)}`,{category:"error",importance:6,createdBy:i,tags:["auto-learned","error",e]})}if(e==="list_dir"&&r){let o=t.path||".";this.set(`structure:${o}`,s.slice(0,300),{category:"pattern",importance:3,createdBy:i,tags:["auto-learned","structure"],relatedFiles:[o]})}}}size(){return this.entries.size}clear(){this.entries.clear(),this.agentLanes.clear(),this.save(),this.saveAgentLanes()}render(){if(this.getAll().length===0)return" No project memories stored";let t={convention:"\u{1F4CF}",decision:"\u{1F3AF}",pattern:"\u{1F504}",note:"\u{1F4DD}",error:"\u26A0\uFE0F","tool-result":"\u{1F527}","user-pref":"\u{1F464}",dependency:"\u{1F4E6}",performance:"\u26A1",security:"\u{1F512}",api:"\u{1F310}","agent-learning":"\u{1F916}"};return this.getTopMemories(20).map(i=>{let o=t[i.category]||"\xB7",a=i.importance>=7?" \u2605":"",l=i.useCount>0?` (used ${i.useCount}\xD7)`:"";return` ${o}${a} ${i.key}: ${i.value}${l}`}).join(`
|
|
693
|
+
`)}autoImportance(e,t){let r={convention:6,decision:8,pattern:5,note:3,error:7,"tool-result":2,"user-pref":7,dependency:4,performance:5,security:9,api:6,"agent-learning":4}[e]||3;return/\b(important|critical|must|always|never|danger|warning|breaking)\b/i.test(t)&&(r=Math.min(10,r+2)),r}autoTag(e,t){let s=[t];return/\b(react|vue|angular|svelte|next|nuxt)\b/i.test(e)&&s.push("frontend"),/\b(express|fastify|nest|koa|hapi)\b/i.test(e)&&s.push("backend"),/\b(postgres|mysql|mongo|redis|sqlite)\b/i.test(e)&&s.push("database"),/\b(docker|kubernetes|k8s|ci\/cd|deploy)\b/i.test(e)&&s.push("devops"),/\b(test|jest|vitest|cypress|playwright)\b/i.test(e)&&s.push("testing"),/\b(auth|jwt|oauth|session|token)\b/i.test(e)&&s.push("auth"),/\b(api|endpoint|route|rest|graphql)\b/i.test(e)&&s.push("api"),s}extractFileRefs(e){let t=/[\w\-./]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|sql|sh|toml|xml|env)/gi,s=e.match(t);return s?[...new Set(s)]:[]}load(){try{if(Ce.existsSync(this.filePath)){let e=JSON.parse(Ce.readFileSync(this.filePath,"utf-8"));if(Array.isArray(e))for(let t of e)t.importance||(t.importance=3),t.createdBy||(t.createdBy="hablas"),t.accessCount||(t.accessCount=0),t.useCount||(t.useCount=0),t.tags||(t.tags=[t.category||"note"]),t.relatedFiles||(t.relatedFiles=[]),t.lastAccessedAt||(t.lastAccessedAt=t.updatedAt||Date.now()),this.entries.set(t.key,t)}}catch{}this.loadAgentLanes()}save(){try{Ce.existsSync(pn)||Ce.mkdirSync(pn,{recursive:!0});let e=Array.from(this.entries.values());Ce.writeFileSync(this.filePath,JSON.stringify(e,null,2),"utf-8")}catch{}}loadAgentLanes(){try{if(Ce.existsSync(this.agentLanesPath)){let e=JSON.parse(Ce.readFileSync(this.agentLanesPath,"utf-8"));for(let[t,s]of Object.entries(e)){let r=new Map;for(let i of s)r.set(i.key,i);this.agentLanes.set(t,r)}}}catch{}}saveAgentLanes(){try{Ce.existsSync(pn)||Ce.mkdirSync(pn,{recursive:!0});let e={};for(let[t,s]of this.agentLanes)e[t]=Array.from(s.values());Ce.writeFileSync(this.agentLanesPath,JSON.stringify(e,null,2),"utf-8")}catch{}}}});var Ao=H((MC,Ad)=>{"use strict";var Un=n=>n&&typeof n.message=="string",_o=n=>{if(!n)return;let e=n.cause;if(typeof e=="function"){let t=n.cause();return Un(t)?t:void 0}else return Un(e)?e:void 0},Sd=(n,e)=>{if(!Un(n))return"";let t=n.stack||"";if(e.has(n))return t+`
|
|
694
|
+
causes have become circular...`;let s=_o(n);return s?(e.add(n),t+`
|
|
695
|
+
caused by: `+Sd(s,e)):t},wb=n=>Sd(n,new Set),_d=(n,e,t)=>{if(!Un(n))return"";let s=t?"":n.message||"";if(e.has(n))return s+": ...";let r=_o(n);if(r){e.add(n);let i=typeof n.cause=="function";return s+(i?"":": ")+_d(r,e,i)}else return s},xb=n=>_d(n,new Set);Ad.exports={isErrorLike:Un,getErrorCause:_o,stackWithCauses:wb,messageWithCauses:xb}});var ko=H((LC,$d)=>{"use strict";var Sb=Symbol("circular-ref-tag"),Fs=Symbol("pino-raw-err-ref"),kd=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[Fs]},set:function(n){this[Fs]=n}}});Object.defineProperty(kd,Fs,{writable:!0,value:{}});$d.exports={pinoErrProto:kd,pinoErrorSymbols:{seen:Sb,rawSymbol:Fs}}});var Td=H((DC,Cd)=>{"use strict";Cd.exports=Eo;var{messageWithCauses:_b,stackWithCauses:Ab,isErrorLike:Ed}=Ao(),{pinoErrProto:kb,pinoErrorSymbols:$b}=ko(),{seen:$o}=$b,{toString:Eb}=Object.prototype;function Eo(n){if(!Ed(n))return n;n[$o]=void 0;let e=Object.create(kb);e.type=Eb.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=_b(n),e.stack=Ab(n),Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>Eo(t)));for(let t in n)if(e[t]===void 0){let s=n[t];Ed(s)?t!=="cause"&&!Object.prototype.hasOwnProperty.call(s,$o)&&(e[t]=Eo(s)):e[t]=s}return delete n[$o],e.raw=n,e}});var Od=H((NC,Rd)=>{"use strict";Rd.exports=js;var{isErrorLike:Co}=Ao(),{pinoErrProto:Cb,pinoErrorSymbols:Tb}=ko(),{seen:Hs}=Tb,{toString:Rb}=Object.prototype;function js(n){if(!Co(n))return n;n[Hs]=void 0;let e=Object.create(Cb);e.type=Rb.call(n.constructor)==="[object Function]"?n.constructor.name:n.name,e.message=n.message,e.stack=n.stack,Array.isArray(n.errors)&&(e.aggregateErrors=n.errors.map(t=>js(t))),Co(n.cause)&&!Object.prototype.hasOwnProperty.call(n.cause,Hs)&&(e.cause=js(n.cause));for(let t in n)if(e[t]===void 0){let s=n[t];Co(s)?Object.prototype.hasOwnProperty.call(s,Hs)||(e[t]=js(s)):e[t]=s}return delete n[Hs],e.raw=n,e}});var Ld=H((FC,Md)=>{"use strict";Md.exports={mapHttpRequest:Ob,reqSerializer:Id};var To=Symbol("pino-raw-req-ref"),Pd=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[To]},set:function(n){this[To]=n}}});Object.defineProperty(Pd,To,{writable:!0,value:{}});function Id(n){let e=n.info||n.socket,t=Object.create(Pd);if(t.id=typeof n.id=="function"?n.id():n.id||(n.info?n.info.id:void 0),t.method=n.method,n.originalUrl)t.url=n.originalUrl;else{let s=n.path;t.url=typeof s=="string"?s:n.url?n.url.path||n.url:void 0}return n.query&&(t.query=n.query),n.params&&(t.params=n.params),t.headers=n.headers,t.remoteAddress=e&&e.remoteAddress,t.remotePort=e&&e.remotePort,t.raw=n.raw||n,t}function Ob(n){return{req:Id(n)}}});var Hd=H((HC,Fd)=>{"use strict";Fd.exports={mapHttpResponse:Pb,resSerializer:Nd};var Ro=Symbol("pino-raw-res-ref"),Dd=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ro]},set:function(n){this[Ro]=n}}});Object.defineProperty(Dd,Ro,{writable:!0,value:{}});function Nd(n){let e=Object.create(Dd);return e.statusCode=n.headersSent?n.statusCode:null,e.headers=n.getHeaders?n.getHeaders():n._headers,e.raw=n,e}function Pb(n){return{res:Nd(n)}}});var Po=H((jC,jd)=>{"use strict";var Oo=Td(),Ib=Od(),Bs=Ld(),Us=Hd();jd.exports={err:Oo,errWithCause:Ib,mapHttpRequest:Bs.mapHttpRequest,mapHttpResponse:Us.mapHttpResponse,req:Bs.reqSerializer,res:Us.resSerializer,wrapErrorSerializer:function(e){return e===Oo?e:function(s){return e(Oo(s))}},wrapRequestSerializer:function(e){return e===Bs.reqSerializer?e:function(s){return e(Bs.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===Us.resSerializer?e:function(s){return e(Us.resSerializer(s))}}}});var Io=H((BC,Bd)=>{"use strict";function Mb(n,e){return e}Bd.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Mb;let t=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let s=t.slice(2),r=[];for(let i of s)i&&r.push(i.getFileName());return r}});var Vd=H((UC,Gd)=>{"use strict";function Mo(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof Array){let e=[];for(let t=0;t<n.length;t++)e[t]=Mo(n[t]);return e}if(typeof n=="object"){let e=Object.create(Object.getPrototypeOf(n));for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=Mo(n[t]));return e}return n}function Ud(n){let e=[],t="",s=!1,r=!1,i="";for(let o=0;o<n.length;o++){let a=n[o];!s&&a==="."?t&&(e.push(t),t=""):a==="["?(t&&(e.push(t),t=""),s=!0):a==="]"&&s?(e.push(t),t="",s=!1,r=!1):(a==='"'||a==="'")&&s?r?a===i?(r=!1,i=""):t+=a:(r=!0,i=a):t+=a}return t&&e.push(t),e}function Kd(n,e,t){let s=n;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]=t;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=t)}else typeof s=="object"&&s!==null&&r in s&&Object.prototype.hasOwnProperty.call(s,r)&&(s[r]=t);return!0}function qd(n,e){let t=n;for(let r=0;r<e.length-1;r++){let i=e[r];if(typeof t!="object"||t===null||!(i in t)||typeof t[i]!="object"||t[i]===null)return!1;t=t[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(t))for(let r=0;r<t.length;r++)t[r]=void 0;else if(typeof t=="object"&&t!==null)for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&delete t[r]}else typeof t=="object"&&t!==null&&s in t&&Object.prototype.hasOwnProperty.call(t,s)&&delete t[s];return!0}var Ks=Symbol("PATH_NOT_FOUND");function Lb(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null||!(s in t))return Ks;t=t[s]}return t}function Db(n,e){let t=n;for(let s of e){if(t==null||typeof t!="object"||t===null)return;t=t[s]}return t}function Nb(n,e,t,s=!1){for(let r of e){let i=Ud(r);if(i.includes("*"))Wd(n,i,t,r,s);else if(s)qd(n,i);else{let o=Lb(n,i);if(o===Ks)continue;let a=typeof t=="function"?t(o,i):t;Kd(n,i,a)}}}function Wd(n,e,t,s,r=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=n;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(r)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],d=typeof t=="function"?t(a[l],c):t;a[l]=d}else if(typeof a=="object"&&a!==null)if(r){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],d=typeof t=="function"?t(a[l],c):t;a[l]=d}}else Fb(n,e,t,i,s,r)}function Fb(n,e,t,s,r,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function c(d,f){if(f===o.length){if(Array.isArray(d))for(let h=0;h<d.length;h++)l[f]=h.toString(),c(d[h],f+1);else if(typeof d=="object"&&d!==null)for(let h in d)l[f]=h,c(d[h],f+1)}else if(f<o.length){let h=o[f];d&&typeof d=="object"&&d!==null&&h in d&&(l[f]=h,c(d[h],f+1))}else if(a.includes("*"))Wd(d,a,typeof t=="function"?(m,p)=>{let g=[...l.slice(0,f),...p];return t(m,g)}:t,r,i);else if(i)qd(d,a);else{let h=typeof t=="function"?t(Db(d,a),[...l.slice(0,f),...a]):t;Kd(d,a,h)}}if(o.length===0)c(n,0);else{let d=n;for(let f=0;f<o.length;f++){let h=o[f];if(d==null||typeof d!="object"||d===null)return;d=d[h],l[f]=h}d!=null&&c(d,o.length)}}function Hb(n){if(n.length===0)return null;let e=new Map;for(let t of n){let s=Ud(t),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 jb(n,e){if(!e)return n;function t(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 l=0;l<s.length;l++){let c=l.toString();r.has(c)||r.has("*")?a[l]=t(s[l],r.get(c)||r.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r.has(a)||r.has("*")?o[a]=t(s[a],r.get(a)||r.get("*")):o[a]=s[a]);return o}return t(n,e)}function Bb(n){if(typeof n!="string")throw new Error("Paths must be (non-empty) strings");if(n==="")throw new Error("Invalid redaction path ()");if(n.includes(".."))throw new Error(`Invalid redaction path (${n})`);if(n.includes(","))throw new Error(`Invalid redaction path (${n})`);let e=0,t=!1,s="";for(let r=0;r<n.length;r++){let i=n[r];if((i==='"'||i==="'")&&e>0)t?i===s&&(t=!1,s=""):(t=!0,s=i);else if(i==="["&&!t)e++;else if(i==="]"&&!t&&(e--,e<0))throw new Error(`Invalid redaction path (${n})`)}if(e!==0)throw new Error(`Invalid redaction path (${n})`)}function Ub(n){if(!Array.isArray(n))throw new TypeError("paths must be an array");for(let e of n)Bb(e)}function Kb(n={}){let{paths:e=[],censor:t="[REDACTED]",serialize:s=JSON.stringify,strict:r=!0,remove:i=!1}=n;Ub(e);let o=Hb(e);return function(l){if(r&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let c=jb(l,o),d=l,f=t;return typeof t=="function"&&(f=t),Nb(c,e,f,i),s===!1?(c.restore=function(){return Mo(d)},c):typeof s=="function"?s(c):JSON.stringify(c)}}Gd.exports=Kb});var hn=H((KC,zd)=>{"use strict";var qb=Symbol("pino.setLevel"),Wb=Symbol("pino.getLevel"),Gb=Symbol("pino.levelVal"),Vb=Symbol("pino.levelComp"),zb=Symbol("pino.useLevelLabels"),Yb=Symbol("pino.useOnlyCustomLevels"),Jb=Symbol("pino.mixin"),Qb=Symbol("pino.lsCache"),Xb=Symbol("pino.chindings"),Zb=Symbol("pino.asJson"),ev=Symbol("pino.write"),tv=Symbol("pino.redactFmt"),nv=Symbol("pino.time"),sv=Symbol("pino.timeSliceIndex"),rv=Symbol("pino.stream"),iv=Symbol("pino.stringify"),ov=Symbol("pino.stringifySafe"),av=Symbol("pino.stringifiers"),lv=Symbol("pino.end"),cv=Symbol("pino.formatOpts"),uv=Symbol("pino.messageKey"),dv=Symbol("pino.errorKey"),fv=Symbol("pino.nestedKey"),pv=Symbol("pino.nestedKeyStr"),hv=Symbol("pino.mixinMergeStrategy"),mv=Symbol("pino.msgPrefix"),gv=Symbol("pino.wildcardFirst"),yv=Symbol.for("pino.serializers"),bv=Symbol.for("pino.formatters"),vv=Symbol.for("pino.hooks"),wv=Symbol.for("pino.metadata");zd.exports={setLevelSym:qb,getLevelSym:Wb,levelValSym:Gb,levelCompSym:Vb,useLevelLabelsSym:zb,mixinSym:Jb,lsCacheSym:Qb,chindingsSym:Xb,asJsonSym:Zb,writeSym:ev,serializersSym:yv,redactFmtSym:tv,timeSym:nv,timeSliceIndexSym:sv,streamSym:rv,stringifySym:iv,stringifySafeSym:ov,stringifiersSym:av,endSym:lv,formatOptsSym:cv,messageKeySym:uv,errorKeySym:dv,nestedKeySym:fv,wildcardFirstSym:gv,needsMetadataGsym:wv,useOnlyCustomLevelsSym:Yb,formattersSym:bv,hooksSym:vv,nestedKeyStrSym:pv,mixinMergeStrategySym:hv,msgPrefixSym:mv}});var Do=H((qC,Xd)=>{"use strict";var Yd=Vd(),{redactFmtSym:xv,wildcardFirstSym:qs}=hn(),Lo=/[^.[\]]+|\[([^[\]]*?)\]/g,Jd="[Redacted]",Qd=!1;function Sv(n,e){let{paths:t,censor:s,remove:r}=_v(n),i=t.reduce((l,c)=>{Lo.lastIndex=0;let d=Lo.exec(c),f=Lo.exec(c),h=d[1]!==void 0?d[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):d[0];if(h==="*"&&(h=qs),f===null)return l[h]=null,l;if(l[h]===null)return l;let{index:m}=f,p=`${c.substr(m,c.length-1)}`;return l[h]=l[h]||[],h!==qs&&l[h].length===0&&l[h].push(...l[qs]||[]),h===qs&&Object.keys(l).forEach(function(g){l[g]&&l[g].push(p)}),l[h].push(p),l},{}),o={[xv]:Yd({paths:t,censor:s,serialize:e,strict:Qd,remove:r})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=d=>a(d,[c]);else{let d=typeof s=="function"?(f,h)=>s(f,[c,...h]):s;l[c]=Yd({paths:i[c],censor:d,serialize:e,strict:Qd,remove:r})}return l},o)}function _v(n){if(Array.isArray(n))return n={paths:n,censor:Jd},n;let{paths:e,censor:t=Jd,remove:s}=n;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(t=void 0),{paths:e,censor:t,remove:s}}Xd.exports=Sv});var tf=H((WC,ef)=>{"use strict";var Av=()=>"",kv=()=>`,"time":${Date.now()}`,$v=()=>`,"time":${Math.round(Date.now()/1e3)}`,Ev=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Cv=1000000n,Zd=1000000000n,Tv=BigInt(Date.now())*Cv,Rv=process.hrtime.bigint(),Ov=()=>{let n=process.hrtime.bigint()-Rv,e=Tv+n,t=e/Zd,s=e%Zd,r=Number(t*1000n+s/1000000n),i=new Date(r),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),d=i.getUTCMinutes().toString().padStart(2,"0"),f=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${d}:${f}.${s.toString().padStart(9,"0")}Z"`};ef.exports={nullTime:Av,epochTime:kv,unixTime:$v,isoTime:Ev,isoTimeNano:Ov}});var sf=H((GC,nf)=>{"use strict";function Pv(n){try{return JSON.stringify(n)}catch{return'"[Circular]"'}}nf.exports=Iv;function Iv(n,e,t){var s=t&&t.stringify||Pv,r=1;if(typeof n=="object"&&n!==null){var i=e.length+r;if(i===1)return n;var o=new Array(i);o[0]=s(n);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof n!="string")return n;var l=e.length;if(l===0)return n;for(var c="",d=1-r,f=-1,h=n&&n.length||0,m=0;m<h;){if(n.charCodeAt(m)===37&&m+1<h){switch(f=f>-1?f:0,n.charCodeAt(m+1)){case 100:case 102:if(d>=l||e[d]==null)break;f<m&&(c+=n.slice(f,m)),c+=Number(e[d]),f=m+2,m++;break;case 105:if(d>=l||e[d]==null)break;f<m&&(c+=n.slice(f,m)),c+=Math.floor(Number(e[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||e[d]===void 0)break;f<m&&(c+=n.slice(f,m));var p=typeof e[d];if(p==="string"){c+="'"+e[d]+"'",f=m+2,m++;break}if(p==="function"){c+=e[d].name||"<anonymous>",f=m+2,m++;break}c+=s(e[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(c+=n.slice(f,m)),c+=String(e[d]),f=m+2,m++;break;case 37:f<m&&(c+=n.slice(f,m)),c+="%",f=m+2,m++,d--;break}++d}++m}return f===-1?n:(f<h&&(c+=n.slice(f)),c)}});var Fo=H((VC,No)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="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(n,0,0,Number(t))},n=new Int32Array(new SharedArrayBuffer(4));No.exports=e}else{let n=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(););};No.exports=n}});var ff=H((zC,df)=>{"use strict";var re=require("fs"),Mv=require("events"),Lv=require("util").inherits,rf=require("path"),jo=Fo(),Dv=require("assert"),Ws=100,Gs=Buffer.allocUnsafe(0),Nv=16*1024,of="buffer",af="utf8",[Fv,Hv]=(process.versions.node||"0.0").split(".").map(Number),jv=Fv>=22&&Hv>=7;function lf(n,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function t(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=n,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&&re.mkdirSync(rf.dirname(n),{recursive:!0});let i=re.openSync(n,s,r);t(null,i)}catch(i){throw t(i),i}else e.mkdir?re.mkdir(rf.dirname(n),{recursive:!0},i=>{if(i)return t(i);re.open(n,s,r,t)}):re.open(n,s,r,t)}function Ze(n){if(!(this instanceof Ze))return new Ze(n);let{fd:e,dest:t,minLength:s,maxLength:r,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:d,fsync:f,contentMode:h,mode:m}=n||{};e=e||t,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||Nv,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=f||!1,this.append=l||!1,this.mode=m,this.retryEAGAIN=d||(()=>!0),this.mkdir=c||!1;let p,g;if(h===of)this._writingBuf=Gs,this.write=Kv,this.flush=Wv,this.flushSync=Vv,this._actualWrite=Yv,p=()=>re.writeSync(this.fd,this._writingBuf),g=()=>re.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===af)this._writingBuf="",this.write=Uv,this.flush=qv,this.flushSync=Gv,this._actualWrite=zv,p=()=>Buffer.isBuffer(this._writingBuf)?re.writeSync(this.fd,this._writingBuf):re.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>Buffer.isBuffer(this._writingBuf)?re.write(this.fd,this._writingBuf,this.release):re.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${af}" and "${of}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")lf(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=(_,A)=>{if(_){if((_.code==="EAGAIN"||_.code==="EBUSY")&&this.retryEAGAIN(_,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{jo(Ws),this.release(void 0,0)}catch(y){this.release(y)}else setTimeout(g,Ws);else this._writing=!1,this.emit("error",_);return}this.emit("write",A);let S=Ho(this._writingBuf,this._len,A);if(this._len=S.len,this._writingBuf=S.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let y=p(),v=Ho(this._writingBuf,this._len,y);this._len=v.len,this._writingBuf=v.writingBuf}while(this._writingBuf.length)}catch(y){this.release(y);return}}this._fsync&&re.fsyncSync(this.fd);let k=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):k>this.minLength?this._actualWrite():this._ending?k>0?this._actualWrite():(this._writing=!1,Vs(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Bv,this)):this.emit("drain"))},this.on("newListener",function(_){_==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Ho(n,e,t){return typeof n=="string"&&(n=Buffer.from(n)),e=Math.max(e-t,0),n=n.subarray(t),{writingBuf:n,len:e}}function Bv(n){n.listenerCount("drain")>0&&(n._asyncDrainScheduled=!1,n.emit("drain"))}Lv(Ze,Mv);function cf(n,e){return n.length===0?Gs:n.length===1?n[0]:Buffer.concat(n,e)}function Uv(n){if(this.destroyed)throw new Error("SonicBoom destroyed");n=""+n;let e=Buffer.byteLength(n),t=this._len+e,s=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(n):s[s.length-1]+=n,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Kv(n){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+n.length,t=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",n),this._len<this._hwm):(t.length===0||s[s.length-1]+n.length>this.maxWrite?(t.push([n]),s.push(n.length)):(t[t.length-1].push(n),s[s.length-1]+=n.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function uf(n){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,n();else try{re.fsync(this.fd,s=>{this._flushPending=!1,n(s)})}catch(s){n(s)}this.off("error",t)},t=s=>{this._flushPending=!1,n(s),this.off("drain",e)};this.once("drain",e),this.once("error",t)}function qv(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&uf.call(this,n),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Wv(n){if(n!=null&&typeof n!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(n){n(e);return}throw e}if(this.minLength<=0){n?.();return}n&&uf.call(this,n),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}Ze.prototype.reopen=function(n){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(n)});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(n&&(this.file=n),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&re.close(e,t=>{if(t)return this.emit("error",t)})}),lf(this.file,this)};Ze.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():Vs(this)))};function Gv(){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 n="";for(;this._bufs.length||n.length;){n.length<=0&&(n=this._bufs[0]);try{let e=Buffer.isBuffer(n)?re.writeSync(this.fd,n):re.writeSync(this.fd,n,"utf8"),t=Ho(n,this._len,e);n=t.writingBuf,this._len=t.len,n.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;jo(Ws)}}try{re.fsyncSync(this.fd)}catch{}}function Vv(){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=Gs);let n=Gs;for(;this._bufs.length||n.length;){n.length<=0&&(n=cf(this._bufs[0],this._lens[0]));try{let e=re.writeSync(this.fd,n);n=n.subarray(e),this._len=Math.max(this._len-e,0),n.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,n.length,this._len-n.length))throw e;jo(Ws)}}}Ze.prototype.destroy=function(){this.destroyed||Vs(this)};function zv(){let n=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)?re.writeSync(this.fd,this._writingBuf):re.writeSync(this.fd,this._writingBuf,"utf8");n(null,e)}catch(e){n(e)}else re.write(this.fd,this._writingBuf,n)}function Yv(){let n=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:cf(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=re.writeSync(this.fd,this._writingBuf);n(null,e)}catch(e){n(e)}else jv&&(this._writingBuf=Buffer.from(this._writingBuf)),re.write(this.fd,this._writingBuf,n)}function Vs(n){if(n.fd===-1){n.once("ready",Vs.bind(null,n));return}n._periodicFlushTimer!==void 0&&clearInterval(n._periodicFlushTimer),n.destroyed=!0,n._bufs=[],n._lens=[],Dv(typeof n.fd=="number",`sonic.fd must be a number, got ${typeof n.fd}`);try{re.fsync(n.fd,e)}catch{}function e(){n.fd!==1&&n.fd!==2?re.close(n.fd,t):t()}function t(s){if(s){n.emit("error",s);return}n._ending&&!n._writing&&n.emit("finish"),n.emit("close")}}Ze.SonicBoom=Ze;Ze.default=Ze;df.exports=Ze});var Bo=H((YC,yf)=>{"use strict";var et={exit:[],beforeExit:[]},pf={exit:Xv,beforeExit:Zv},mn;function Jv(){mn===void 0&&(mn=new FinalizationRegistry(ew))}function Qv(n){et[n].length>0||process.on(n,pf[n])}function hf(n){et[n].length>0||(process.removeListener(n,pf[n]),et.exit.length===0&&et.beforeExit.length===0&&(mn=void 0))}function Xv(){mf("exit")}function Zv(){mf("beforeExit")}function mf(n){for(let e of et[n]){let t=e.deref(),s=e.fn;t!==void 0&&s(t,n)}et[n]=[]}function ew(n){for(let e of["exit","beforeExit"]){let t=et[e].indexOf(n);et[e].splice(t,t+1),hf(e)}}function gf(n,e,t){if(e===void 0)throw new Error("the object can't be undefined");Qv(n);let s=new WeakRef(e);s.fn=t,Jv(),mn.register(e,s),et[n].push(s)}function tw(n,e){gf("exit",n,e)}function nw(n,e){gf("beforeExit",n,e)}function sw(n){if(mn!==void 0){mn.unregister(n);for(let e of["exit","beforeExit"])et[e]=et[e].filter(t=>{let s=t.deref();return s&&s!==n}),hf(e)}}yf.exports={register:tw,registerBeforeExit:nw,unregister:sw}});var bf=H((JC,rw)=>{rw.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 wf=H((QC,vf)=>{"use strict";function iw(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(n,e);if(a===t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(n,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function ow(n,e,t,s,r){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(n,e)!==t){r(null,"ok");return}if(i!==1/0&&Date.now()>i){r(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(n,e,t,l);c.async?c.value.then(d=>{if(d==="ok"){r(null,"ok");return}o()}):setImmediate(o)};o()}vf.exports={wait:iw,waitDiff:ow}});var Sf=H((XC,xf)=>{"use strict";xf.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Mf=H((ZC,If)=>{"use strict";var{version:aw}=bf(),{EventEmitter:lw}=require("events"),{Worker:cw}=require("worker_threads"),{join:uw}=require("path"),{pathToFileURL:dw}=require("url"),{wait:fw}=wf(),{WRITE_INDEX:St,READ_INDEX:qt,SEQ_INDEX:Uo}=Sf(),pw=require("buffer"),hw=require("assert"),R=Symbol("kImpl"),mw=pw.constants.MAX_STRING_LENGTH;function _f(){}function Go(n,e){Atomics.add(n[R].state,Uo,1),e(),Atomics.add(n[R].state,Uo,1),Atomics.notify(n[R].state,Uo)}function Af(n){Go(n,()=>{Atomics.store(n[R].state,qt,0),Atomics.store(n[R].state,St,0)})}var Kn=class{constructor(e){this._value=e}deref(){return this._value}},zs=class{register(){}unregister(){}},gw=process.env.NODE_V8_COVERAGE?zs:global.FinalizationRegistry||zs,yw=process.env.NODE_V8_COVERAGE?Kn:global.WeakRef||Kn,kf=new gw(n=>{n.exited||n.terminate()});function bw(n,e){let{filename:t,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||uw(__dirname,"lib","worker.js"),o=new cw(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:t.indexOf("file://")===0?t:dw(t).href,dataBuf:n[R].dataBuf,stateBuf:n[R].stateBuf,workerData:{$context:{threadStreamVersion:aw},...s}}});return o.stream=new Kn(n),o.on("message",vw),o.on("exit",Cf),kf.register(n,o),o}function $f(n){hw(!n[R].sync),n[R].needDrain&&(n[R].needDrain=!1,n.emit("drain"))}function Ef(n){for(;;){let e=Atomics.load(n[R].state,St),t=n[R].data.length-e;if(t>0){if(n[R].bufLen===0){n[R].flushing=!1,n[R].ending?Vo(n):n[R].needDrain&&process.nextTick($f,n);return}Of(n,t,_f);continue}if(t===0){if(e===0&&n[R].bufLen===0)return;Ys(n,()=>{n.destroyed||(Af(n),Ef(n))});return}qe(n,new Error("overwritten"));return}}function vw(n){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(n?.code!=null)switch(n.code){case"READY":this.stream=new yw(e),Ys(e,()=>{e[R].ready=!0,e.emit("ready")});break;case"ERROR":qe(e,n.err);break;case"EVENT":Array.isArray(n.args)?e.emit(n.name,...n.args):e.emit(n.name,n.args);break;case"FLUSHED":{if(n.context!=="thread-stream"){qe(e,new Error("this should not happen: "+n.code));break}let t=e[R].flushCallbacks.get(n.id);t&&(e[R].flushCallbacks.delete(n.id),process.nextTick(t));break}case"WARNING":process.emitWarning(n.err);break;default:qe(e,new Error("this should not happen: "+n.code))}}function Cf(n){let e=this.stream.deref();e!==void 0&&(kf.unregister(e),e.worker.exited=!0,e.worker.off("exit",Cf),qe(e,n!==0?new Error("the worker thread exited"):null))}var qo=class extends lw{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[R]={},this[R].stateBuf=new SharedArrayBuffer(128),this[R].state=new Int32Array(this[R].stateBuf),this[R].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[R].data=Buffer.from(this[R].dataBuf),this[R].sync=e.sync||!1,this[R].ending=!1,this[R].ended=!1,this[R].needDrain=!1,this[R].destroyed=!1,this[R].flushing=!1,this[R].ready=!1,this[R].finished=!1,this[R].errored=null,this[R].closed=!1,this[R].buf=[],this[R].bufHead=0,this[R].bufLen=0,this[R].flushCallbacks=new Map,this[R].nextFlushId=0,this.worker=bw(this,e),this.on("message",(t,s)=>{this.worker.postMessage(t,s)})}write(e){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[R].destroyed)return Wo(this,new Error("the worker has exited")),!1;if(this[R].ending)return Wo(this,new Error("the worker is ending")),!1;if(this[R].flushing&&this[R].bufLen+t.length>=mw)try{Ko(this),this[R].flushing=!0}catch(s){return qe(this,s),!1}if(this[R].buf.push(t),this[R].bufLen+=t.length,this[R].sync)try{return Ko(this),!0}catch(s){return qe(this,s),!1}return this[R].flushing||(this[R].flushing=!0,setImmediate(Ef,this)),this[R].needDrain=this[R].data.length-this[R].bufLen-Atomics.load(this[R].state,St)<=0,!this[R].needDrain}end(){this[R].destroyed||(this[R].ending=!0,Vo(this))}flush(e){e=typeof e=="function"?e:_f,Tf(this,t=>{if(t){process.nextTick(e,t);return}Rf(this,e)})}flushSync(){this[R].destroyed||(Ko(this),Pf(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[R].ready}get destroyed(){return this[R].destroyed}get closed(){return this[R].closed}get writable(){return!this[R].destroyed&&!this[R].ending}get writableEnded(){return this[R].ending}get writableFinished(){return this[R].finished}get writableNeedDrain(){return this[R].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[R].errored}};function Tf(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].sync&&(n[R].flushing||n[R].bufLen>0)){setImmediate(Tf,n,e);return}Ys(n,e)}function Ys(n,e){let t=Atomics.load(n[R].state,St);fw(n[R].state,qt,t,1/0,(s,r)=>{if(s){qe(n,s),e(s);return}if(r!=="ok"){Ys(n,e);return}e()})}function Rf(n,e){if(n[R].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!n[R].ready){let s=()=>{i(),Rf(n,e)},r=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{n.off("ready",s),n.off("close",r)};n.once("ready",s),n.once("close",r);return}let t=++n[R].nextFlushId;n[R].flushCallbacks.set(t,e);try{n.worker.postMessage({code:"FLUSH",context:"thread-stream",id:t})}catch(s){n[R].flushCallbacks.delete(t),qe(n,s),process.nextTick(e,s)}}function ww(n,e){let t=n[R].flushCallbacks;if(t.size===0)return;let s=e||new Error("the worker has exited");for(let r of t.values())process.nextTick(r,s);t.clear()}function Wo(n,e){setImmediate(()=>{n.emit("error",e)})}function qe(n,e){n[R].destroyed||(n[R].destroyed=!0,ww(n,e),e&&(n[R].errored=e,Wo(n,e)),n.worker.exited?setImmediate(()=>{n[R].closed=!0,n.emit("close")}):n.worker.terminate().catch(()=>{}).then(()=>{n[R].closed=!0,n.emit("close")}))}function Of(n,e,t){let r=Atomics.load(n[R].state,St),i=e;for(;i>0&&n[R].bufLen!==0;){let o=n[R].bufHead,a=n[R].buf[o];if(a.length<=i){a.copy(n[R].data,r),r+=a.length,i-=a.length,n[R].bufLen-=a.length,n[R].bufHead=o+1,n[R].bufHead===n[R].buf.length?(n[R].buf.length=0,n[R].bufHead=0):n[R].bufHead>=1024&&n[R].bufHead*2>=n[R].buf.length&&(n[R].buf.splice(0,n[R].bufHead),n[R].bufHead=0);continue}a.copy(n[R].data,r,0,i),n[R].buf[o]=a.subarray(i),n[R].bufLen-=i,r+=i,i=0}return Go(n,()=>{Atomics.store(n[R].state,St,r)}),t(),!0}function Vo(n){if(!(n[R].ended||!n[R].ending||n[R].flushing)){n[R].ended=!0;try{n.flushSync();let e=Atomics.load(n[R].state,qt);Go(n,()=>{Atomics.store(n[R].state,St,-1)});let t=0;for(;e!==-1;){if(Atomics.wait(n[R].state,qt,e,1e3),e=Atomics.load(n[R].state,qt),e===-2){qe(n,new Error("end() failed"));return}if(++t===10){qe(n,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{n[R].finished=!0,n.emit("finish")})}catch(e){qe(n,e)}}}function Ko(n){let e=()=>{n[R].ending?Vo(n):n[R].needDrain&&process.nextTick($f,n)};for(n[R].flushing=!1;n[R].bufLen!==0;){let t=Atomics.load(n[R].state,St),s=n[R].data.length-t;if(s===0){Pf(n),Af(n);continue}else if(s<0)throw new Error("overwritten");Of(n,s,e)}}function Pf(n){if(n[R].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(n[R].state,St),t=0;for(;;){let s=Atomics.load(n[R].state,qt);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(n[R].state,qt,s,1e3);else break;if(++t===10)throw new Error("_flushSync took too long (10s)")}}If.exports=qo});var Jo=H((eT,Nf)=>{"use strict";var{createRequire:xw}=require("module"),{existsSync:Sw}=require("node:fs"),_w=Io(),{join:zo,isAbsolute:Df,sep:Aw}=require("node:path"),{fileURLToPath:kw}=require("node:url"),$w=Fo(),Yo=Bo(),Ew=Mf();function Cw(n){Yo.register(n,Iw),Yo.registerBeforeExit(n,Mw),n.on("close",function(){Yo.unregister(n)})}function Tw(){let n=process.execArgv;for(let e=0;e<n.length;e++){let t=n[e];if(t==="--import"||t==="--require"||t==="-r"||t.startsWith("--import=")||t.startsWith("--require=")||t.startsWith("-r="))return!0}return!1}function Rw(n){let e=n.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return n;let t=[],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&&Lf(o)){s=!0,r++;continue}t.push(i),o&&(t.push(o),r++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Lf(o)){s=!0;continue}}t.push(i)}return s?t.join(" "):n}function Lf(n){let e=Ow(n);if(!e)return!1;let t=e;if(t.startsWith("file://"))try{t=kw(t)}catch{return!1}return Df(t)&&!Sw(t)}function Ow(n){let e=n[0],t=n[n.length-1];return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function Pw(n,e,t,s,r){if(!t.execArgv&&Tw()&&require.main===void 0&&(t={...t,execArgv:[]}),!t.env&&process.env.NODE_OPTIONS){let l=Rw(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(t={...t,env:{...process.env,NODE_OPTIONS:l}})}t={...t,name:r};let i=new Ew({filename:n,workerData:e,workerOpts:t,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(),t.autoEnd!==!1&&Cw(i)}function a(){i.closed||(i.flushSync(),$w(100),i.end())}return i}function Iw(n){n.ref(),n.flushSync(),n.end(),n.once("close",function(){n.unref()})}function Mw(n){n.flushSync()}function Lw(n){let{pipeline:e,targets:t,levels:s,dedupe:r,worker:i={},caller:o=_w(),sync:a=!1}=n,l={...n.options},c=typeof o=="string"?[o]:o,d=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),f=n.target;if(f&&t)throw new Error("only one of target or targets can be specified");t?(f=d["pino-worker"]||zo(__dirname,"worker.js"),l.targets=t.filter(p=>p.target).map(p=>({...p,target:m(p.target)})),l.pipelines=t.filter(p=>p.pipeline).map(p=>p.pipeline.map(g=>({...g,level:p.level,target:m(g.target)})))):e&&(f=d["pino-worker"]||zo(__dirname,"worker.js"),l.pipelines=[e.map(p=>({...p,target:m(p.target)}))]),s&&(l.levels=s),r&&(l.dedupe=r),l.pinoWillSendConfig=!0;let h=t||e?"pino.transport":f;return Pw(m(f),l,i,a,h);function m(p){if(p=d[p]||p,Df(p)||p.indexOf("file://")===0)return p;if(p==="pino/file")return zo(__dirname,"..","file.js");let g;for(let _ of c)try{let A=_==="node:repl"?process.cwd()+Aw:_;g=xw(A).resolve(p);break}catch{continue}if(!g)throw new Error(`unable to determine transport target for "${p}"`);return g}}Nf.exports=Lw});var Xs=H((tT,Jf)=>{"use strict";var Dw=require("node:diagnostics_channel"),Ff=sf(),{mapHttpRequest:Nw,mapHttpResponse:Fw}=Po(),Xo=ff(),Hf=Bo(),{lsCacheSym:Hw,chindingsSym:qf,writeSym:jf,serializersSym:Wf,formatOptsSym:Bf,endSym:jw,stringifiersSym:Gf,stringifySym:Vf,stringifySafeSym:Zo,wildcardFirstSym:zf,nestedKeySym:Bw,formattersSym:Yf,messageKeySym:Uw,errorKeySym:Kw,nestedKeyStrSym:qw,msgPrefixSym:Js}=hn(),{isMainThread:Ww}=require("worker_threads"),Gw=Jo(),[Vw]=process.versions.node.split(".").map(n=>Number(n)),Uf=Dw.tracingChannel("pino_asJson"),Qo=Vw>=25?n=>JSON.stringify(n):Yw;function gn(){}function zw(n,e){if(!e)return t;return function(...r){e.call(this,r,t,n)};function t(s,...r){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=Nw(s):typeof s.setHeader=="function"&&(s=Fw(s)));let o;i===null&&r.length===0?o=[null]:(i=r.shift(),o=r),typeof this[Js]=="string"&&i!==void 0&&i!==null&&(i=this[Js]+i),this[jf](s,Ff(i,o,this[Bf]),n)}else{let i=s===void 0?r.shift():s;typeof this[Js]=="string"&&i!==void 0&&i!==null&&(i=this[Js]+i),this[jf](null,Ff(i,r,this[Bf]),n)}}}function Yw(n){let e="",t=0,s=!1,r=255,i=n.length;if(i>100)return JSON.stringify(n);for(var o=0;o<i&&r>=32;o++)r=n.charCodeAt(o),(r===34||r===92)&&(e+=n.slice(t,o)+"\\",t=o,s=!0);return s?e+=n.slice(t):e=n,r<32?JSON.stringify(n):'"'+e+'"'}function Jw(n,e,t,s){if(Uf.hasSubscribers===!1)return Kf.call(this,n,e,t,s);let r={instance:this,arguments};return Uf.traceSync(Kf,r,this,n,e,t,s)}function Kf(n,e,t,s){let r=this[Vf],i=this[Zo],o=this[Gf],a=this[jw],l=this[qf],c=this[Wf],d=this[Yf],f=this[Uw],h=this[Kw],m=this[Hw][t]+s;m=m+l;let p;d.log&&(n=d.log(n));let g=o[zf],_="";for(let S in n)if(p=n[S],Object.prototype.hasOwnProperty.call(n,S)&&p!==void 0){c[S]?p=c[S](p):S===h&&c.err&&(p=c.err(p));let k=o[S]||g;switch(typeof p){case"undefined":case"function":continue;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":k&&(p=k(p));break;case"string":p=(k||Qo)(p);break;default:p=(k||r)(p,i)}if(p===void 0)continue;let y=Qo(S);_+=","+y+":"+p}let A="";if(e!==void 0){p=c[f]?c[f](e):e;let S=o[f]||g;switch(typeof p){case"function":break;case"number":Number.isFinite(p)===!1&&(p=null);case"boolean":S&&(p=S(p)),A=',"'+f+'":'+p;break;case"string":p=(S||Qo)(p),A=',"'+f+'":'+p;break;default:p=(S||r)(p,i),A=',"'+f+'":'+p}}return this[Bw]&&_?m+this[qw]+_.slice(1)+"}"+A+a:m+_+A+a}function Qw(n,e){let t,s=n[qf],r=n[Vf],i=n[Zo],o=n[Gf],a=o[zf],l=n[Wf],c=n[Yf].bindings;e=c(e);for(let d in e)if(t=e[d],((d.length<5||d!=="level"&&d!=="serializers"&&d!=="formatters"&&d!=="customLevels")&&e.hasOwnProperty(d)&&t!==void 0)===!0){if(t=l[d]?l[d](t):t,t=(o[d]||a||r)(t,i),t===void 0)continue;s+=',"'+d+'":'+t}return s}function Xw(n){return n.write!==n.constructor.prototype.write}function Qs(n){let e=new Xo(n);return e.on("error",t),!n.sync&&Ww&&(Hf.register(e,Zw),e.on("close",function(){Hf.unregister(e)})),e;function t(s){if(s.code==="EPIPE"){e.write=gn,e.end=gn,e.flushSync=gn,e.destroy=gn;return}e.removeListener("error",t),e.emit("error",s)}}function Zw(n,e){n.destroyed||(e==="beforeExit"?(n.flush(),n.on("drain",function(){n.end()})):n.flushSync())}function ex(n){return function(t,s,r={},i){if(typeof r=="string")i=Qs({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=Qs({dest:i})}else if(r instanceof Xo||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof Xo||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 l;r.customLevels&&(l=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=Gw({caller:s,...r.transport,levels:l})}if(r=Object.assign({},n,r),r.serializers=Object.assign({},n.serializers,r.serializers),r.formatters=Object.assign({},n.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=gn),i||(Xw(process.stdout)?i=process.stdout:i=Qs({fd:process.stdout.fd||1})),{opts:r,stream:i}}}function tx(n,e){try{return JSON.stringify(n)}catch{try{return(e||this[Zo])(n)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function nx(n,e,t){return{level:n,bindings:e,log:t}}function sx(n){let e=Number(n);return typeof n=="string"&&Number.isFinite(e)?e:n===void 0?1:n}Jf.exports={noop:gn,buildSafeSonicBoom:Qs,asChindings:Qw,asJson:Jw,genLog:zw,createArgsNormalizer:ex,stringify:tx,buildFormatters:nx,normalizeDestFileDescriptor:sx}});var Zs=H((nT,Qf)=>{var rx={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ix={ASC:"ASC",DESC:"DESC"};Qf.exports={DEFAULT_LEVELS:rx,SORTING_ORDER:ix}});var na=H((sT,tp)=>{"use strict";var{lsCacheSym:ox,levelValSym:ea,useOnlyCustomLevelsSym:ax,streamSym:lx,formattersSym:cx,hooksSym:ux,levelCompSym:Xf}=hn(),{noop:dx,genLog:Wt}=Xs(),{DEFAULT_LEVELS:lt,SORTING_ORDER:Zf}=Zs(),ep={fatal:n=>{let e=Wt(lt.fatal,n);return function(...t){let s=this[lx];if(e.call(this,...t),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:n=>Wt(lt.error,n),warn:n=>Wt(lt.warn,n),info:n=>Wt(lt.info,n),debug:n=>Wt(lt.debug,n),trace:n=>Wt(lt.trace,n)},ta=Object.keys(lt).reduce((n,e)=>(n[lt[e]]=e,n),{}),fx=Object.keys(ta).reduce((n,e)=>(n[e]='{"level":'+Number(e),n),{});function px(n){let e=n[cx].level,{labels:t}=n.levels,s={};for(let r in t){let i=e(t[r],Number(r));s[r]=JSON.stringify(i).slice(0,-1)}return n[ox]=s,n}function hx(n,e){if(e)return!1;switch(n){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function mx(n){let{labels:e,values:t}=this.levels;if(typeof n=="number"){if(e[n]===void 0)throw Error("unknown level value"+n);n=e[n]}if(t[n]===void 0)throw Error("unknown level "+n);let s=this[ea],r=this[ea]=t[n],i=this[ax],o=this[Xf],a=this[ux].logMethod;for(let l in t){if(o(t[l],r)===!1){this[l]=dx;continue}this[l]=hx(l,i)?ep[l](a):Wt(t[l],a)}this.emit("level-change",n,r,e[s],s,this)}function gx(n){let{levels:e,levelVal:t}=this;return e&&e.labels?e.labels[t]:""}function yx(n){let{values:e}=this.levels,t=e[n];return t!==void 0&&this[Xf](t,this[ea])}function bx(n,e,t){return n===Zf.DESC?e<=t:e>=t}function vx(n){return typeof n=="string"?bx.bind(null,n):n}function wx(n=null,e=!1){let t=n?Object.keys(n).reduce((i,o)=>(i[n[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:ta,t),r=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:lt,n);return{labels:s,values:r}}function xx(n,e,t){if(typeof n=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),t?[]:Object.keys(ta).map(i=>+i),1/0).includes(n))throw Error(`default level:${n} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:lt,e);if(!(n in s))throw Error(`default level:${n} must be included in custom levels`)}function Sx(n,e){let{labels:t,values:s}=n;for(let r in e){if(r in s)throw Error("levels cannot be overridden");if(e[r]in t)throw Error("pre-existing level values cannot be used for new levels")}}function _x(n){if(typeof n!="function"&&!(typeof n=="string"&&Object.values(Zf).includes(n)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}tp.exports={initialLsCache:fx,genLsCache:px,levelMethods:ep,getLevel:gx,setLevel:mx,isLevelEnabled:yx,mappings:wx,assertNoLevelCollisions:Sx,assertDefaultLevelFound:xx,genLevelComparison:vx,assertLevelComparison:_x}});var sa=H((rT,np)=>{"use strict";np.exports={version:"10.3.1"}});var up=H((oT,cp)=>{"use strict";var{EventEmitter:Ax}=require("node:events"),{lsCacheSym:kx,levelValSym:$x,setLevelSym:ia,getLevelSym:sp,chindingsSym:tr,mixinSym:Ex,asJsonSym:ip,writeSym:Cx,mixinMergeStrategySym:Tx,timeSym:Rx,timeSliceIndexSym:Ox,streamSym:op,serializersSym:Gt,formattersSym:qn,errorKeySym:Px,messageKeySym:Ix,useOnlyCustomLevelsSym:Mx,needsMetadataGsym:Lx,redactFmtSym:Dx,stringifySym:Nx,formatOptsSym:Fx,stringifiersSym:Hx,msgPrefixSym:oa,hooksSym:jx}=hn(),{getLevel:Bx,setLevel:Ux,isLevelEnabled:Kx,mappings:qx,initialLsCache:Wx,genLsCache:Gx,assertNoLevelCollisions:Vx}=na(),{asChindings:aa,asJson:zx,buildFormatters:ra,stringify:rp,noop:ap}=Xs(),{version:Yx}=sa(),Jx=Do(),Qx=class{},lp={constructor:Qx,child:Xx,bindings:Zx,setBindings:eS,flush:sS,isLevelEnabled:Kx,version:Yx,get level(){return this[sp]()},set level(n){this[ia](n)},get levelVal(){return this[$x]},set levelVal(n){throw Error("levelVal is read-only")},get msgPrefix(){return this[oa]},get[Symbol.toStringTag](){return"Pino"},[kx]:Wx,[Cx]:nS,[ip]:zx,[sp]:Bx,[ia]:Ux};Object.setPrototypeOf(lp,Ax.prototype);cp.exports=function(){return Object.create(lp)};var er=n=>n;function Xx(n,e){if(!n)throw Error("missing bindings for child Pino");let t=this[Gt],s=this[qn],r=Object.create(this);if(e==null)return r[qn].bindings!==er&&(r[qn]=ra(s.level,er,s.log)),r[tr]=aa(r,n),this.onChild!==ap&&this.onChild(r),r;if(e.hasOwnProperty("serializers")===!0){r[Gt]=Object.create(null);for(let c in t)r[Gt][c]=t[c];let a=Object.getOwnPropertySymbols(t);for(var i=0;i<a.length;i++){let c=a[i];r[Gt][c]=t[c]}for(let c in e.serializers)r[Gt][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];r[Gt][c]=e.serializers[c]}}else r[Gt]=t;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;r[qn]=ra(a||s.level,l||er,c||s.log)}else r[qn]=ra(s.level,er,s.log);if(e.hasOwnProperty("customLevels")===!0&&(Vx(this.levels,e.customLevels),r.levels=qx(e.customLevels,r[Mx]),Gx(r)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){r.redact=e.redact;let a=Jx(r.redact,rp),l={stringify:a[Dx]};r[Nx]=rp,r[Hx]=a,r[Fx]=l}if(typeof e.msgPrefix=="string"&&(r[oa]=(this[oa]||"")+e.msgPrefix),r[tr]=aa(r,n),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;r[ia](a)}return this.onChild(r),r}function Zx(){let e=`{${this[tr].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function eS(n){let e=aa(this,n);this[tr]=e}function tS(n,e){return Object.assign(e,n)}function nS(n,e,t){let s=this[Rx](),r=this[Ex],i=this[Px],o=this[Ix],a=this[Tx]||tS,l,c=this[jx].streamWrite;n==null?l={}:n instanceof Error?(l={[i]:n},e===void 0&&(e=n.message)):(l=n,e===void 0&&n[o]===void 0&&n[i]&&(e=n[i].message)),r&&(l=a(l,r(l,t,this)));let d=this[ip](l,e,t,s),f=this[op];f[Lx]===!0&&(f.lastLevel=t,f.lastObj=l,f.lastMsg=e,f.lastTime=s.slice(this[Ox]),f.lastLogger=this),f.write(c?c(d):d)}function sS(n){if(n!=null&&typeof n!="function")throw Error("callback must be a function");let e=this[op];typeof e.flush=="function"?e.flush(n||ap):n&&n()}});var hp=H((da,pp)=>{"use strict";var{hasOwnProperty:Wn}=Object.prototype,zt=ua();zt.configure=ua;zt.stringify=zt;zt.default=zt;da.stringify=zt;da.configure=ua;pp.exports=zt;var rS=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function It(n){return n.length<5e3&&!rS.test(n)?`"${n}"`:JSON.stringify(n)}function la(n,e){if(n.length>200||e)return n.sort(e);for(let t=1;t<n.length;t++){let s=n[t],r=t;for(;r!==0&&n[r-1]>s;)n[r]=n[r-1],r--;n[r]=s}return n}var iS=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ca(n){return iS.call(n)!==void 0&&n.length!==0}function dp(n,e,t){n.length<t&&(t=n.length);let s=e===","?"":" ",r=`"0":${s}${n[0]}`;for(let i=1;i<t;i++)r+=`${e}"${i}":${s}${n[i]}`;return r}function oS(n){if(Wn.call(n,"circularValue")){let e=n.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 aS(n){let e;if(Wn.call(n,"deterministic")&&(e=n.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 lS(n,e){let t;if(Wn.call(n,e)&&(t=n[e],typeof t!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return t===void 0?!0:t}function fp(n,e){let t;if(Wn.call(n,e)){if(t=n[e],typeof t!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(t))throw new TypeError(`The "${e}" argument must be an integer`);if(t<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return t===void 0?1/0:t}function Vt(n){return n===1?"1 item":`${n} items`}function cS(n){let e=new Set;for(let t of n)(typeof t=="string"||typeof t=="number")&&e.add(String(t));return e}function uS(n){if(Wn.call(n,"strict")){let e=n.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return t=>{let s=`Object can not safely be stringified. Received type ${typeof t}`;throw typeof t!="function"&&(s+=` (${t.toString()})`),new Error(s)}}}function ua(n){n={...n};let e=uS(n);e&&(n.bigint===void 0&&(n.bigint=!1),"circularValue"in n||(n.circularValue=Error));let t=oS(n),s=lS(n,"bigint"),r=aS(n),i=typeof r=="function"?r:void 0,o=fp(n,"maximumDepth"),a=fp(n,"maximumBreadth");function l(m,p,g,_,A,S){let k=p[m];switch(typeof k=="object"&&k!==null&&typeof k.toJSON=="function"&&(k=k.toJSON(m)),k=_.call(p,m,k),typeof k){case"string":return It(k);case"object":{if(k===null)return"null";if(g.indexOf(k)!==-1)return t;let y="",v=",",b=S;if(Array.isArray(k)){if(k.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(k),A!==""&&(S+=A,y+=`
|
|
696
|
+
${S}`,v=`,
|
|
697
|
+
${S}`);let F=Math.min(k.length,a),j=0;for(;j<F-1;j++){let C=l(String(j),k,g,_,A,S);y+=C!==void 0?C:"null",y+=v}let z=l(String(j),k,g,_,A,S);if(y+=z!==void 0?z:"null",k.length-1>a){let C=k.length-a-1;y+=`${v}"... ${Vt(C)} not stringified"`}return A!==""&&(y+=`
|
|
698
|
+
${b}`),g.pop(),`[${y}]`}let w=Object.keys(k),x=w.length;if(x===0)return"{}";if(o<g.length+1)return'"[Object]"';let T="",L="";A!==""&&(S+=A,v=`,
|
|
699
|
+
${S}`,T=" ");let $=Math.min(x,a);r&&!ca(k)&&(w=la(w,i)),g.push(k);for(let F=0;F<$;F++){let j=w[F],z=l(j,k,g,_,A,S);z!==void 0&&(y+=`${L}${It(j)}:${T}${z}`,L=v)}if(x>a){let F=x-a;y+=`${L}"...":${T}"${Vt(F)} not stringified"`,L=v}return A!==""&&L.length>1&&(y=`
|
|
700
|
+
${S}${y}
|
|
701
|
+
${b}`),g.pop(),`{${y}}`}case"number":return isFinite(k)?String(k):e?e(k):"null";case"boolean":return k===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(k);default:return e?e(k):void 0}}function c(m,p,g,_,A,S){switch(typeof p=="object"&&p!==null&&typeof p.toJSON=="function"&&(p=p.toJSON(m)),typeof p){case"string":return It(p);case"object":{if(p===null)return"null";if(g.indexOf(p)!==-1)return t;let k=S,y="",v=",";if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),A!==""&&(S+=A,y+=`
|
|
702
|
+
${S}`,v=`,
|
|
703
|
+
${S}`);let x=Math.min(p.length,a),T=0;for(;T<x-1;T++){let $=c(String(T),p[T],g,_,A,S);y+=$!==void 0?$:"null",y+=v}let L=c(String(T),p[T],g,_,A,S);if(y+=L!==void 0?L:"null",p.length-1>a){let $=p.length-a-1;y+=`${v}"... ${Vt($)} not stringified"`}return A!==""&&(y+=`
|
|
704
|
+
${k}`),g.pop(),`[${y}]`}g.push(p);let b="";A!==""&&(S+=A,v=`,
|
|
705
|
+
${S}`,b=" ");let w="";for(let x of _){let T=c(x,p[x],g,_,A,S);T!==void 0&&(y+=`${w}${It(x)}:${b}${T}`,w=v)}return A!==""&&w.length>1&&(y=`
|
|
706
|
+
${S}${y}
|
|
707
|
+
${k}`),g.pop(),`{${y}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function d(m,p,g,_,A){switch(typeof p){case"string":return It(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return d(m,p,g,_,A);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let S=A;if(Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p),A+=_;let T=`
|
|
708
|
+
${A}`,L=`,
|
|
709
|
+
${A}`,$=Math.min(p.length,a),F=0;for(;F<$-1;F++){let z=d(String(F),p[F],g,_,A);T+=z!==void 0?z:"null",T+=L}let j=d(String(F),p[F],g,_,A);if(T+=j!==void 0?j:"null",p.length-1>a){let z=p.length-a-1;T+=`${L}"... ${Vt(z)} not stringified"`}return T+=`
|
|
710
|
+
${S}`,g.pop(),`[${T}]`}let k=Object.keys(p),y=k.length;if(y===0)return"{}";if(o<g.length+1)return'"[Object]"';A+=_;let v=`,
|
|
711
|
+
${A}`,b="",w="",x=Math.min(y,a);ca(p)&&(b+=dp(p,v,a),k=k.slice(p.length),x-=p.length,w=v),r&&(k=la(k,i)),g.push(p);for(let T=0;T<x;T++){let L=k[T],$=d(L,p[L],g,_,A);$!==void 0&&(b+=`${w}${It(L)}: ${$}`,w=v)}if(y>a){let T=y-a;b+=`${w}"...": "${Vt(T)} not stringified"`,w=v}return w!==""&&(b=`
|
|
733
712
|
${A}${b}
|
|
734
|
-
${
|
|
713
|
+
${S}`),g.pop(),`{${b}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function f(m,p,g){switch(typeof p){case"string":return It(p);case"object":{if(p===null)return"null";if(typeof p.toJSON=="function"){if(p=p.toJSON(m),typeof p!="object")return f(m,p,g);if(p===null)return"null"}if(g.indexOf(p)!==-1)return t;let _="",A=p.length!==void 0;if(A&&Array.isArray(p)){if(p.length===0)return"[]";if(o<g.length+1)return'"[Array]"';g.push(p);let b=Math.min(p.length,a),w=0;for(;w<b-1;w++){let T=f(String(w),p[w],g);_+=T!==void 0?T:"null",_+=","}let x=f(String(w),p[w],g);if(_+=x!==void 0?x:"null",p.length-1>a){let T=p.length-a-1;_+=`,"... ${Vt(T)} not stringified"`}return g.pop(),`[${_}]`}let S=Object.keys(p),k=S.length;if(k===0)return"{}";if(o<g.length+1)return'"[Object]"';let y="",v=Math.min(k,a);A&&ca(p)&&(_+=dp(p,",",a),S=S.slice(p.length),v-=p.length,y=","),r&&(S=la(S,i)),g.push(p);for(let b=0;b<v;b++){let w=S[b],x=f(w,p[w],g);x!==void 0&&(_+=`${y}${It(w)}:${x}`,y=",")}if(k>a){let b=k-a;_+=`${y}"...":"${Vt(b)} not stringified"`}return g.pop(),`{${_}}`}case"number":return isFinite(p)?String(p):e?e(p):"null";case"boolean":return p===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(p);default:return e?e(p):void 0}}function h(m,p,g){if(arguments.length>1){let _="";if(typeof g=="number"?_=" ".repeat(Math.min(g,10)):typeof g=="string"&&(_=g.slice(0,10)),p!=null){if(typeof p=="function")return l("",{"":m},[],p,_,"");if(Array.isArray(p))return c("",m,[],cS(p),_,"")}if(_.length!==0)return d("",m,[],_,"")}return f("",m,[])}return h}});var bp=H((aT,yp)=>{"use strict";var fa=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:gp}=Zs(),dS=gp.info;function fS(n,e){n=n||[],e=e||{dedupe:!1};let t=Object.create(gp);t.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(f=>{t[f]=e.levels[f]});let s={write:r,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:d,[fa]:!0,streamLevels:t};return Array.isArray(n)?n.forEach(a,s):a.call(s,n),n=null,s;function r(f){let h,m=this.lastLevel,{streams:p}=this,g=0,_;for(let A=pS(p.length,e.dedupe);mS(A,p.length,e.dedupe);A=hS(A,e.dedupe))if(h=p[A],h.level<=m){if(g!==0&&g!==h.level)break;if(_=h.stream,_[fa]){let{lastTime:S,lastMsg:k,lastObj:y,lastLogger:v}=this;_.lastLevel=m,_.lastTime=S,_.lastMsg=k,_.lastObj=y,_.lastLogger=v}_.write(f),e.dedupe&&(g=h.level)}else if(!e.dedupe)break}function i(...f){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...f)}function o(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync()}function a(f){if(!f)return s;let h=typeof f.write=="function"||f.stream,m=f.write?f:f.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:p,streamLevels:g}=this,_;typeof f.levelVal=="number"?_=f.levelVal:typeof f.level=="string"?_=g[f.level]:typeof f.level=="number"?_=f.level:_=dS;let A={stream:m,level:_,levelVal:void 0,id:++s.lastId};return p.unshift(A),p.sort(mp),this.minLevel=p[0].level,s}function l(f){let{streams:h}=this,m=h.findIndex(p=>p.id===f);return m>=0&&(h.splice(m,1),h.sort(mp),this.minLevel=h.length>0?h[0].level:-1),s}function c(){for(let{stream:f}of this.streams)typeof f.flushSync=="function"&&f.flushSync(),f.end()}function d(f){let h=new Array(this.streams.length);for(let m=0;m<h.length;m++)h[m]={level:f,stream:this.streams[m].stream};return{write:r,add:a,remove:l,minLevel:f,streams:h,clone:d,emit:i,flushSync:o,[fa]:!0}}}function mp(n,e){return n.level-e.level}function pS(n,e){return e?n-1:0}function hS(n,e){return e?n-1:n+1}function mS(n,e,t){return t?n>=0:n<e}yp.exports=fS});var ga=H((lT,We)=>{"use strict";var gS=require("node:os"),$p=Po(),yS=Io(),bS=Do(),Ep=tf(),vS=up(),Cp=hn(),{configure:wS}=hp(),{assertDefaultLevelFound:xS,mappings:Tp,genLsCache:SS,genLevelComparison:_S,assertLevelComparison:AS}=na(),{DEFAULT_LEVELS:Rp,SORTING_ORDER:kS}=Zs(),{createArgsNormalizer:$S,asChindings:ES,buildSafeSonicBoom:vp,buildFormatters:CS,stringify:pa,normalizeDestFileDescriptor:wp,noop:TS}=Xs(),{version:RS}=sa(),{chindingsSym:xp,redactFmtSym:OS,serializersSym:Sp,timeSym:PS,timeSliceIndexSym:IS,streamSym:MS,stringifySym:_p,stringifySafeSym:ha,stringifiersSym:Ap,setLevelSym:LS,endSym:DS,formatOptsSym:NS,messageKeySym:FS,errorKeySym:HS,nestedKeySym:jS,mixinSym:BS,levelCompSym:US,useOnlyCustomLevelsSym:KS,formattersSym:kp,hooksSym:qS,nestedKeyStrSym:WS,mixinMergeStrategySym:GS,msgPrefixSym:VS}=Cp,{epochTime:Op,nullTime:zS}=Ep,{pid:YS}=process,JS=gS.hostname(),QS=$p.err,XS={level:"info",levelComparison:kS.ASC,levels:Rp,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:YS,hostname:JS},serializers:Object.assign(Object.create(null),{err:QS}),formatters:Object.assign(Object.create(null),{bindings(n){return n},level(n,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Op,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},ZS=$S(XS),e_=Object.assign(Object.create(null),$p);function ma(...n){let e={},{opts:t,stream:s}=ZS(e,yS(),...n);t.level&&typeof t.level=="string"&&Rp[t.level.toLowerCase()]!==void 0&&(t.level=t.level.toLowerCase());let{redact:r,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:d,base:f,name:h,level:m,customLevels:p,levelComparison:g,mixin:_,mixinMergeStrategy:A,useOnlyCustomLevels:S,formatters:k,hooks:y,depthLimit:v,edgeLimit:b,onChild:w,msgPrefix:x}=t,T=wS({maximumDepth:v,maximumBreadth:b}),L=CS(k.level,k.bindings,k.log),$=pa.bind({[ha]:T}),F=r?bS(r,$):{},j=r?{stringify:F[OS]}:{stringify:$},z="}"+(i?`\r
|
|
735
714
|
`:`
|
|
736
|
-
`),C=
|
|
715
|
+
`),C=ES.bind(null,{[xp]:"",[Sp]:o,[Ap]:F,[_p]:pa,[ha]:T,[kp]:L}),E="";f!==null&&(h===void 0?E=C(f):E=C(Object.assign({},f,{name:h})));let K=a instanceof Function?a:a?Op:zS,D=K().indexOf(":")+1;if(S&&!p)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(_&&typeof _!="function")throw Error(`Unknown mixin type "${typeof _}" - expected "function"`);if(x&&typeof x!="string")throw Error(`Unknown msgPrefix type "${typeof x}" - expected "string"`);xS(m,p,S);let Q=Tp(p,S);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Q,messageKey:l,errorKey:c}}),AS(g);let me=_S(g);return Object.assign(e,{levels:Q,[US]:me,[KS]:S,[MS]:s,[PS]:K,[IS]:D,[_p]:pa,[ha]:T,[Ap]:F,[DS]:z,[NS]:j,[FS]:l,[HS]:c,[jS]:d,[WS]:d?`,${JSON.stringify(d)}:{`:"",[Sp]:o,[BS]:_,[GS]:A,[xp]:E,[kp]:L,[qS]:y,silent:TS,onChild:w,[VS]:x}),Object.setPrototypeOf(e,vS()),SS(e),e[LS](m),e}We.exports=ma;We.exports.destination=(n=process.stdout.fd)=>typeof n=="object"?(n.dest=wp(n.dest||process.stdout.fd),vp(n)):vp({dest:wp(n),minLength:0});We.exports.transport=Jo();We.exports.multistream=bp();We.exports.levels=Tp();We.exports.stdSerializers=e_;We.exports.stdTimeFunctions=Object.assign({},Ep);We.exports.symbols=Cp;We.exports.version=RS;We.exports.default=ma;We.exports.pino=ma});function Gn(n){return new ya(n)}var t_,n_,s_,ya,ba=N(()=>{"use strict";t_={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},n_=`
|
|
737
716
|
## Reasoning Protocol
|
|
738
717
|
|
|
739
718
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -762,15 +741,15 @@ After receiving a tool result, think again:
|
|
|
762
741
|
- One tool call per turn. Wait for the result before the next call.
|
|
763
742
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
764
743
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
765
|
-
`.trim(),
|
|
744
|
+
`.trim(),s_=`
|
|
766
745
|
## Reasoning
|
|
767
746
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
768
747
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
769
|
-
`.trim(),
|
|
748
|
+
`.trim(),ya=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...t_,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,t="M"){return!this.config.thinkingEnabled||t==="XS"?e:t==="S"?`${e}
|
|
770
749
|
|
|
771
|
-
${
|
|
750
|
+
${s_}`:`${e}
|
|
772
751
|
|
|
773
|
-
${
|
|
752
|
+
${n_}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let t=[],s=e,r=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=r.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)t.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(t.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(t.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:t.join(`
|
|
774
753
|
|
|
775
754
|
`).trim(),visibleContent:s.trim(),hasThinking:t.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let t={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(t),t}recordObservation(e,t){let s=this.turnSteps[this.turnSteps.length-1];s&&(s.observation=e,t&&(s.reflection=t))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,t,s){return`
|
|
776
755
|
<self_eval>
|
|
@@ -793,22 +772,22 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
793
772
|
}
|
|
794
773
|
</self_eval>
|
|
795
774
|
`.trim()}parseSelfEval(e){let t=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let s of t){let r=e.match(s);if(r)try{let i=JSON.parse(r[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let t=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,s=typeof e.completed=="boolean"?e.completed:t>=7,r=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:t>=8?o="high":t<=4&&(o="low"),{score:t,completed:s,rationale:r,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,t,s){return t?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${s.slice(0,300)}`,"</thinking>"].join(`
|
|
796
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,t=this.turnSteps.filter(r=>r.action).length,s=this.turnSteps.filter(r=>r.reflection).length;return`${e} steps, ${t} actions, ${s} reflections`}}});function
|
|
797
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.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
|
|
775
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,t=this.turnSteps.filter(r=>r.action).length,s=this.turnSteps.filter(r=>r.reflection).length;return`${e} steps, ${t} actions, ${s} reflections`}}});function Vn(n=3){return new va(n)}var r_,va,wa=N(()=>{"use strict";r_=[{test:n=>/ENOENT|no such file|not found|does not exist/i.test(n),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:n=>/EACCES|permission denied/i.test(n),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:n=>/EISDIR|is a directory/i.test(n),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:n=>/EEXIST|already exists/i.test(n),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:n=>/no match|not found in file|search string not found/i.test(n),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:n=>/command not found|not recognized/i.test(n),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:n=>/timeout|timed out|ETIMEDOUT/i.test(n),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:n=>/exit code|exited with|non-zero/i.test(n),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:n=>/syntax error|unexpected token|parse error|SyntaxError/i.test(n),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:n=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(n),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:n=>/invalid argument|missing required|expected.*but got|type error/i.test(n),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:n=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(n),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}],va=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,t,s){let r=this.failures.get(e),i=r?r.count+1:1,o={tool:e,count:i,lastError:t,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 r_)if(a.test(t)){let l=r?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,t){let s=[`ERROR: ${t}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
|
|
776
|
+
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let t=this.failures.get(e);return t?t.count<=1&&t.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 i_(){try{if(_t.existsSync(nr))return JSON.parse(_t.readFileSync(nr,"utf-8"))}catch{}return{}}function o_(n){try{let e=sr.dirname(nr);_t.existsSync(e)||_t.mkdirSync(e,{recursive:!0}),_t.writeFileSync(nr,JSON.stringify(n,null,2),"utf-8")}catch{}}function Aa(n,e){let t=0,s=!1,r=!1;for(let i=e;i<n.length;i++){let o=n[i];if(r){r=!1;continue}if(o==="\\"&&s){r=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&t++,o==="}"&&(t--,t===0)))return n.slice(e,i+1)}return null}function zn(n){if(typeof n.name=="string"&&n.arguments&&typeof n.arguments=="object")return{tool:n.name,args:n.arguments};if(typeof n.tool=="string"&&n.args&&typeof n.args=="object")return{tool:n.tool,args:n.args};if(typeof n.name=="string"&&n.parameters&&typeof n.parameters=="object")return{tool:n.name,args:n.parameters};if(n.function&&typeof n.function=="object"){let e=n.function;if(typeof e.name=="string"){let t={};if(typeof e.arguments=="string")try{t=JSON.parse(e.arguments)}catch{t={}}else e.arguments&&typeof e.arguments=="object"&&(t=e.arguments);return{tool:e.name,args:t}}}return null}function a_(n){return n.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function l_(n){let e=[],t=/<<?action\s*>>?([\s\S]*?)(?:<<?\/action\s*>>?|$)/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1].trim();if(r)try{let i=JSON.parse(r);i.tool&&i.args&&typeof i.args=="object"&&e.push({tool:i.tool,args:i.args,format:"action_tag_json",rawMatch:s[0]})}catch{let i=Aa(r,r.indexOf("{"));if(i)try{let o=JSON.parse(i);o.tool&&o.args&&typeof o.args=="object"&&e.push({tool:o.tool,args:o.args,format:"action_tag_json",rawMatch:s[0]})}catch{}}}return e}function c_(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=zn(r);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function u_(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim());if(r.parameters||r.name){let i=zn(r);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function d_(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=t.exec(n))!==null;){let r=s[1],i=Ip(r);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function Ip(n){let e=[],t=["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"];for(let s of t){let r=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=r.exec(n))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,d;for(;(d=c.exec(o))!==null;){let h=d[1].toLowerCase(),m=d[2]??d[3]??d[4];l[h]=a_(m)}let f=a.trim();f&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=f:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),s==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function f_(n){return Ip(n)}function p_(n){let e=[],t=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=t.exec(n))!==null;)try{let r=JSON.parse(s[1].trim()),i=zn(r);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function h_(n){let e=[],t=/\{\s*"function"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Aa(n,s.index);if(r)try{let i=JSON.parse(r),o=zn(i);o&&e.push({...o,format:"function_call",rawMatch:r})}catch{}}return e}function m_(n){let e=[],t=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=t.exec(n))!==null;){let r=Aa(n,s.index);if(r)try{let i=JSON.parse(r),o=zn(i);o&&e.push({...o,format:"json_object",rawMatch:r})}catch{}}return e}function g_(n){let e=[],t=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,r=!1;for(;(s=t.exec(n))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){r=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,d;for(;(d=c.exec(i))!==null;){let f=d[1].trim(),h=d[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[f]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!r&&/<function=([^>]+)>/i.test(n)){let i=/<function=([^>]+)>/i.exec(n);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(n))!==null;){let d=c[1].trim(),f=c[2].trim();f==="true"?f=!0:f==="false"?f=!1:!isNaN(Number(f))&&f!==""&&(f=Number(f)),a[d]=f}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:n})}}return e}function Mp(){return Sa||(Sa=new _a),Sa}var _t,sr,Pp,nr,xa,_a,Sa,Lp=N(()=>{"use strict";_t=O(require("fs")),sr=O(require("path")),Pp=O(require("os")),nr=sr.join(Pp.homedir(),".hablas","model-formats.json");xa=[{format:"action_tag_json",parse:l_},{format:"xml_tool_call_wrapper",parse:d_},{format:"xml_prompt",parse:f_},{format:"xml_tags",parse:c_},{format:"xml_parameters",parse:g_},{format:"hermes",parse:u_},{format:"markdown_json",parse:p_},{format:"function_call",parse:h_},{format:"json_object",parse:m_}],_a=class{registry;constructor(){this.registry=i_()}parse(e,t,s){if(t&&Array.isArray(t)&&t.length>0){let o=t.filter(a=>a?.function?.name&&typeof a.function.name=="string");if(o.length>0){let a=o.map(l=>({function:{name:l.function.name,arguments:l.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:a,displayContent:(e||"").trim(),format:"native"}}}let r=e||"";if(!r.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let o=this.registry[s];if(o&&o.format!=="native"){let a=xa.find(l=>l.format===o.format);if(a){let l=a.parse(r);if(l.length>0)return this.learnFormat(s,o.format),this.buildResult(l,r)}}}for(let{parse:o}of xa){let a=o(r);if(a.length>0){let l=a[0].format;return s&&this.learnFormat(s,l),this.buildResult(a,r)}}let i=r.trim();return i=i.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),i=i.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),i=i.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),i=i.replace(/<<?response>>?/gi,"").replace(/<<?\/response>>?/gi,""),{toolCalls:[],displayContent:i.trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let t=e.trim();return!!(/<<?action[\s>]/i.test(t)||/<<?tool[-_]call[\s>]/i.test(t)||/<function=/i.test(t)||t.includes("```tool_call")||t.includes("```json")&&t.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)[\s>]/i.test(t)||t.startsWith("{")&&(t.includes('"name"')||t.includes('"tool"'))&&(t.includes('"arguments"')||t.includes('"args"')||t.includes('"parameters"'))||t.includes('"function"')&&t.includes('"name"'))}detectFormat(e){for(let{format:t,parse:s}of xa)if(s(e).length>0)return t;return"unknown"}learnFormat(e,t){let s=this.registry[e];s&&s.format===t?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:t,successCount:1,lastUsed:new Date().toISOString()},o_(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[t,s]of Object.entries(this.registry))e[t]={format:s.format,successCount:s.successCount};return e}buildResult(e,t){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),r=t,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)r=r.replace(o.rawMatch,"");return r=r.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),r=r.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),r=r.replace(/<<?action>>?[\s\S]*?<<?\/action>>?/gi,""),r=r.replace(/<<?response>>?/gi,"").replace(/<<?\/response>>?/gi,""),r=r.replace(/\n{3,}/g,`
|
|
798
777
|
|
|
799
|
-
`),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},
|
|
800
|
-
Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped
|
|
778
|
+
`),{toolCalls:s,displayContent:r.trim(),format:e[0]?.format??"unknown"}}},Sa=null});function b_(n,e,t){let r=Mp().parse(e,n,t);return{toolCalls:r.toolCalls,displayContent:r.displayContent}}function v_(n,e){return n==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(n==="edit_file"||n==="patch_file"||n==="search_and_replace")&&typeof e.path=="string"?`modify ${e.path}`:n==="read_file"&&typeof e.path=="string"?`read ${e.path}`:n==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):typeof e.path=="string"?String(e.path):n.replace(/_/g," ")}function w_(n){let e=(n||"").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 Fp(n,e,t,s){let r=0,i=Date.now();for(;r<=Np;){let o=await n.execute({name:e,arguments:t});if(o.success||r>=Np)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 ir(n){let{identity:e,client:t,registry:s,session:r,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:d}=n,f=n.reactEngine??Gn(),h=n.errorRecovery??Vn(),m=d?[]:s.getOllamaTools(),p=t.getModel(),g=n.maxIterations??150,_="IDLE",A=0,S=(T,L)=>{let $=y_[_];if(!$||!$.includes(T))throw new Error(`\u{1F6AB} Illegal State Transition Attempt: ${_} \u2501\u2501\u25B6 ${T} (Reason: ${L??"none"})`);o.info({from:_,to:T,reason:L},"FSM State Transition"),_=T},k=[],y=[],v=[],b="",w=0,x=!1;for(S("THINKING","Starting agentic turn");w<g;){if(w++,c?.aborted)return S("TERMINAL_ABORT","Operation aborted by signal"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:"Aborted",completedNaturally:x};let T=f.buildBudgetWarningPrompt();T&&r.addUserMessage(T,{priority:"critical",tags:["system-budget"]});let L;try{L=await t.chatWithTools(r.getMessages(),m,c)}catch(E){if(E.name==="AbortError"||c?.aborted)return S("TERMINAL_ABORT","Aborted during inference"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:"Aborted",completedNaturally:x};if(w<=1){a.onNotice?.(`Transient model error: ${E.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(K=>setTimeout(K,1e3)),w--;continue}return S("TERMINAL_ABORT","Inference failure"),a.onError?.(E.message??"Model request failed"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:E.message,completedNaturally:x}}let $=L.message?.content||"",F=L.message?.tool_calls,j=f.parseThinking($);j.hasThinking&&(f.recordStep({thought:j.thinking}),o.debug({thinking:j.thinking.slice(0,200)},"ReAct thinking")),S("PARSE_VALIDATING","Received model response, parsing");let{toolCalls:z,displayContent:C}=b_(F,$,p);if(z.length===0&&$.toLowerCase().includes("<action>")){if(A++,A>=rr){S("STATE_RECONCILIATION",`Self-correction loop exhausted after ${A} attempts`);let K=`Failed to execute after ${rr} syntax corrections. Rollback initiated.`;a.onError?.(K);try{let D=s.get("undo");D&&await D.execute({count:100})}catch{}return S("TERMINAL_ABORT","Fatal syntactic self-correction exhaustion"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:K,completedNaturally:x}}let E=`[SYSTEM ERROR - RETRY ${A}/${rr}] Malformed action block detected inside <action> tags. Expected a valid JSON object matching the HEP-1 tool schema.
|
|
779
|
+
Please correct your format and try again. Ensure all JSON keys/values are double-quoted and correctly escaped.`;S("ERROR_HEALING",`Syntax error inside action tags (attempt ${A})`),a.onNotice?.(`Malformed action block detected \u2014 healing attempt ${A}/${rr}\u2026`,"retry"),r.addToolMessage(E),S("THINKING","Error injected, waiting for next generation");continue}if(C&&C.trim()&&(b=C,await a.onAssistantText?.(C,e)),$.includes("ESCALATE_SCOPE")||v.length>3){S("ESCALATING","Detected need for scope escalation"),a.onNotice?.("Escalating scope: Task requires more specialized agents.","info"),r.addAssistantMessage($,z,e.role),x=!0;break}if(z.length===0){r.addAssistantMessage($,void 0,e.role),x=!0,S("SYNTHESIZING","Completed execution naturally");break}S("ACTION_READY","Action parsed and verified"),r.addAssistantMessage($,z,e.role);for(let E=0;E<z.length;E++){let K=z[E];if(!K?.function?.name)continue;let D=K.function.name,Q=K.function.arguments||{},me=s.getSafetyLevel(D)??"confirm";if(!s.get(D)){S("ERROR_HEALING",`Unknown tool execution: ${D}`),a.onNotice?.(`Unknown tool: ${D} \u2014 skipping`,"warn"),r.addToolMessage(`Error: Unknown tool "${D}". Available: ${s.getAll().map(ue=>ue.name).join(", ")}`),S("THINKING","Returning to thought loop");continue}if(await l(D,me,Q)==="skip"){r.addToolMessage(`Tool ${D} was skipped by policy/user.`);break}k.push(D),typeof Q.path=="string"&&v.push(Q.path);let _e=v_(D,Q);a.onToolStart?.(D,_e,Q),a.onToolCall?.(),f.recordStep({thought:j.hasThinking?`Executing: ${D}`:"",action:D,actionInput:Q}),S("EXECUTING_TOOL",`Executing tool: ${D}`);let pe=await Fp(s,D,Q,o);a.onToolEnd?.(D,pe.success,pe.error||pe.output,pe.duration,Q);let Oe;if(pe.success)Oe=Fn(pe.output,Dp),f.recordObservation(Oe.slice(0,300)),y.push({tool:D,success:!0,summary:pe.output.slice(0,150)}),S("THINKING",`Successfully executed tool: ${D}`);else{let ue=pe.error||"Unknown error";if(w_(ue)){S("STATE_RECONCILIATION",`Critical failure in tool ${D}: ${ue}`),a.onNotice?.("Critical tool failure \u2014 aborting and rolling back changes.","warn");try{let we=s.get("undo");we&&await we.execute({count:100})}catch{}return S("TERMINAL_ABORT","State reverted due to critical failure"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:ue,completedNaturally:x}}let q=h.analyze(D,ue,Q);if(Oe=h.buildRecoveryMessage(q,ue),f.recordObservation(`FAILED: ${ue}`,`Recovery: ${q.strategy} \u2014 ${q.suggestion}`),y.push({tool:D,success:!1,summary:ue.slice(0,150)}),q.autoRetry&&!f.isOverBudget()){S("ERROR_HEALING","Attempting auto-recovery for transient error"),a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let we=await Fp(s,D,Q,o);a.onToolEnd?.(D,we.success,we.output,we.duration,Q),we.success?(Oe=Fn(we.output,Dp),f.recordObservation(Oe.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:D,success:!0,summary:we.output.slice(0,150)},S("THINKING","Recovery successful")):S("THINKING","Recovery failed, continuing turn")}else S("THINKING","Continuing turn with failed step")}r.addToolMessage(Oe),pe.success&&D==="read_file"&&typeof Q.path=="string"&&i?.addFile(Q.path,pe.output),o.info({tool:D,success:pe.success,durationMs:pe.duration,retries:pe.retries},"Tool executed")}f.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${f.getConfig().maxSteps}). Wrapping up.`,"warn")}return w>=g&&!x?(a.onNotice?.(`Reached max iterations (${g}). Stopping.`,"warn"),S("TERMINAL_ABORT","Max iterations boundary exceeded"),{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!1,error:"Max iterations exceeded",completedNaturally:x}):(S("TERMINAL_SUCCESS","Turn finalized successfully"),_="IDLE",{output:b,toolsUsed:Te(k),toolResults:y,touchedFiles:Te(v),iterations:w,success:!0,completedNaturally:x})}function Te(n){return[...new Set(n)]}function Hp(n){return async(e,t)=>{let s=e.replace(/_/g," ");return!n.autoMode&&n.interactive?t==="confirm"&&n.confirm?await n.confirm(`Proceed with ${s}?`)?"allow":"skip":t==="dangerous"&&n.confirmDangerous?await n.confirmDangerous(`Dangerous: ${s}`)?"allow":"skip":"allow":!n.autoMode&&t==="dangerous"?"skip":"allow"}}function jp(){return(n,e)=>e==="dangerous"?"skip":"allow"}var Dp,Np,rr,y_,ka=N(()=>{"use strict";Qi();ba();wa();Lp();Dp=2e3,Np=2,rr=3,y_={IDLE:["THINKING"],THINKING:["PARSE_VALIDATING","TERMINAL_ABORT","ESCALATING"],PARSE_VALIDATING:["ACTION_READY","ERROR_HEALING","SYNTHESIZING","TERMINAL_ABORT"],ACTION_READY:["EXECUTING_TOOL","STATE_RECONCILIATION","TERMINAL_ABORT"],EXECUTING_TOOL:["THINKING","ERROR_HEALING","STATE_RECONCILIATION","TERMINAL_ABORT","ESCALATING"],ERROR_HEALING:["THINKING","STATE_RECONCILIATION","TERMINAL_ABORT"],STATE_RECONCILIATION:["TERMINAL_ABORT"],SYNTHESIZING:["TERMINAL_SUCCESS","TERMINAL_ABORT"],ESCALATING:["SYNTHESIZING","TERMINAL_ABORT"],TERMINAL_SUCCESS:["IDLE"],TERMINAL_ABORT:["IDLE"]}});var Up,x_,S_,__,Bp,or,Kp=N(()=>{"use strict";Up=O(ga());$n();Zi();Xi();En();vi();So();ka();x_={hablas:"planner",bob:"architect",alex:"coder",david:"researcher",emma:"product-manager"},S_=(0,Up.default)({level:"silent"}),__=40,Bp={hablas:{role:"hablas",model:"stepfun-ai/step-3.7-flash",temperature:.7},bob:{role:"bob",model:"stepfun-ai/step-3.7-flash",temperature:.4},alex:{role:"alex",model:"stepfun-ai/step-3.7-flash",temperature:.2},david:{role:"david",model:"stepfun-ai/step-3.7-flash",temperature:.5},emma:{role:"emma",model:"stepfun-ai/step-3.7-flash",temperature:.6}},or=class{baseConfig;agentModels;toolRegistry=null;onOutput=null;channel=null;mindsetRegistry=Ds();sharedContext=null;contextManager;constructor(e){this.baseConfig=e,this.agentModels=Cn(),this.contextManager=new Bt(e)}setSharedContext(e){this.sharedContext=e}setChannel(e){this.channel=e}setToolRegistry(e){this.toolRegistry=e}setOutputCallback(e){this.onOutput=e}reloadModels(){this.agentModels=Cn()}getAgentModel(e){let t=this.agentModels[e];if(t)return{model:t.model,temperature:t.temperature??Bp[e]?.temperature??.5};let s=Bp[e];return{model:s.model,temperature:s.temperature??.5}}async runAgent(e,t,s,r,i){let o=Date.now(),a=ge.find(S=>S.role===e),l=this.getAgentModel(e),c=i?.maxIterations||__,d={...this.baseConfig,model:l.model},f=He(d),h=this.buildAgentPrompt(a,s),m=new Ut(h,30,this.baseConfig.contextBudget);m.addUserMessage(t);let p={name:a.name,title:a.title,role:e};this.emit(a.name,"thinking",`\u2605 Hablas \u2192 Delegating to @${a.name} (${a.title})...`);let g={onAssistantText:S=>{this.emit(a.name,"speaking",S.slice(0,200))},onToolStart:(S,k,y)=>{this.emit(a.name,"tool",k),this.channel&&this.channel.emitEvent({type:"act",agent:a.name,toolName:S,toolArgs:this.safeArgs(y),content:k})},onToolEnd:(S,k,y)=>{this.channel&&this.channel.emitEvent({type:"observe",agent:a.name,toolName:S,success:k,content:k?this.summarizeOk(S,y):`error: ${y.slice(0,120)}`})},onError:S=>this.emit(a.name,"error",S)},_=await ir({identity:p,client:f,registry:this.toolRegistry,session:m,contextManager:this.contextManager,logger:S_,io:g,safetyPolicy:jp(),abortSignal:i?.abortSignal,skipTools:(!r||r.length===0,!1),maxIterations:c});if(this.sharedContext&&_.touchedFiles.length)try{this.sharedContext.set(`files:@${a.name}`,_.touchedFiles.join(", "))}catch{}let A=_.touchedFiles.length?[`@${a.name} touched: ${_.touchedFiles.join(", ")}`]:[];return{agent:e,agentName:a.name,output:_.output||(_.success?"Done.":_.error??"No output"),toolsUsed:_.toolsUsed,toolResults:_.toolResults,duration:Date.now()-o,iterations:_.iterations,success:_.success,error:_.error,discoveries:A,touchedFiles:_.touchedFiles}}async runSequential(e,t,s){let r=[],i="",o=[];for(let a=0;a<e.length;a++){let{role:l,task:c}=e[a];if(s?.abortSignal?.aborted)break;let d=[];if(i&&(d.push("## Previous Agent Results"),d.push(i)),o.length>0){d.push(`
|
|
801
780
|
## Handoff Chain`);for(let p of o)d.push(`- @${p.from} \u2192 @${p.to}: ${p.context.slice(0,100)}`)}let f=d.join(`
|
|
802
|
-
`),h=
|
|
781
|
+
`),h=ge.find(p=>p.role===l);if(h&&a>0){let p=e[a-1].role,g=ge.find(_=>_.role===p);this.emit(h.name,"thinking",`\u2605 Handoff: @${g?.name||p} \u2192 @${h.name} (${h.title})`)}let m=await this.runAgent(l,c,f,t,s);if(r.push(m),m.success&&m.output){let p=m.output.length>600?m.output.slice(0,600)+"...":m.output;i+=`
|
|
803
782
|
|
|
804
|
-
### @${m.agentName} (${
|
|
805
|
-
${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:
|
|
783
|
+
### @${m.agentName} (${ge.find(g=>g.role===l)?.title||l})
|
|
784
|
+
${p}`,a<e.length-1&&o.push({from:l,to:e[a+1].role,context:m.output.slice(0,200),artifacts:m.touchedFiles})}}return r}async runParallel(e,t,s){let r=s?.maxConcurrent||3,i=[];for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r),l=await Promise.all(a.map(({role:c,task:d})=>this.runAgent(c,d,void 0,t,s)));i.push(...l)}return i}async runWithEscalation(e,t,s,r){let i=await this.runAgent(e,t,s,r);if(i.success)return i;this.emit(ge.find(a=>a.role===e)?.name||e,"error",`First attempt failed: ${i.error}. Retrying...`);let o=(s||"")+`
|
|
806
785
|
|
|
807
786
|
## Previous Attempt Failed
|
|
808
787
|
Error: ${i.error}
|
|
809
|
-
Please try a different approach.`;if(i=await this.runAgent(e,t,o,r),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${
|
|
788
|
+
Please try a different approach.`;if(i=await this.runAgent(e,t,o,r),i.success)return i;if(e!=="hablas"){this.emit("Hablas","thinking",`@${ge.find(l=>l.role===e)?.name} failed. Hablas taking over...`);let a=`Agent @${e} failed twice on this task.
|
|
810
789
|
Original error: ${i.error}
|
|
811
|
-
Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=
|
|
790
|
+
Please complete this task.`;return this.runAgent("hablas",t,a,r)}return i}buildAgentPrompt(e,t){let s=x_[e.role]??"coder",r=this.mindsetRegistry.get(s),o=(r?`${r.systemPrompt}
|
|
812
791
|
|
|
813
792
|
---
|
|
814
793
|
|
|
@@ -869,15 +848,15 @@ Expertise: ${e.expertise.join(", ")}
|
|
|
869
848
|
${t}`),this.sharedContext){let a=this.sharedContext.getSummary();a&&(o+=`
|
|
870
849
|
|
|
871
850
|
## Shared Team Context
|
|
872
|
-
${a}`)}return o}emit(e,t,s){if(this.onOutput&&this.onOutput(e,t,s),this.channel){let r=t==="speaking"?"speak":t==="tool"?"act":t;this.channel.emitEvent({type:r,agent:e,content:s})}}safeArgs(e){let t={};for(let[s,r]of Object.entries(e||{}))typeof r=="string"?t[s]=r.length>160?r.slice(0,160)+"\u2026":r:(typeof r=="number"||typeof r=="boolean")&&(t[s]=r);return t}summarizeOk(e,t){let s=t.split(/\r?\n/).length;return e==="write_file"||e==="edit_file"||e==="patch_file"?`ok \xB7 ${s} line${s===1?"":"s"}`:e==="run_command"?`ok \xB7 ${t.split(/\r?\n/).find(i=>i.trim())?.slice(0,80)||"ok"}`:e==="read_file"?`ok \xB7 ${s} line${s===1?"":"s"} read`:"ok"}}});var
|
|
873
|
-
${
|
|
851
|
+
${a}`)}return o}emit(e,t,s){if(this.onOutput&&this.onOutput(e,t,s),this.channel){let r=t==="speaking"?"speak":t==="tool"?"act":t;this.channel.emitEvent({type:r,agent:e,content:s})}}safeArgs(e){let t={};for(let[s,r]of Object.entries(e||{}))typeof r=="string"?t[s]=r.length>160?r.slice(0,160)+"\u2026":r:(typeof r=="number"||typeof r=="boolean")&&(t[s]=r);return t}summarizeOk(e,t){let s=t.split(/\r?\n/).length;return e==="write_file"||e==="edit_file"||e==="patch_file"?`ok \xB7 ${s} line${s===1?"":"s"}`:e==="run_command"?`ok \xB7 ${t.split(/\r?\n/).find(i=>i.trim())?.slice(0,80)||"ok"}`:e==="read_file"?`ok \xB7 ${s} line${s===1?"":"s"} read`:"ok"}}});var qp,ar,Wp=N(()=>{"use strict";qp=require("events"),ar=class extends qp.EventEmitter{events=[];maxHistory;constructor(e=500){super(),this.setMaxListeners(50),this.maxHistory=e}emitEvent(e){let t={...e,timestamp:Date.now()};return this.events.push(t),this.events.length>this.maxHistory&&this.events.splice(0,this.events.length-this.maxHistory),this.emit("event",t),this.emit(t.type,t),t}history(){return[...this.events]}reset(){this.events=[]}onEvent(e){return this.on("event",e),this}offEvent(e){return this.off("event",e),this}}});var A_,ct,lr,cr,Gp=N(()=>{"use strict";$n();A_={hablas:"Hablas \u2014 INTJ Team Leader. Authoritative, terse, engineering-precise. Speaks in short systemic statements. No pleasantries.",emma:"Emma \u2014 Product Manager. Calm, user-focused, structured. Clarifies scope and outcomes in plain language.",bob:"Bob \u2014 System Architect. Methodical, principled, slightly formal. Talks in terms of boundaries, trade-offs, contracts.",alex:"Alex \u2014 Senior Engineer. Pragmatic, concise, action-biased. Confirms intent, then ships.",david:"David \u2014 Data & Research Analyst. Factual, evidence-driven, neutral tone. Cites context, not opinions."},ct={hablas:"Hablas",emma:"Emma",bob:"Bob",alex:"Alex",david:"David"},lr={handoff:(n,e,t)=>{let s=ct[e];return{hablas:`Routing this to you, @${s}.`,emma:`@${s}, I need the requirements framed before we move.`,bob:`@${s}, design the structure for this. Keep boundaries clean.`,alex:`@${s}, you have the implementation. Stay surgical.`,david:`@${s}, gather the context we need on this.`}[e]||`@${s}, taking this from here.`},ack:(n,e)=>`Acknowledged, @${ct[e]}. Proceeding.`,review:(n,e)=>`@${ct[e]}, structurally sound. Watch the boundaries on the next pass.`,reviewAck:(n,e)=>`Noted, @${ct[e]}. Integrating.`},cr=class{client;spent=0;cache=new Map;opts;constructor(e,t={}){this.opts={tokenBudget:t.tokenBudget??500,maxChars:t.maxChars??140,lightModel:t.lightModel,abortSignal:t.abortSignal};let s={...e,model:this.opts.lightModel||e.model};this.client=He(s)}resetBudget(){this.spent=0,this.cache.clear()}setAbortSignal(e){this.opts.abortSignal=e}async generateHandoffLine(e,t,s){return this.generate(`handoff:${e}:${t}:${this.hash(s)}`,this.buildPrompt(e,t,"handoff",s),()=>lr.handoff(e,t,s))}async generateAckLine(e,t){return this.generate(`ack:${e}:${t}`,this.buildPrompt(e,t,"ack"),()=>lr.ack(e,t))}async generateReviewLine(e,t,s){return this.generate(`review:${e}:${t}:${this.hash(s.slice(0,200))}`,this.buildPrompt(e,t,"review",s.slice(0,400)),()=>lr.review(e,t))}async generateReviewAck(e,t){return this.generate(`reviewAck:${e}:${t}`,this.buildPrompt(e,t,"reviewAck"),()=>lr.reviewAck(e,t))}async generate(e,t,s){let r=this.cache.get(e);if(r)return r;if(this.spent>=this.opts.tokenBudget||this.opts.abortSignal?.aborted)return s();try{let o=((await this.client.chatWithTools(t,[],this.opts.abortSignal)).message?.content||"").trim(),a=this.cleanLine(o);return a?(this.spent+=Math.ceil(a.length/4)+40,this.cache.set(e,a),a):s()}catch{return s()}}buildPrompt(e,t,s,r){let i=`You are ${ct[e]}, speaking in your own voice.
|
|
852
|
+
${A_[e]}
|
|
874
853
|
|
|
875
854
|
Hard constraints:
|
|
876
855
|
- Output exactly ONE sentence.
|
|
877
856
|
- No prefix, no quotes, no markdown, no emojis, no role labels.
|
|
878
857
|
- Maximum ${this.opts.maxChars} characters.
|
|
879
|
-
- Address @${
|
|
880
|
-
- Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${
|
|
858
|
+
- Address @${ct[t]} directly.
|
|
859
|
+
- Stay in character. Be useful, not chatty.`,o;switch(s){case"handoff":o=`You are about to hand the following task to @${ct[t]}. Write a single in-character line that briefly frames what you need from them. Task: "${(r||"").slice(0,300)}"`;break;case"ack":o=`@${ct[t]} just handed you a task. Write a single in-character line acknowledging it and stating your immediate next move.`;break;case"review":o=`You just reviewed @${ct[t]}'s output below. Write a single in-character line of feedback \u2014 substantive but extremely brief. Output excerpt: """${(r||"").slice(0,400)}"""`;break;case"reviewAck":o=`@${ct[t]} just reviewed your work and gave you feedback. Write a single in-character line acknowledging it and noting the integration.`;break}return[{role:"system",content:i},{role:"user",content:o}]}cleanLine(e){let t=e.trim();return t=t.replace(/^```[a-z]*\n?|```$/gi,"").trim(),t=t.split(/\r?\n/)[0].trim(),t=t.replace(/^@?[A-Z][a-zA-Z]+\s*:\s*/,"").trim(),t=t.replace(/^["'`«»“”]+|["'`«»“”]+$/g,"").trim(),t.length>this.opts.maxChars&&(t=t.slice(0,this.opts.maxChars-1).trim()+"\u2026"),t}hash(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t.toString(36)}}});var X,tt,k_,zp,$_,Yp,Vp,yn,$a=N(()=>{"use strict";X=O(require("fs")),tt=O(require("path")),k_=".hablas",zp=`# Project Context
|
|
881
860
|
|
|
882
861
|
## Overview
|
|
883
862
|
<!-- Auto-generated by hablas. Describe your project here. -->
|
|
@@ -890,33 +869,33 @@ Hard constraints:
|
|
|
890
869
|
|
|
891
870
|
## Notes
|
|
892
871
|
<!-- Miscellaneous context for agents -->
|
|
893
|
-
|
|
872
|
+
`,$_=`# Decisions Log
|
|
894
873
|
|
|
895
874
|
| Date | Decision | By | Rationale |
|
|
896
875
|
|------|----------|-----|-----------|
|
|
897
|
-
`,
|
|
876
|
+
`,Yp=`# Task Assignments
|
|
898
877
|
|
|
899
878
|
## Active Tasks
|
|
900
879
|
<!-- Format: - [ ] Task description (@agent) -->
|
|
901
880
|
|
|
902
881
|
## Completed
|
|
903
882
|
<!-- Format: - [x] Task description (@agent) \u2014 result -->
|
|
904
|
-
`,
|
|
905
|
-
`+t,"utf-8")}logDecision(e,t,s){let i=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} |`;this.append("DECISIONS.md",i)}addTask(e,t){let s=`- [ ] ${e} (@${t})`,i=(this.read("TASKS.md")||
|
|
883
|
+
`,Vp={"CONTEXT.md":zp,"DECISIONS.md":$_,"TASKS.md":Yp},yn=class{contextDir;constructor(e){this.contextDir=tt.join(e,k_)}init(){let e=tt.join(tt.dirname(this.contextDir),".flowagent");if(X.existsSync(e)&&!X.existsSync(this.contextDir))try{X.renameSync(e,this.contextDir)}catch{}X.existsSync(this.contextDir)||X.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(Vp)){let r=tt.join(this.contextDir,t);X.existsSync(r)||X.writeFileSync(r,s,"utf-8")}}exists(){return X.existsSync(this.contextDir)}read(e){let t=tt.join(this.contextDir,e);return X.existsSync(t)?X.readFileSync(t,"utf-8"):null}write(e,t){this.ensureDir();let s=tt.join(this.contextDir,e);X.writeFileSync(s,t,"utf-8")}append(e,t){this.ensureDir();let s=tt.join(this.contextDir,e),r=X.existsSync(s)?X.readFileSync(s,"utf-8"):"";X.writeFileSync(s,r+`
|
|
884
|
+
`+t,"utf-8")}logDecision(e,t,s){let i=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} |`;this.append("DECISIONS.md",i)}addTask(e,t){let s=`- [ ] ${e} (@${t})`,i=(this.read("TASKS.md")||Yp).replace(`## Active Tasks
|
|
906
885
|
`,`## Active Tasks
|
|
907
886
|
${s}
|
|
908
|
-
`);this.write("TASKS.md",i)}completeTask(e,t){let s=this.read("TASKS.md");if(!s)return;let r=`- [ ] ${e}`,i=`- [x] ${e}${t?" \u2014 "+t:""}`,o=s.replace(r,i);this.write("TASKS.md",o)}getAll(){return
|
|
887
|
+
`);this.write("TASKS.md",i)}completeTask(e,t){let s=this.read("TASKS.md");if(!s)return;let r=`- [ ] ${e}`,i=`- [x] ${e}${t?" \u2014 "+t:""}`,o=s.replace(r,i);this.write("TASKS.md",o)}getAll(){return X.existsSync(this.contextDir)?X.readdirSync(this.contextDir).filter(t=>t.endsWith(".md")).map(t=>{let s=tt.join(this.contextDir,t),r=X.statSync(s);return{file:t,content:X.readFileSync(s,"utf-8"),lastModified:r.mtime}}):[]}getSummary(){let e=this.getAll();return e.length===0?"":e.map(t=>`### ${t.file}
|
|
909
888
|
${t.content}`).join(`
|
|
910
889
|
|
|
911
|
-
`)}kvStore=new Map;set(e,t){this.kvStore.set(e,t),this.persistKV()}get(e){return this.kvStore.get(e)}delete(e){let t=this.kvStore.delete(e);return t&&this.persistKV(),t}clear(){this.kvStore.clear();for(let[e,t]of Object.entries(
|
|
890
|
+
`)}kvStore=new Map;set(e,t){this.kvStore.set(e,t),this.persistKV()}get(e){return this.kvStore.get(e)}delete(e){let t=this.kvStore.delete(e);return t&&this.persistKV(),t}clear(){this.kvStore.clear();for(let[e,t]of Object.entries(Vp)){let s=tt.join(this.contextDir,e);X.existsSync(s)&&X.writeFileSync(s,t,"utf-8")}}getDecisions(){let e=this.read("DECISIONS.md");if(!e)return[];let t=e.split(`
|
|
912
891
|
`),s=[];for(let r of t){let i=r.match(/^\|\s*(\d{4}-\d{2}-\d{2})\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|$/);i&&s.push({timestamp:i[1],decision:i[2].trim(),by:i[3].trim(),rationale:i[4].trim()})}return s}render(){let e=[];if(this.kvStore.size>0){e.push(" Key-Value Store:");for(let[r,i]of this.kvStore)e.push(` ${r}: ${i}`)}else e.push(" No key-value entries");let t=this.getAll();if(t.length>0){e.push(""),e.push(" Context Files:");for(let r of t){let i=r.content.split(`
|
|
913
892
|
`).length;e.push(` ${r.file} (${i} lines)`)}}let s=this.getDecisions();return s.length>0&&(e.push(""),e.push(` Decisions: ${s.length} logged`)),e.join(`
|
|
914
|
-
`)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||
|
|
893
|
+
`)}persistKV(){if(this.kvStore.size===0)return;let e=this.read("CONTEXT.md")||zp,t=Array.from(this.kvStore.entries()).map(([i,o])=>`- **${i}**: ${o}`).join(`
|
|
915
894
|
`),s=/## Notes\n[\s\S]*$/,r=e.replace(s,`## Notes
|
|
916
895
|
${t}
|
|
917
|
-
`);this.write("CONTEXT.md",r)}ensureDir(){
|
|
896
|
+
`);this.write("CONTEXT.md",r)}ensureDir(){X.existsSync(this.contextDir)||X.mkdirSync(this.contextDir,{recursive:!0})}}});function Ea(n){return ge.find(e=>e.role===n)?.name||n}var ur,Jp=N(()=>{"use strict";En();$a();ur=class{channel;runner;chat;constructor(e,t,s,r){this.channel=e,this.runner=t,this.chat=s,this.runner.setChannel(e),this.chat.resetBudget()}async run(e,t,s,r={}){this.chat.setAbortSignal(r.abortSignal);let i=r.peerReview!==!1,o=new yn(process.cwd());this.runner.setSharedContext(o),this.channel.emitEvent({type:"phase",agent:"System",content:"Delegating to the team"});let a=t.tasks.filter(h=>h.role!=="hablas").map(h=>({role:h.role,task:`${h.description}
|
|
918
897
|
|
|
919
|
-
Original request: ${e}`})),l=[],
|
|
898
|
+
Original request: ${e}`})),l=[],c="hablas",d=null;for(let h of a){if(r.abortSignal?.aborted)break;let m=ge.find(S=>S.role===h.role);if(!m)continue;this.channel.emitEvent({type:"handoff",agent:Ea(c),to:m.name});let p=await this.chat.generateHandoffLine(c,h.role,h.task);this.channel.emitEvent({type:"speak",agent:Ea(c),to:m.name,content:p});let g=await this.chat.generateAckLine(h.role,c);this.channel.emitEvent({type:"speak",agent:m.name,to:Ea(c),content:g});let _=Date.now(),A=await this.runner.runAgent(h.role,h.task,void 0,s,{abortSignal:r.abortSignal});l.push(A),A.success&&A.output?(this.channel.emitEvent({type:"summary",agent:m.name,durationMs:Date.now()-_}),h.role==="alex"&&(d=A.output),i&&h.role==="alex"&&t.tasks.some(S=>S.role==="bob")&&d&&await this.runPeerReview("bob","alex",d,r.abortSignal)):A.error&&this.channel.emitEvent({type:"error",agent:m.name,content:A.error}),c=h.role}this.channel.emitEvent({type:"phase",agent:"System",content:"Hablas compiling final report"});let f=await this.synthesize(e,l,s,r.abortSignal);return this.channel.emitEvent({type:"done",agent:"Hablas"}),f}async runPeerReview(e,t,s,r){let i=ge.find(c=>c.role===e),o=ge.find(c=>c.role===t);if(!i||!o)return;let a=await this.chat.generateReviewLine(e,t,s);this.channel.emitEvent({type:"review",agent:i.name,to:o.name,content:a});let l=await this.chat.generateReviewAck(t,e);this.channel.emitEvent({type:"speak",agent:o.name,to:i.name,content:l}),r?.aborted}async synthesize(e,t,s,r){let i=t.filter(d=>d.success&&d.output);if(i.length===0)return{results:t,finalSynthesis:"The team encountered errors and could not complete the task. Please review the logs and try again.",synthesisOk:!1};let o=i.map(d=>{let f=ge.find(h=>h.role===d.agent);return`### Report from @${d.agentName} (${f?.title??d.agent}):
|
|
920
899
|
${d.output}`}).join(`
|
|
921
900
|
|
|
922
901
|
`),a=`You are Hablas, the Team Leader. Your team has completed a multi-agent workflow for the user's request: "${e}".
|
|
@@ -926,172 +905,40 @@ Here are the individual execution reports from your team members:
|
|
|
926
905
|
${o}
|
|
927
906
|
"""
|
|
928
907
|
|
|
929
|
-
Please compile, synthesize, and present the final unified response to the user. Describe what was achieved, the files modified/created (if any), and any next steps. Speak in your characteristic Hablas voice \u2014 INTJ, authoritative, terse, engineering-precise. Speak directly to the user.`,l=await this.runner.runAgent("hablas",a,void 0,s,{abortSignal:r});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let
|
|
908
|
+
Please compile, synthesize, and present the final unified response to the user. Describe what was achieved, the files modified/created (if any), and any next steps. Speak in your characteristic Hablas voice \u2014 INTJ, authoritative, terse, engineering-precise. Speak directly to the user.`,l=await this.runner.runAgent("hablas",a,void 0,s,{abortSignal:r});if(l.success&&l.output)return{results:t,finalSynthesis:l.output,synthesisOk:!0};let c=i.map(d=>{let f=ge.find(h=>h.role===d.agent);return`### @${d.agentName} (${f?.title??d.agent}):
|
|
930
909
|
${d.output}`}).join(`
|
|
931
910
|
|
|
932
|
-
`);return{results:t,finalSynthesis:
|
|
933
|
-
${
|
|
934
|
-
${i("\u270E")} ${
|
|
935
|
-
${
|
|
936
|
-
|
|
937
|
-
## Project Overview
|
|
938
|
-
<!-- Auto-populated by Hablas on first scan -->
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
## Current Sprint
|
|
955
|
-
<!-- Active work items -->
|
|
956
|
-
|
|
957
|
-
## Requirements Overview
|
|
958
|
-
<!-- High-level requirements -->
|
|
959
|
-
|
|
960
|
-
## User Stories
|
|
961
|
-
<!-- As a [role], I want [feature], so that [benefit] -->
|
|
962
|
-
|
|
963
|
-
## Task Breakdown
|
|
964
|
-
| Task | Assignee | Status | Started | Completed |
|
|
965
|
-
|------|----------|--------|---------|-----------|
|
|
966
|
-
|
|
967
|
-
## Progress Log
|
|
968
|
-
<!-- Chronological log of all actions taken -->
|
|
969
|
-
`,A0=`# Architecture Design
|
|
970
|
-
|
|
971
|
-
## System Overview
|
|
972
|
-
<!-- High-level architecture description -->
|
|
973
|
-
|
|
974
|
-
## Tech Stack
|
|
975
|
-
| Layer | Technology | Rationale |
|
|
976
|
-
|-------|-----------|-----------|
|
|
977
|
-
|
|
978
|
-
## Module Design
|
|
979
|
-
| Module | Responsibility | Key Files | Dependencies |
|
|
980
|
-
|--------|---------------|-----------|-------------|
|
|
981
|
-
|
|
982
|
-
## API Design
|
|
983
|
-
<!-- Endpoints, contracts, protocols -->
|
|
984
|
-
|
|
985
|
-
## Data Model
|
|
986
|
-
<!-- Database schema, data flow -->
|
|
987
|
-
|
|
988
|
-
## Architecture Decision Records (ADRs)
|
|
989
|
-
| # | Decision | Status | Date | Context |
|
|
990
|
-
|---|----------|--------|------|---------|
|
|
991
|
-
|
|
992
|
-
## File Tree Plan
|
|
993
|
-
<!-- Planned or actual directory structure -->
|
|
994
|
-
|
|
995
|
-
## Implementation Guide
|
|
996
|
-
<!-- Step-by-step implementation order -->
|
|
997
|
-
`,k0=`# Agent Activity Log
|
|
998
|
-
|
|
999
|
-
## Session History
|
|
1000
|
-
| Session | Date | Duration | Agents Used | Tasks Completed |
|
|
1001
|
-
|---------|------|----------|-------------|-----------------|
|
|
1002
|
-
|
|
1003
|
-
## Delegation Log
|
|
1004
|
-
| Time | From | To | Task | Model Used | Result | Duration |
|
|
1005
|
-
|------|------|----|------|-----------|--------|----------|
|
|
1006
|
-
|
|
1007
|
-
## Agent Performance
|
|
1008
|
-
| Agent | Total Tasks | Success Rate | Avg Duration | Specialties Used |
|
|
1009
|
-
|-------|-------------|-------------|-------------|-----------------|
|
|
1010
|
-
|
|
1011
|
-
## Inter-Agent Communication
|
|
1012
|
-
<!-- Messages exchanged between agents during complex tasks -->
|
|
1013
|
-
`,$0=`# Learned Knowledge
|
|
1014
|
-
|
|
1015
|
-
## Project Conventions
|
|
1016
|
-
<!-- Coding style, naming conventions, file organization patterns -->
|
|
1017
|
-
|
|
1018
|
-
## Discovered Patterns
|
|
1019
|
-
<!-- Patterns found in the codebase by agents -->
|
|
1020
|
-
|
|
1021
|
-
## Known Gotchas
|
|
1022
|
-
<!-- Things that went wrong and how they were fixed -->
|
|
1023
|
-
|
|
1024
|
-
## Auto-Discoveries
|
|
1025
|
-
<!-- Automatically detected facts about the project -->
|
|
1026
|
-
|
|
1027
|
-
## Dependency Notes
|
|
1028
|
-
<!-- Important notes about dependencies and versions -->
|
|
1029
|
-
`,E0={"HABLAS.md":S0,"PROGRESS.md":_0,"ARCHITECTURE.md":A0,"AGENTS.md":k0,"MEMORY.md":$0},zr=class{contextDir;sessionDelegations=[];sessionDiscoveries=[];constructor(e){this.contextDir=dt.join(e,x0)}init(){let e=dt.join(dt.dirname(this.contextDir),".hablas-legacy");if(ce.existsSync(e)&&!ce.existsSync(this.contextDir))try{ce.renameSync(e,this.contextDir);let t=dt.join(this.contextDir,"LEGACY.md"),s=dt.join(this.contextDir,"HABLAS.md");ce.existsSync(t)&&!ce.existsSync(s)&&ce.renameSync(t,s)}catch{}ce.existsSync(this.contextDir)||ce.mkdirSync(this.contextDir,{recursive:!0});for(let[t,s]of Object.entries(E0)){let r=dt.join(this.contextDir,t);ce.existsSync(r)||ce.writeFileSync(r,s,"utf-8")}}exists(){return ce.existsSync(this.contextDir)}readContext(e){let t=dt.join(this.contextDir,e);return ce.existsSync(t)?ce.readFileSync(t,"utf-8"):null}updateProgress(e){let t=new Date().toISOString().split("T")[0],s=new Date().toISOString().split("T")[1].split(".")[0],r=`- [${t} ${s}] ${e}`;this.appendToSection("PROGRESS.md","## Progress Log",r)}addTask(e,t){let s=new Date().toISOString().split("T")[0],r=`| ${e} | @${t} | \u{1F535} pending | ${s} | \u2014 |`;this.appendToSection("PROGRESS.md","## Task Breakdown",r)}updateSprint(e){this.updateSection("PROGRESS.md","## Current Sprint",e)}recordDecision(e,t,s,r="medium"){let o=`| ${new Date().toISOString().split("T")[0]} | ${e} | ${t} | ${s} | ${r} |`;this.appendToSection("HABLAS.md","## Key Decisions",o)}updateArchitecture(e,t){this.updateSection("ARCHITECTURE.md",e,t)}recordADR(e,t,s="accepted"){let r=new Date().toISOString().split("T")[0],a=`| ${((this.readContext("ARCHITECTURE.md")||"").match(/^\|/gm)||[]).length} | ${e} | ${s} | ${r} | ${t} |`;this.appendToSection("ARCHITECTURE.md","## Architecture Decision Records (ADRs)",a)}logDelegation(e){this.sessionDelegations.push(e);let t=`| ${e.time} | ${e.from} | ${e.to} | ${e.task.slice(0,50)} | ${e.model} | ${e.result} | ${e.durationMs}ms |`;this.appendToSection("AGENTS.md","## Delegation Log",t)}logSession(e){let t=`| ${e.sessionId} | ${e.date} | ${Math.round(e.duration/1e3)}s | ${e.agentsUsed.join(", ")} | ${e.tasksCompleted} |`;this.appendToSection("AGENTS.md","## Session History",t)}updateAgentPerformance(e,t,s,r,i){let o=`| @${e} | ${t} | ${Math.round(s*100)}% | ${Math.round(r)}ms | ${i.join(", ")} |`;this.appendToSection("AGENTS.md","## Agent Performance",o)}logAgentComm(e,t,s){let i=`- [${new Date().toISOString()}] **@${e}** \u2192 **@${t}**: ${s.slice(0,200)}`;this.appendToSection("AGENTS.md","## Inter-Agent Communication",i)}addConvention(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Project Conventions",r),this.sessionDiscoveries.push({type:"convention",description:e,source:t,date:s})}addPattern(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Discovered Patterns",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}addGotcha(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u26A0\uFE0F ${e} *(found by ${t})*`;this.appendToSection("MEMORY.md","## Known Gotchas",r),this.sessionDiscoveries.push({type:"gotcha",description:e,source:t,date:s})}addAutoDiscovery(e,t){let s=new Date().toISOString().split("T")[0],r=`- [${s}] \u{1F50D} ${e} *(by ${t})*`;this.appendToSection("MEMORY.md","## Auto-Discoveries",r),this.sessionDiscoveries.push({type:"pattern",description:e,source:t,date:s})}getSummary(e=8e3){let t=["HABLAS.md","PROGRESS.md","ARCHITECTURE.md","MEMORY.md"],s=[],r=0;for(let i of t){let o=this.readContext(i);if(o&&o.trim().length>0){let a=e-r;if(a<=200)break;let l=o.length>a?o.slice(0,a)+`
|
|
1030
|
-
...(truncated)`:o;s.push(`### ${i}
|
|
1031
|
-
${l}`),r+=l.length}}return s.length>0?s.join(`
|
|
1032
|
-
|
|
1033
|
-
`):""}getAgentContext(e,t=4e3){let s=[],r=0,i=this.readContext("HABLAS.md");if(i){let o=this.extractSection(i,"## Project Overview"),a=this.extractSection(i,"## Key Decisions");o&&s.push(`## Project Overview
|
|
1034
|
-
${o}`),a&&s.push(`## Key Decisions
|
|
1035
|
-
${a}`),r=s.join(`
|
|
1036
|
-
`).length}switch(e){case"emma":this.addContextFromFile(s,"PROGRESS.md",["## Requirements Overview","## User Stories","## Current Sprint"],t-r);break;case"bob":this.addContextFromFile(s,"ARCHITECTURE.md",["## System Overview","## Tech Stack","## Module Design","## Architecture Decision Records (ADRs)"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Discovered Patterns","## Project Conventions"],t-r);break;case"alex":this.addContextFromFile(s,"ARCHITECTURE.md",["## Module Design","## File Tree Plan","## Implementation Guide"],t-r),this.addContextFromFile(s,"MEMORY.md",["## Project Conventions","## Known Gotchas"],t-r),this.addContextFromFile(s,"PROGRESS.md",["## Current Sprint","## Task Breakdown"],t-r);break;case"david":this.addContextFromFile(s,"MEMORY.md",["## Auto-Discoveries","## Dependency Notes"],t-r);break;default:let o=this.getSummary(t-r);o&&s.push(o)}return s.join(`
|
|
1037
|
-
|
|
1038
|
-
`)}getSessionDelegations(){return[...this.sessionDelegations]}getSessionDiscoveries(){return[...this.sessionDiscoveries]}addContextFromFile(e,t,s,r){let i=this.readContext(t);if(!i)return;let o=0;for(let a of s){if(o>=r)break;let l=this.extractSection(i,a);if(l&&l.trim().length>10){let u=r-o,d=l.length>u?l.slice(0,u)+"...":l;e.push(`${a}
|
|
1039
|
-
${d}`),o+=d.length}}}extractSection(e,t){let s=e.split(`
|
|
1040
|
-
`),r=s.findIndex(o=>o.trim()===t);if(r===-1)return null;let i=s.length;for(let o=r+1;o<s.length;o++)if(/^#{1,2}\s/.test(s[o])){i=o;break}return s.slice(r+1,i).join(`
|
|
1041
|
-
`).trim()}updateSection(e,t,s){let r=dt.join(this.contextDir,e);if(!ce.existsSync(r))return;let o=ce.readFileSync(r,"utf-8").split(`
|
|
1042
|
-
`),a=o.findIndex(h=>h.trim()===t);if(a===-1)return;let l=o.length;for(let h=a+1;h<o.length;h++)if(/^#{1,2}\s/.test(o[h])){l=h;break}let u=o.slice(0,a+1),d=o.slice(l),f=[...u,s,"",...d].join(`
|
|
1043
|
-
`);ce.writeFileSync(r,f,"utf-8")}appendToSection(e,t,s){let r=dt.join(this.contextDir,e);ce.existsSync(r)||this.init();let i=ce.readFileSync(r,"utf-8"),o=i.split(`
|
|
1044
|
-
`),a=o.findIndex(u=>u.trim()===t);if(a===-1){ce.writeFileSync(r,i+`
|
|
1045
|
-
`+s+`
|
|
1046
|
-
`,"utf-8");return}let l=a+1;for(;l<o.length;){let u=o[l].trim();if(/^#{1,2}\s/.test(u))break;l++}o.splice(l,0,s),ce.writeFileSync(r,o.join(`
|
|
1047
|
-
`),"utf-8")}}});function $g(n){let t=n.trim().toLowerCase(),s=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/gi,r=t.match(s)||[];return C0.test(t)?"ECOSYSTEM":T0.test(t)?"APPLICATION":R0.test(t)||r.length>=3?"SERVICE":O0.test(t)||r.length===2?"COMPONENT":"FILE"}var C0,T0,R0,O0,Eg=N(()=>{"use strict";C0=/\b(deploy|ci|cd|docker|docker-compose|gvisor|kubernetes|aws|gcp|vercel|heroku|server|cloud)\b/i,T0=/\b(full\s+system|complete\s+project|from\s+scratch|entire\s+application|prd|end-to-end|database.*api.*frontend)\b/i,R0=/\b(service|module|auth|login|session|api|controller|middleware|backend|database|schema)\b/i,O0=/\b(component|widget|screen|page|interface|view|button|sidebar|header|footer|form|ui)\b/i});function Cg(n){let e=n.toLowerCase();return/\b(how|why|what|tell\s+me|explain)\b/i.test(e)&&!/\b(build|fix|add)\b/i.test(e)?"QUESTION":/\b(research|find|search|docs|compare|analyze)\b/i.test(e)?"RESEARCH":/\b(fix|bug|issue|error|solve|debug)\b/i.test(e)?"DEBUGGING":/\b(refactor|cleanup|restructure|rewrite)\b/i.test(e)?"REFACTORING":/\b(design|architect|schema|blueprint|structure)\b/i.test(e)?"ARCHITECTURE":/\b(review|check|audit|verify)\b/i.test(e)?"REVIEW":"IMPLEMENTATION"}function Tg(n){let e=n.trim(),t=e.toLowerCase();if(!e)return 0;let r=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/i.test(e)?1:0,o=/\b(read_file|write_file|run_command|edit_file|search_codebase|list_dir|create_dir|delete_file|patch_file|search_and_replace)\b/i.test(e)?1:0,a=e.startsWith("/")?1:0,u=/\b(something|fix\s+it|make\s+better|do\s+stuff|change\s+things|some\s+file|مشكلة|شيء)\b/i.test(t)?1:0,d=.4*r+.3*o+.3*a-.5*u;return Math.max(0,Math.min(1,d))}var Rg=N(()=>{"use strict"});function Pg(n){let e=n.trim();if(e.length<20||Vt(e)||Og.test(e)||e.includes("```")||I0.test(e)||/\/[\w-]+\.[\w]+/.test(e)||e.length<60&&Og.test(e))return null;for(let{pattern:t,question:s,choices:r}of P0)if(t.test(e))return e.length>40&&/\b(called|named|using|with|for)\b/i.test(e)?null:{question:s,choices:r,context:e};return null}function Ig(n,e){let t=n.trim().toLowerCase(),s=t.split(/[,\s]+/).filter(i=>/^[a-z]$/.test(i));if(s.length>0)return s.map(i=>{let o=i.charCodeAt(0)-97;return e.choices[o]?.value}).filter(i=>i!==void 0);let r=t.split(/[,\s]+/).filter(i=>/^\d+$/.test(i));return r.length>0?r.map(i=>{let o=parseInt(i,10)-1;return e.choices[o]?.value}).filter(i=>i!==void 0):[t]}var P0,Og,I0,Mg=N(()=>{"use strict";un();P0=[{pattern:/\b(create|make|build)\s+(a|an|the)?\s*(app|application|project)\b/i,question:"What type of application would you like to create?",choices:[{label:"Web application (React/Next.js)",value:"web"},{label:"CLI tool (Node.js)",value:"cli"},{label:"API server (Express/Fastify)",value:"api"},{label:"Something else (please describe)",value:"other"}]},{pattern:/\b(refactor|rewrite|restructure)\s+(the\s+)?(entire|whole|all)\b/i,question:"Large-scale refactoring detected. How would you like to proceed?",choices:[{label:"Incremental \u2014 one module at a time",value:"incremental"},{label:"Full rewrite \u2014 replace everything",value:"full"},{label:"Just the architecture \u2014 keep implementations",value:"architecture"},{label:"Let me specify which parts",value:"specify"}]},{pattern:/\b(delete|remove|drop)\s+(all|every|the\s+entire)\b/i,question:"This is a destructive operation. Please confirm scope:",choices:[{label:"Yes, remove everything matching",value:"all"},{label:"Only unused/dead code",value:"unused"},{label:"Let me be more specific",value:"specify"},{label:"Cancel \u2014 don't delete anything",value:"cancel"}]},{pattern:/\b(setup|configure|install)\s+(the\s+)?(project|environment|dev)\b/i,question:"What environment are you setting up?",choices:[{label:"Development (local)",value:"dev"},{label:"Production deployment",value:"prod"},{label:"CI/CD pipeline",value:"ci"},{label:"Docker/containerized",value:"docker"}]},{pattern:/\b(fix|debug|solve)\s+(the\s+)?(issue|bug|problem|error)\b/i,question:"Can you provide more details about the issue?",choices:[{label:"Runtime error (crashes/exceptions)",value:"runtime"},{label:"Build/compile error",value:"build"},{label:"Logic bug (wrong behavior)",value:"logic"},{label:"Performance issue (slow)",value:"performance"}]}],Og=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|scss|html|vue|svelte|go|rs|java|c|cpp|h|rb|php|sql|sh|bash|toml|xml|env)/i,I0=/\b(fix|update|change|add|remove|rename|move|edit|read|show|cat|open)\s+(the\s+)?(typo|bug|error|import|line|function|variable|class|method|comment|style)/i});var Yr,vt,Qr,Jr,Lg=N(()=>{"use strict";Yr=O(require("fs")),vt=O(require("fs/promises")),Qr=O(require("path")),Jr=class{stack=[];workingDir;maxEntries;nextGroupId=1;constructor(e,t=200){this.workingDir=e,this.maxEntries=t}async record(e,t,s,r="hablas",i){let o=Qr.resolve(this.workingDir,e),a=null;try{Yr.existsSync(o)&&(a=await vt.readFile(o,"utf-8"))}catch{}let l={id:`undo_${Date.now()}_${this.stack.length}`,filePath:e,absolutePath:o,originalContent:a,newContent:t,toolName:s,agent:r,timestamp:Date.now(),undone:!1,groupId:i};return this.stack.push(l),this.stack.length>this.maxEntries&&(this.stack=this.stack.slice(-this.maxEntries)),l.id}beginGroup(){return`group_${this.nextGroupId++}`}async undo(e=1){let t=[],r=this.stack.filter(i=>!i.undone).reverse().slice(0,e);for(let i of r)try{i.originalContent===null?(Yr.existsSync(i.absolutePath)&&await vt.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await vt.mkdir(Qr.dirname(i.absolutePath),{recursive:!0}),await vt.writeFile(i.absolutePath,i.originalContent,"utf-8"),t.push({file:i.filePath,success:!0})),i.undone=!0}catch(o){t.push({file:i.filePath,success:!1,error:o.message})}return t}async undoGroup(e){let t=this.stack.filter(r=>r.groupId===e&&!r.undone).reverse(),s=[];for(let r of t)try{r.originalContent===null?Yr.existsSync(r.absolutePath)&&await vt.unlink(r.absolutePath):await vt.writeFile(r.absolutePath,r.originalContent,"utf-8"),r.undone=!0,s.push({file:r.filePath,success:!0})}catch(i){s.push({file:r.filePath,success:!1,error:i.message})}return s}async undoAll(){return this.undo(this.getUndoableCount())}getUndoableCount(){return this.stack.filter(e=>!e.undone).length}getRecent(e=15){return this.stack.filter(t=>!t.undone).slice(-e).reverse()}getModifiedFiles(){let e=new Set;for(let t of this.stack.filter(s=>!s.undone))e.add(t.filePath);return Array.from(e)}formatList(e=15){let t=this.getRecent(e);if(t.length===0)return" No changes to undo";let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=this.formatAge(o.timestamp),l=o.originalContent===null?"created":"modified",u=o.agent!=="hablas"?` [@${o.agent}]`:"";s.push(` ${i+1}. ${o.filePath} \u2014 ${l} by ${o.toolName}${u} (${a})`)}let r=this.getUndoableCount();return r>e&&s.push(` ... and ${r-e} more`),s.join(`
|
|
1048
|
-
`)}formatAge(e){let t=Date.now()-e,s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}size(){return this.stack.length}clear(){this.stack=[]}}});function M0(n,e){let t=[],s;for(Dg.lastIndex=0;(s=Dg.exec(n))!==null;){let r=s[1],i=Te.resolve(e,r);ft.existsSync(i)&&t.push(r)}return[...new Set(t)]}function L0(n,e,t){let s=[],r=Te.extname(e),i=Te.dirname(Te.resolve(t,e));if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(r)){let o;for(Ng.lastIndex=0;(o=Ng.exec(n))!==null;){let a=o[1]||o[2];if(!a||!a.startsWith(".")&&!a.startsWith("/"))continue;let l=D0(a,i);l&&s.push(Te.relative(t,l))}}else if(r===".py"){let o;for(Fg.lastIndex=0;(o=Fg.exec(n))!==null;){let a=o[1]||o[2];if(!a)continue;let l=a.replace(/\./g,"/")+".py",u=Te.resolve(i,l);ft.existsSync(u)&&s.push(Te.relative(t,u))}}return[...new Set(s)]}function D0(n,e){let t=[".ts",".tsx",".js",".jsx",".mjs",".cjs"],s=Te.resolve(e,n);if(ft.existsSync(s)&&ft.statSync(s).isFile())return s;for(let r of t){let i=s+r;if(ft.existsSync(i))return i}for(let r of t){let i=Te.join(s,`index${r}`);if(ft.existsSync(i))return i}return null}function jg(n,e,t){let s=t?.maxFiles||10,r=t?.maxTokens||8e3,i=t?.followImports!==!1,o=M0(n,e),a=[],l=new Set,u=0;for(let d of o){if(a.length>=s||u>=r)break;if(!l.has(d)){l.add(d);try{let f=Te.resolve(e,d),h=ft.readFileSync(f,"utf-8"),m=h.split(`
|
|
1049
|
-
`).length,p=Math.ceil(h.length/4);if(p>4e3){let g=h.split(`
|
|
1050
|
-
`).slice(0,200).join(`
|
|
1051
|
-
`)+`
|
|
1052
|
-
...(truncated)`,x=Math.ceil(g.length/4);u+x<=r&&(a.push({path:d,content:g,source:"mentioned",lineCount:200}),u+=x)}else if(u+p<=r&&(a.push({path:d,content:h,source:"mentioned",lineCount:m}),u+=p,i)){let g=L0(h,d,e);for(let x of g.slice(0,5)){if(a.length>=s||u>=r)break;if(!l.has(x)){l.add(x);try{let A=Te.resolve(e,x),$=ft.readFileSync(A,"utf-8"),_=Math.ceil($.length/4),y=$.split(`
|
|
1053
|
-
`).length;if(_>2e3){let v=$.split(`
|
|
1054
|
-
`).slice(0,100).join(`
|
|
1055
|
-
`)+`
|
|
1056
|
-
...(truncated)`,b=Math.ceil(v.length/4);u+b<=r&&(a.push({path:x,content:v,source:"imported",lineCount:100}),u+=b)}else u+_<=r&&(a.push({path:x,content:$,source:"imported",lineCount:y}),u+=_)}catch{}}}}}catch{}}}return{files:a,totalTokensEstimate:u,mentionedPaths:o}}function Hg(n){if(n.files.length===0)return"";let e=["## Referenced Files"];for(let t of n.files){let s=t.source==="imported"?" (imported)":"";e.push(`### ${t.path}${s} (${t.lineCount} lines)`),e.push("```"),e.push(t.content),e.push("```")}return e.join(`
|
|
1057
|
-
`)}var ft,Te,Dg,Ng,Fg,Bg=N(()=>{"use strict";ft=O(require("fs")),Te=O(require("path")),Dg=/(?:^|\s|['"`])([.\w\-/\\]+\.(?:ts|js|tsx|jsx|py|go|rs|java|c|cpp|h|css|scss|html|vue|svelte|json|yaml|yml|toml|md|sql|sh|env|xml))\b/gi,Ng=/(?:import\s+.*?\s+from\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\))/g,Fg=/(?:from\s+(\S+)\s+import|import\s+(\S+))/g});var qg={};Ne(qg,{runSetupWizard:()=>Vl});function be(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function F0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function Vl(n){let e=Ug.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${qt}${Ke} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${L}`),console.log(`${qt}${Ke} hablas \u2014 Setup Wizard${L}`),console.log(`${K} Configure your AI provider and model${L}`),console.log(`${qt}${Ke} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${L}`),console.log(),console.log(`${qt} Choose your setup:${L}`),console.log(),console.log(` ${N0}${qt}1${L}. ${qt}Hablas Integrated Engine${L} ${wt}(instant \u2014 no setup needed)${L}`),console.log(` ${K}Pre-configured cloud AI, ready to use immediately${L}`),console.log(),console.log(` ${Ke}${qt}2${L}. ${qt}Custom Provider${L} ${K}(bring your own API key)${L}`),console.log(` ${K}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${L}`),console.log(),(await be(e,` ${K}Your choice (1-2):${L} `)).trim()){case"1":{n.provider=Kt.provider,n.apiUrl=Kt.apiUrl,n.apiKey=F0(),n.model=Kt.model,gt(n),nt({name:Kt.name,apiUrl:Kt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:Kt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Hablas Integrated Engine activated!${L}`),console.log(`${K} Model: ${Kt.model}${L}`),console.log(`${K} API: ${Kt.apiUrl}${L}`),console.log(`${K} No API key needed \u2014 everything is pre-configured.${L}`);break}case"2":{switch(console.log(),console.log(`${K} Select your provider:${L}`),console.log(` ${Ke}a${L}. Ollama (local, free, private)`),console.log(` ${Ke}b${L}. OpenAI API`),console.log(` ${Ke}c${L}. Groq (fast, free tier)`),console.log(` ${Ke}d${L}. OpenRouter (many models)`),console.log(` ${Ke}e${L}. Together AI`),console.log(` ${Ke}f${L}. DeepSeek`),console.log(` ${Ke}g${L}. Custom OpenAI-compatible API`),console.log(` ${Ke}h${L}. NVIDIA NIM (powerful cloud models)`),console.log(),(await be(e,` ${K}Your choice (a-h):${L} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await be(e,` ${K}Ollama host [http://localhost:11434]:${L} `);r.trim()&&(n.ollamaHost=r.trim());let i=await be(e,` ${K}Model [qwen2.5-coder:7b]:${L} `);i.trim()&&(n.model=i.trim()),gt(n),console.log(),console.log(`${wt} \u2713 Configured for Ollama${L}`),console.log(`${K} Model: ${n.model}${L}`),console.log(`${K} Host: ${n.ollamaHost}${L}`),console.log(`${K} Make sure Ollama is running: ollama serve${L}`);break}case"b":{let r=await be(e,` ${K}OpenAI API Key (sk-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await be(e,` ${K}Model [gpt-4o]:${L} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",gt(n),nt({name:"OpenAI",apiUrl:"https://api.openai.com/v1",apiKey:r.trim(),models:["gpt-4o","gpt-4o-mini","gpt-4-turbo","o1","o3-mini"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for OpenAI${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"c":{let r=await be(e,` ${K}Groq API Key (gsk_...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await be(e,` ${K}Model [llama-3.3-70b-versatile]:${L} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",gt(n),nt({name:"Groq",apiUrl:"https://api.groq.com/openai/v1",apiKey:r.trim(),models:["llama-3.3-70b-versatile","llama-3.1-70b-versatile","mixtral-8x7b-32768","gemma2-9b-it"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for Groq${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"d":{let r=await be(e,` ${K}OpenRouter API Key (sk-or-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await be(e,` ${K}Model [anthropic/claude-3.5-sonnet]:${L} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",gt(n),nt({name:"OpenRouter",apiUrl:"https://openrouter.ai/api/v1",apiKey:r.trim(),models:["openai/gpt-4o","anthropic/claude-3.5-sonnet","google/gemini-2.0-flash-001","deepseek/deepseek-r1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for OpenRouter${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"e":{let r=await be(e,` ${K}Together API Key:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await be(e,` ${K}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${L} `);n.provider="custom",n.apiUrl="https://api.together.xyz/v1",n.apiKey=r.trim(),n.model=i.trim()||"meta-llama/Llama-3.3-70B-Instruct-Turbo",gt(n),nt({name:"Together",apiUrl:"https://api.together.xyz/v1",apiKey:r.trim(),models:["meta-llama/Llama-3.3-70B-Instruct-Turbo","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for Together AI${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"f":{let r=await be(e,` ${K}DeepSeek API Key:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`);break}let i=await be(e,` ${K}Model [deepseek-chat]:${L} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",gt(n),nt({name:"DeepSeek",apiUrl:"https://api.deepseek.com/v1",apiKey:r.trim(),models:["deepseek-chat","deepseek-coder","deepseek-reasoner"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for DeepSeek${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"g":{let r=await be(e,` ${K}Provider name:${L} `);if(!r.trim()){console.log(`${xt} \u26A0 Cancelled${L}`);break}let i=await be(e,` ${K}API base URL:${L} `);if(!i.trim()){console.log(`${xt} \u26A0 URL is required \u2014 cancelled${L}`);break}let o=await be(e,` ${K}API Key (leave empty if none):${L} `),a=await be(e,` ${K}Default model ID:${L} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",gt(n),nt({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for ${r.trim()}${L}`),console.log(`${K} URL: ${i.trim()}${L}`),console.log(`${K} Model: ${n.model}${L}`);break}case"h":{let r=await be(e,` ${K}NVIDIA API Key (nvapi-...):${L} `);if(!r.trim()){console.log(`${xt} \u26A0 No key provided \u2014 cancelled${L}`),console.log(`${K} Get your key at: https://build.nvidia.com/${L}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(Dn(),gc));console.log(),console.log(`${K} Available NVIDIA models:${L}`),i.models.forEach((u,d)=>{console.log(` ${Ke}${d+1}${L}. ${u}`)}),console.log();let o=await be(e,` ${K}Model number [1]:${L} `),a=parseInt(o.trim())-1,l=i.models[a]||i.defaultModel;n.provider="nvidia",n.apiUrl=i.apiUrl,n.apiKey=r.trim(),n.model=l,gt(n),nt({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${wt} \u2713 Configured for NVIDIA NIM${L}`),console.log(`${K} Model: ${l}${L}`),console.log(`${K} API: ${i.apiUrl}${L}`);break}default:console.log(`${xt} \u26A0 Invalid choice${L}`)}break}default:console.log(`${xt} \u26A0 Invalid choice \u2014 please select 1 or 2${L}`)}console.log(),console.log(`${K} Run 'hablas' to start chatting!${L}`),console.log(),e.close()}var Ug,Ke,wt,xt,K,qt,L,N0,Kt,zl=N(()=>{"use strict";Ug=O(require("readline"));hr();vi();Ke="\x1B[36m",wt="\x1B[32m",xt="\x1B[33m",K="\x1B[2m",qt="\x1B[1m",L="\x1B[0m",N0="\x1B[35m";Kt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var Ft={};Ne(Ft,{activeCollabManager:()=>Re,runSingleCommand:()=>G0,startRepl:()=>Ql});function U0(){return!pt.existsSync(Yl)}function Kg(){return pt.existsSync(j0)}function q0(){let n=Mt.dirname(Yl);pt.existsSync(n)||pt.mkdirSync(n,{recursive:!0}),pt.writeFileSync(Yl,new Date().toISOString(),"utf-8")}async function K0(n,e=10){let t=n.split(/(\s+)/);for(let s of t)process.stdout.write(s),await new Promise(r=>setTimeout(r,e))}async function Vg(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:u,onToolCall:d,skipTools:f}=r,h=r.reactEngine??ys(),m=r.errorRecovery??bs(),p=n.getMessages().filter(b=>b.role==="user").pop()?.content||"Solo Execution",x={taskTitle:p.length>45?p.slice(0,45)+"...":p,currentPhase:"Cognitive Reasoning & Planning",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:"Analyzing workspace & preparing reasoning path",roster:{Hablas:"active",Emma:"pending",Bob:"pending",Alex:"pending",David:"pending"}},A=new Un;A.render(x);let $=new ze("Hablas is thinking");$.start();let _=b=>{$&&($.stop(b),$=null)},y=dg({autoMode:o,interactive:i,confirm:a?b=>a.confirm(b):void 0,confirmDangerous:a?b=>a.confirmDangerous(b):void 0});await jr({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:h,errorRecovery:m,logger:l,io:{onAssistantText:async b=>{_(),console.log(qn("Hablas","Team Leader")),await K0(Kn(b))},onToolStart:(b,w)=>{_(),x.currentActivity=`Executing: ${b}`,A.render(x),console.log(gu(b,w)),$=new ze("Continuing"),$.start()},onToolEnd:(b,w,S,T)=>{_(),console.log(yu(w,S,T))},onNotice:(b,w)=>{_(),console.log(w==="retry"?c.muted(` \u21BB ${b}`):B(b))},onError:b=>{_(),b.includes("ECONNREFUSED")?console.log(He("Connection lost","Check your provider connection or run /provider test")):/timeout/i.test(b)?console.log(He("Request timed out (120s)","The API is slow. Try again or use a faster model.")):b.includes("429")?console.log(He("Rate limited by API","Wait a moment and try again, or switch providers.")):b.includes("model")?console.log(He("Model error","Check model availability: /models")):console.log(He(`Error: ${b}`,"Try again or check /status"))},onToolCall:()=>{d&&d()}},safetyPolicy:y,abortSignal:u,skipTools:f,maxIterations:H0}),_()}async function Ql(n,e){Kp();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=ee=>pt.existsSync(Mt.join(ee,".git"));if(!s(t)&&!n.team?.enabled)console.log(` ${c.warning("\u26A0")} ${c.secondary("Not in a Git repository. Versioning and auto-sync features are limited.")}
|
|
1058
|
-
`);else if(n.team?.enabled&&!s(t)){console.log(`
|
|
1059
|
-
${c.accent("\u2726")} ${c.strong("Team Mode Strategy Required")}`),console.log(` ${c.muted("Collaboration requires a stable Git repository root.")}
|
|
1060
|
-
`);let te=await new us(t).prompt(` ${c.primary("\u203A")} Specify repo path OR type 'init' to start here: `);if(te.trim().toLowerCase()==="init")try{(0,Wg.execSync)("git init",{cwd:t,stdio:"ignore"}),console.log(` ${c.success("\u2713")} Git repository initialized in ${c.highlight(t)}
|
|
1061
|
-
`)}catch{console.log($e("Failed to initialize Git. Please run git init manually.")),process.exit(1)}else{let _e=Mt.resolve(t,te.trim());pt.existsSync(_e)&&s(_e)?(t=_e,n.workingDirectory=t,console.log(` ${c.success("\u2713")} Context switched to repository: ${c.highlight(t)}
|
|
1062
|
-
`)):(console.log($e(`Path "${_e}" is not a valid Git repository.`)),process.exit(1))}}let r=Fe(n),i=new as(t,n),o=new en(n),a=new us(t),l=mr(),u=new gr,d=new fs(t),f=new In(t),h=new Vr,m=new Hr(n);m.setToolRegistry(i);let p=new Br,g=new Wr(p).attach(),x=new qr(n,{tokenBudget:500,maxChars:140});if(m.setChannel(p),n.team?.enabled){let ee=n.team.user||"developer",te=n.team.key||"default-key";Re=new is(t,n,ee,te),await Re.init()&&console.log(` ${c.success("\u2713")} ${c.muted("[Team]")} Scoped cooperative sync initialized successfully.
|
|
1063
|
-
`)}let A=new Jr(t),$=new Un;f.init();let _=null;n.context?.hablasCoreEnabled&&(_=new zr(t),_.init());let y=await yn(t,n),v=l.getActive(),b=v?v.systemPrompt:Wn,w=bn(b,y,d,f),S=ys({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:150,minConfidence:.6}),T=bs(3),M=new tn(w,n.historySize),k=jn();k=Fi(k),fn(k);let F=0,H=0,V=Date.now(),C=n.autoMode||!1,E=0,Y=new AbortController;process.on("SIGINT",()=>{let ee=Date.now();if(ee-E<B0){console.log(Zi({turns:F,duration:Date.now()-V,toolCalls:H}));let te=Re?Re.shutdown():Promise.resolve();Promise.resolve(te).finally(()=>process.exit(0)),setTimeout(()=>process.exit(0),2e3);return}E=ee,Y.abort(),Y=new AbortController,process.stdout.write(`
|
|
1064
|
-
`),console.log(B("Operation cancelled \u2014 press Ctrl+C again to exit"))});let D=Es(n);if(console.log(uu(n.model,t)),n.provider==="custom"&&console.log(he(`Provider: ${D}`)),C&&console.log(he("Auto mode enabled \u2014 tool confirmations skipped (plan approval still required)")),(U0()||!Kg())&&(console.log(pu()),console.log(""),console.log(he("First run detected \u2014 launching setup wizard...")),console.log(""),a.close(),await Vl(n),q0(),r=Fe(n),a.reinitialize()),Kg()){let ee=new ze("Connecting");ee.start();let te=await r.checkConnection();if(ee.stop(te?"ready":void 0),te){let _e=await r.listModels();console.log(J(`Connected \xB7 ${_e.length} models available`)),n.provider==="ollama"&&!_e.includes(n.model)&&console.log(B(`Model "${n.model}" not found. Pull: ollama pull ${n.model}`))}else n.provider==="custom"?console.log(He(`Cannot connect to ${n.apiUrl}`,"Check your --api-url and --api-key, or run /provider test")):n.provider==="nvidia"?console.log(He("Cannot connect to NVIDIA NIM","Check your API key or run: hablas --setup")):console.log(He("Cannot connect to Ollama","Start it with: ollama serve \u2014 or switch provider: /provider"))}console.log(du()),console.log();let X=!0;for(;X;)try{let te=(await a.prompt(` ${c.primary("\u203A")} `)).trim();if(!te)continue;if(te.startsWith("/")){if(await qu(te,n,r,i,o,M,t,a,F,l,u,d,ue=>{r=ue},f,h,A,m)==="quit"){X=!1;break}continue}e.info({input:te},"Processing user input");let _e=Ic(te),Q=zg(_e,t);if(F++,console.log(bu(F)),k=ji(k),fn(k),!C){let q=Pg(Q);if(q){console.log(Su(q));let ue=await a.prompt(` ${c.muted("\u203A")} `),Ge=Ig(ue,q);Q=`${Q}
|
|
1065
|
-
[Clarification: ${Ge.join(", ")}]`}}let Ae=jg(Q,t,{maxFiles:8,maxTokens:6e3});if(Ae.files.length>0){let q=Hg(Ae);M.addUserMessage(`[Auto-loaded ${Ae.files.length} file(s): ${Ae.mentionedPaths.join(", ")}]
|
|
1066
|
-
${q}`,{priority:"low",tags:["auto-inject"]})}if(n.team?.enabled&&Re){let q=n.team?.user||Re.getLocalState().my_username,ue=Ae.mentionedPaths||[];if(ue.length>0){let Ge=await Re.fetchLocks(),I=ue.map(Z=>Ge.find(P=>P.file_path===Z&&P.locked_by!==q)).filter(Z=>!!Z);if(I.length>0){let Z=I[0];console.log(`
|
|
1067
|
-
${c.architect("\u25C6")} ${c.strong("@Consul")} [Coordinator] detected an active lock held by a teammate.`),console.log(`
|
|
1068
|
-
${c.error("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}`),console.log(` ${c.error("\u2551")} ${c.strong("\u{1F512} FILE LOCKED BY TEAMMATE")} ${c.error("\u2551")}`),console.log(` ${c.error("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")}`),console.log(` ${c.error("\u2551")} File ${c.highlight(Z.file_path.padEnd(44))} held by ${c.strong(`@${(Z.locked_by||"").padEnd(12)}`)} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} Context: ${c.muted((Z.lock_context||"\u2014").slice(0,61).padEnd(61))} ${c.error("\u2551")}`),console.log(` ${c.error("\u2551")} @Consul halted this turn to prevent a Git conflict on the shared repo. ${c.error("\u2551")}`),console.log(` ${c.error("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}`);for(let P of I)await Re.sendMessage(P.locked_by,`@${q} needs to edit ${P.file_path}. Please release the lock when you can.`);console.log(` ${c.muted("@Consul notified the teammate(s). Try again once the lock is released, or coordinate directly.")}
|
|
1069
|
-
`);continue}for(let Z of ue)if(!await Re.acquireLock(Z,Q.slice(0,100))){console.log(`
|
|
1070
|
-
${c.warning("\u26A0")} ${c.strong("@Consul")}: a teammate locked ${c.highlight(Z)} first. Halting to avoid a conflict.
|
|
1071
|
-
`);continue}}Re.setActivity(Q.slice(0,80))}if(n.agents.enabled&&n.agents.orchestration==="auto"){let q=Cg(Q),ue=Tg(Q),Ge="SOLO",I="FILE";ue<.7&&!Vt(Q)?Ge="NORMALIZER":Vt(Q)||q==="QUESTION"?Ge="SOLO":(I=$g(Q),Ge=I==="FILE"||I==="COMPONENT"?"SOLO":"TEAM");let Z={bob:"architect",alex:"coder",david:"researcher",hablas:"planner",emma:"product-manager"};if(Ge==="SOLO"){let G=Oi(Q).find(ne=>ne!=="hablas")||"alex";q!=="QUESTION"&&!Vt(Q)&&(k=Bi(k,G),fn(k)),M.addUserMessage(Q)}else{let P=Oi(Q),G=Uc(Q,P),ne={taskTitle:Q.length>40?Q.slice(0,37)+"...":Q,currentPhase:Ge==="NORMALIZER"?"Requirements Normalization":"Strategic Planning",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:Ge==="NORMALIZER"?"Refining vague user intent":"Orchestrating specialized team",roster:{Hablas:"active",Emma:P.includes("emma")?"pending":"done",Bob:P.includes("bob")?"pending":"done",Alex:P.includes("alex")?"pending":"done",David:P.includes("david")?"pending":"done"}};console.log(`
|
|
1072
|
-
`+eo(ne));let pe=i.getOllamaTools(),ie=new Kr(p,m,x,n),{finalSynthesis:Oe,synthesisOk:We}=await ie.run(Q,G,pe,{abortSignal:Y?.signal,peerReview:I==="SERVICE"||I==="APPLICATION"});console.log(qn("Hablas","Team Leader")),console.log(Kn(Oe)),M.addAssistantMessage(We?Oe:`[Team Execution Summary]
|
|
1073
|
-
|
|
1074
|
-
${Oe}`),await Gg(n,t);continue}}else M.addUserMessage(Q);Y=new AbortController,S.startTurn(),T.resetTurn(),await Vg(M,r,i,o,{interactive:!0,autoMode:C,input:a,logger:e,config:n,abortSignal:Y.signal,reactEngine:S,errorRecovery:T,skipTools:!1,onToolCall:()=>{H++,k=Hi(k,"tool_call"),fn(k)}}),await Gg(n,t)}catch(ee){if(ee.code==="ERR_USE_AFTER_CLOSE")break;if(ee.name==="AbortError")continue;console.log($e(ee.message)),e.error(ee,"REPL error")}a.close(),Re&&await Re.shutdown(),console.log(Zi({turns:F,duration:Date.now()-V,toolCalls:H}))}async function G0(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=Fe(e),i=new as(s,e),o=new en(e),a=new fs(s),l=await yn(s,e),u=bn(Wn,l,a),d=new tn(u,e.historySize),f=zg(n,s);d.addUserMessage(f),await Vg(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function zg(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=Mt.resolve(e,i);pt.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}async function Gg(n,e){if(!(n.team?.enabled&&Re))return;if(await Re.releaseAllMyLocks(),!n.workspace?.autoPush){console.log(`
|
|
1075
|
-
${c.info("\u2139")} ${c.strong("@Consul")}: "Changes tracked. Auto-push is off \u2014 commit & push manually when ready."
|
|
1076
|
-
`);return}let{execSync:t}=await import("child_process"),s=r=>t(r,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).trim();try{if(!s("git status --porcelain")){console.log(`
|
|
1077
|
-
${c.muted("@Consul: workspace clean \u2014 nothing to push.")}
|
|
1078
|
-
`);return}let i=s("git rev-parse --abbrev-ref HEAD");if(!i||i==="HEAD"){console.log(`
|
|
1079
|
-
${c.warning("\u26A0")} ${c.strong("@Consul")}: detached HEAD \u2014 skipping auto-push. Checkout a branch first.
|
|
1080
|
-
`);return}let o="";try{o=s("git config --get remote.origin.url")}catch{}if(!o){console.log(`
|
|
1081
|
-
${c.warning("\u26A0")} ${c.strong("@Consul")}: no 'origin' remote configured \u2014 committed locally, skipping push.
|
|
1082
|
-
`),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');return}console.log(`
|
|
1083
|
-
${c.success("\u{1F4C1}")} ${c.muted("[Git]")} ${c.strong("@Consul")} committing & pushing to ${c.highlight(i)} \u2192 ${c.muted(o)} ...`),s("git add -A"),s('git commit -m "sync(team): automatic updates via @Consul" --no-verify');try{s(`git push origin ${i}`)}catch{s(`git push --set-upstream origin ${i}`)}console.log(` ${c.success("\u2713")} ${c.strong("@Consul")}: "Pushed to ${i}. Teammates can pull the latest."
|
|
1084
|
-
`)}catch(r){let i=r.stderr||r.message||"unknown error",o=/authentication|permission|denied|403|401/i.test(i)?"Check your Git credentials / token for this remote.":/non-fast-forward|rejected|behind/i.test(i)?"Remote has newer commits \u2014 pull/rebase first, then push.":"Resolve the issue and push manually.";console.log(` ${c.warning("\u26A0")} ${c.strong("@Consul")}: auto-push failed. ${c.muted(o)}
|
|
1085
|
-
`)}}var pt,Wg,Mt,Jl,Re,Yl,j0,H0,B0,Ct=N(()=>{"use strict";Ku();ua();pt=O(require("fs")),Wg=require("child_process"),Mt=O(require("path")),Jl=O(require("os"));Nn();Fp();ya();ba();Up();hr();Ha();Gp();zp();wi();un();mg();yg();bg();Sg();_g();Hn();Kl();Ag();kg();Eg();Rg();Mg();gn();Lg();Bg();zl();Dl();Fl();ql();Re=null,Yl=Mt.join(Jl.homedir(),".hablas",".first_run_done"),j0=Mt.join(Jl.homedir(),".hablas","config.json"),H0=150,B0=1500});function Lt(n){let e=Zl.join(Yg.homedir(),".hablas","logs");Xr.existsSync(e)||Xr.mkdirSync(e,{recursive:!0});let t=Zl.join(e,`session-${Date.now()}.log`);return(0,Xl.default)({level:"info"},Xl.default.destination({dest:t,sync:!1}))}var Xl,Zl,Yg,Xr,ec=N(()=>{"use strict";Xl=O(Ml()),Zl=O(require("path")),Yg=O(require("os")),Xr=O(require("fs"))});var ey={};Ne(ey,{createApiServer:()=>Zg,startApiServer:()=>Y0});function W0(){try{return JSON.parse(Qg.readFileSync(Xg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function Zg(n){let e=Lt(n),t=z0(n);return Jg.createServer(async(r,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.setHeader("Content-Type","application/json"),r.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(r.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(r.method==="POST"||r.method==="PUT")try{let l=[];for await(let d of r)l.push(d);let u=Buffer.concat(l).toString();u&&(o=JSON.parse(u))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===r.method&&r.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${r.method} ${r.url}`}));return}try{let l={method:r.method||"GET",path:r.url||"/",body:o,headers:r.headers},u=await a.handler(l);i.writeHead(u.status),i.end(JSON.stringify(u.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function z0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:V0,uptime:process.uptime()}})},{method:"GET",path:"/api/v1/agents",handler:async()=>({status:200,body:{agents:[{name:"coder",description:"Code generation and modification",status:"available"},{name:"reviewer",description:"Code review and quality analysis",status:"available"},{name:"architect",description:"System architecture design",status:"available"},{name:"devops",description:"Deployment and infrastructure",status:"available"},{name:"researcher",description:"Documentation and research",status:"available"},{name:"planner",description:"Task decomposition and planning",status:"available"},{name:"debugger",description:"Error analysis and fixing",status:"available"}]}})},{method:"GET",path:"/api/v1/models",handler:async()=>({status:200,body:{current:n.model,provider:n.provider,host:n.ollamaHost}})},{method:"POST",path:"/api/v1/chat",handler:async e=>{let{message:t,agent:s}=e.body;return t?{status:200,body:{response:`[${s||"coder"}] Received: ${t}`,agent:s||"coder",model:n.model}}:{status:400,body:{error:"message field is required"}}}},{method:"POST",path:"/api/v1/plan",handler:async e=>{let{task:t}=e.body;return t?{status:200,body:{plan:{task:t,steps:[{step:1,description:"Analyze requirements",agent:"researcher"},{step:2,description:"Design architecture",agent:"architect"},{step:3,description:"Implement code",agent:"coder"},{step:4,description:"Review and test",agent:"reviewer"}]}}}:{status:400,body:{error:"task field is required"}}}},{method:"POST",path:"/api/v1/execute",handler:async e=>{let{command:t}=e.body;return t?n.api.enabled?{status:200,body:{message:"Command queued for execution",command:t}}:{status:403,body:{error:"API execution not enabled"}}:{status:400,body:{error:"command field is required"}}}},{method:"GET",path:"/api/v1/stats",handler:async()=>({status:200,body:{sessions:0,messages:0,uptime:process.uptime(),model:n.model,provider:n.provider}})}]}function Y0(n){return new Promise((e,t)=>{let s=Zg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var Jg,Qg,Xg,V0,ty=N(()=>{"use strict";Jg=O(require("http")),Qg=O(require("fs")),Xg=O(require("path"));ec();V0=W0()});var Q0={};Ne(Q0,{CLI_VERSION:()=>xs});module.exports=cy(Q0);var hc=O(pc(),1),{program:oE,createCommand:aE,createArgument:lE,createOption:cE,CommanderError:uE,InvalidArgumentError:dE,InvalidOptionArgumentError:fE,Command:mc,Argument:pE,Option:hE,Help:mE}=hc.default;Ct();hr();ec();var ny=O(require("fs")),sy=O(require("path"));function J0(){try{let n=sy.resolve(__dirname,"..","package.json");return JSON.parse(ny.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var xs=J0(),oe=new mc;oe.name("hablas").description(`hablas CLI v${xs} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(xs).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 (OpenAI-compatible)").option("--api-key <key>","API key for custom/nvidia provider").option("--auto","Auto mode \u2014 skip all tool confirmations").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--theme <name>","UI theme: dark | light | galaxy | ocean | forest").option("--dashboard","Launch TUI dashboard mode").option("--team","Enable hybrid cooperative sync mode with teammates").option("--user <name>","Teammate username for coordination").option("--team-key <password>","Teammate password/key for secure connection encryption").option("--setup","Run first-time setup wizard");oe.command("create <description>").description("Generate a full project from a description").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=oe.opts(),s=Ze({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});t.auto&&(s.autoMode=!0);let r=Lt(s),{runSingleCommand:i}=await Promise.resolve().then(()=>(Ct(),Ft)),o=`Generate a complete project: ${n}${e.stack?` using ${e.stack}`:""}${e.withTests?" with comprehensive tests":""}${e.withDocker?" with Docker setup":""}. Create all necessary files.`;await i(o,s,r)});oe.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=oe.opts(),e=Ze({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=Lt(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(hn(),Bn)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),u=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(Ct(),Ft));await d(u,e,t)});oe.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=oe.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Lt(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(hn(),Bn)),a=t.workingDirectory||process.cwd(),l=await r(a),u=await i(a,20),d=o(u,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(Ct(),Ft));await f(d,t,s)});oe.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",xs).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=oe.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=Lt(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(hn(),Bn)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:u}=await Promise.resolve().then(()=>(Ct(),Ft));await u(l,t,s)});oe.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=oe.opts(),t=Ze({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{runSecurityScan:s,formatScanResults:r}=await Promise.resolve().then(()=>(Gi(),Jc)),i=t.workingDirectory||process.cwd();console.log(`
|
|
911
|
+
`);return{results:t,finalSynthesis:c,synthesisOk:!1}}}});function nt(n){switch(n){case"Hablas":return u.leader;case"Bob":return u.architect;case"Alex":return u.engineer;case"David":return u.analyst;case"Emma":return u.product;default:return u.primary}}function dr(n){return n==="Hablas"?"\u2605":"\u25C6"}function Yn(n,e=140){let t=(n||"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}function Ca(n){return n==="Hablas"?"Team Leader":n==="Bob"?"Architect":n==="Alex"?"Engineer":n==="David"?"Data Analyst":n==="Emma"?"Product Manager":"Specialist"}var fr,Qp=N(()=>{"use strict";rn();fr=class{channel;opts;attached=!1;listener;lastThinking=null;lastLine="";state={taskTitle:"Autonomous Codebase Engineering",currentPhase:"Initializing",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:"Analyzing workspace",roster:{Hablas:"active",Emma:"pending",Bob:"pending",Alex:"pending",David:"pending"}};constructor(e,t={}){this.channel=e,this.opts={hideThinking:t.hideThinking??!1,hideActs:t.hideActs??!1,maxChars:t.maxChars??140},this.listener=s=>this.handle(s)}attach(){return this.attached?this:(this.channel.onEvent(this.listener),this.attached=!0,this)}detach(){return this.attached?(this.channel.offEvent(this.listener),this.attached=!1,this):this}handle(e){switch(e.type){case"phase":return this.renderPhase(e);case"handoff":return this.renderHandoff(e);case"thinking":return this.renderThinking(e);case"speak":return this.renderSpeak(e);case"act":return this.renderAct(e);case"observe":return this.renderObserve(e);case"review":return this.renderReview(e);case"summary":return this.renderSummary(e);case"decision":return this.renderDecision(e);case"done":return this.renderDone(e);case"error":return this.renderError(e)}}renderPhase(e){let t=(e.content||"").toString();t&&(this.state.currentPhase=t,(t.includes("compiling")||t.includes("report")||t.includes("synthesizing"))&&(this.state.activeAgent="Hablas",this.state.activeAgentTitle="Team Leader",this.state.roster.Hablas="active",this.state.currentActivity="Compiling individual reports and synthesizing final unified solution"),this.print(`
|
|
912
|
+
${u.accent("\u25B8")} ${u.strong(t.toUpperCase())}`),this.lastThinking=null)}renderHandoff(e){let t=e.agent,s=e.to||"";if(!s)return;let r=nt(t),i=nt(s);this.state.roster[t]&&(this.state.roster[t]="done"),this.state.roster[s]="active",this.state.activeAgent=s,this.state.activeAgentTitle=Ca(s),this.state.currentPhase=`Task Handoff to @${s}`,this.state.currentActivity=`Transitioning task context from @${t} to @${s}`,this.print(` ${r(dr(t))} ${r(t)} ${u.muted("\u2501\u2501\u25B6")} ${i(dr(s))} ${i(s)}`),this.lastThinking=null}renderThinking(e){if(this.opts.hideThinking||this.lastThinking===e.agent)return;this.lastThinking=e.agent;let t=nt(e.agent);this.state.activeAgent=e.agent,this.state.activeAgentTitle=Ca(e.agent),this.state.roster[e.agent]="active",this.state.currentActivity="Analyzing workspace & formulating reasoning steps",this.print(` ${t("\u25C9")} [Active Agent: ${e.agent}] is thinking & formulating response\u2026`)}renderSpeak(e){let t=Yn(e.content||"",this.opts.maxChars);if(!t)return;let s=nt(e.agent),r=e.to?` ${u.muted("\u2192")} ${nt(e.to)("@"+e.to)}`:"",i=`speak:${e.agent}:${e.to||""}:${t}`;i!==this.lastLine&&(this.lastLine=i,this.print(` ${s(dr(e.agent))} ${s(e.agent)}${r}${u.muted(":")} ${u.secondary(t)}`),this.lastThinking=null)}renderAct(e){if(this.opts.hideActs)return;let t=nt(e.agent),s=e.toolName||"tool",r=e.toolArgs||{},i="";typeof r.path=="string"?i=` ${u.primary(r.path)}`:typeof r.command=="string"?i=` ${u.primary(r.command)}`:typeof r.query=="string"&&(i=` "${u.primary(r.query)}"`);let o=s==="write_file"||s==="edit_file"||s==="patch_file"?"\u270E":s==="run_command"?"\u2318":s==="read_file"?"\u{1F4D6}":s==="search_codebase"?"\u{1F50E}":"\u{1F527}";this.state.activeAgent=e.agent,this.state.activeAgentTitle=Ca(e.agent),this.state.roster[e.agent]="active",this.state.currentActivity=`Executing ${s}${i}`,this.print(` ${t(o)} [Running Tool]: ${t(e.agent)} is executing ${u.strong(s)}${i}...`),this.lastThinking=null}renderObserve(e){if(this.opts.hideActs)return;let t=e.success!==!1,s=t?u.success("\u2713 COMPLETED"):u.error("\u2717 FAILED"),r=Yn(e.content||(t?"Execution succeeded":"Execution failed"),this.opts.maxChars);this.print(` ${u.muted("\u21B3")} ${s}: ${u.muted(r)}`)}renderReview(e){let t=e.agent,s=e.to||"",r=Yn(e.content||"",this.opts.maxChars);if(!r)return;let i=nt(t),o=nt(s);this.print(`
|
|
913
|
+
${i("\u270E")} ${u.strong("@"+t)} ${u.muted("reviewing")} ${o("@"+s)}${u.muted(":")} ${u.secondary(r)}`),this.lastThinking=null}renderSummary(e){let t=nt(e.agent),s=e.durationMs?` ${u.muted(`(${(e.durationMs/1e3).toFixed(1)}s)`)}`:"";this.print(` ${t(dr(e.agent))} ${t(e.agent)} ${u.muted("\u2500\u2500\u25BA")} ${u.leader("\u2605 Hablas")} ${u.muted("\xB7 report submitted")}${s}`),this.lastThinking=null}renderDecision(e){let t=Yn(e.content||"",this.opts.maxChars);if(!t)return;let s=nt(e.agent);this.print(` ${s("\u25C6")} ${s(e.agent)} ${u.muted("decision:")} ${u.secondary(t)}`)}renderDone(e){this.print(`
|
|
914
|
+
${u.chrome("\u2500".repeat(56))}`),this.lastThinking=null}renderError(e){let t=nt(e.agent),s=Yn(e.content||"unknown error",this.opts.maxChars);this.print(` ${t("\u25C6")} ${t(e.agent)} ${u.error("\u2717")} ${u.error(s)}`),this.lastThinking=null}print(e){console.log(e)}}});var pr,Xp=N(()=>{"use strict";pr=class{plans=new Map;activePlanId=null;nextPlanNum=1;createPlan(e,t,s){let r=`plan_${this.nextPlanNum++}`,i={hablas:"Hablas",bob:"Bob",alex:"Alex",david:"David"},o={id:r,title:e,strategy:t,tasks:s.map((a,l)=>({task_id:`${r}_t${l+1}`,dependent_task_ids:a.dependent_task_ids||[],description:a.description,assignee:a.assignee,assigneeName:a.assigneeName||i[a.assignee]||a.assignee,status:"pending",createdAt:Date.now()})),createdAt:Date.now(),updatedAt:Date.now()};return this.plans.set(r,o),this.activePlanId=r,o}getActivePlan(){return this.activePlanId&&this.plans.get(this.activePlanId)||null}getTask(e){let t=this.getActivePlan();return t&&t.tasks.find(s=>s.task_id===e)||null}startTask(e){let t=this.getTask(e);return!t||!this.areDependenciesMet(e)?!1:(t.status="running",t.startedAt=Date.now(),this.touch(),!0)}finishTask(e,t){let s=this.getTask(e);return s?(s.status="done",s.result=t,s.completedAt=Date.now(),this.touch(),!0):!1}failTask(e,t){let s=this.getTask(e);return s?(s.status="failed",s.error=t,s.completedAt=Date.now(),this.touch(),!0):!1}skipTask(e){let t=this.getTask(e);return t?(t.status="skipped",t.completedAt=Date.now(),this.touch(),!0):!1}resetTask(e){let t=this.getTask(e);return t?(t.status="pending",t.result=void 0,t.error=void 0,t.startedAt=void 0,t.completedAt=void 0,this.touch(),!0):!1}replaceTask(e,t,s){let r=this.getTask(e);return r?(r.description=t,s&&(r.assignee=s),r.status="pending",r.result=void 0,r.error=void 0,this.touch(),!0):!1}areDependenciesMet(e){let t=this.getTask(e);if(!t)return!1;if(t.dependent_task_ids.length===0)return!0;let s=this.getActivePlan();return s?t.dependent_task_ids.every(r=>{let i=s.tasks.find(o=>o.task_id===r);return i&&(i.status==="done"||i.status==="skipped")}):!1}getNextTask(){let e=this.getActivePlan();if(!e)return null;for(let t of e.tasks)if(t.status==="pending"&&this.areDependenciesMet(t.task_id))return t;return null}getDependencyOrder(){let e=this.getActivePlan();if(!e)return[];let t=new Set,s=[],r=new Map(e.tasks.map(o=>[o.task_id,o])),i=o=>{if(t.has(o))return;t.add(o);let a=r.get(o);if(a){for(let l of a.dependent_task_ids)i(l);s.push(a)}};for(let o of e.tasks)i(o.task_id);return s}getProgress(){let e=this.getActivePlan();if(!e)return{total:0,done:0,failed:0,pending:0,running:0,skipped:0,percentage:0};let t=e.tasks.length,s=e.tasks.filter(c=>c.status==="done").length,r=e.tasks.filter(c=>c.status==="failed").length,i=e.tasks.filter(c=>c.status==="pending").length,o=e.tasks.filter(c=>c.status==="running").length,a=e.tasks.filter(c=>c.status==="skipped").length,l=t>0?Math.round((s+a)/t*100):0;return{total:t,done:s,failed:r,pending:i,running:o,skipped:a,percentage:l}}isComplete(){let e=this.getActivePlan();return e?e.tasks.every(t=>t.status==="done"||t.status==="failed"||t.status==="skipped"):!0}serialize(){let e=this.getActivePlan();return e?JSON.stringify(e,null,2):"{}"}deserialize(e){try{let t=JSON.parse(e);return t.id&&t.tasks?(this.plans.set(t.id,t),this.activePlanId=t.id,t):null}catch{return null}}reset(){this.plans.clear(),this.activePlanId=null,this.nextPlanNum=1}clear(){this.plans.clear(),this.activePlanId=null}touch(){let e=this.getActivePlan();e&&(e.updatedAt=Date.now())}}});function Zp(n){let t=n.trim().toLowerCase(),s=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/gi,r=t.match(s)||[];return E_.test(t)?"ECOSYSTEM":C_.test(t)?"APPLICATION":T_.test(t)||r.length>=3?"SERVICE":R_.test(t)||r.length===2?"COMPONENT":"FILE"}var E_,C_,T_,R_,eh=N(()=>{"use strict";E_=/\b(deploy|ci|cd|docker|docker-compose|gvisor|kubernetes|aws|gcp|vercel|heroku|server|cloud)\b/i,C_=/\b(full\s+system|complete\s+project|from\s+scratch|entire\s+application|prd|end-to-end|database.*api.*frontend)\b/i,T_=/\b(service|module|auth|login|session|api|controller|middleware|backend|database|schema)\b/i,R_=/\b(component|widget|screen|page|interface|view|button|sidebar|header|footer|form|ui)\b/i});function th(n){let e=n.toLowerCase();return/\b(how|why|what|tell\s+me|explain)\b/i.test(e)&&!/\b(build|fix|add)\b/i.test(e)?"QUESTION":/\b(research|find|search|docs|compare|analyze)\b/i.test(e)?"RESEARCH":/\b(fix|bug|issue|error|solve|debug)\b/i.test(e)?"DEBUGGING":/\b(refactor|cleanup|restructure|rewrite)\b/i.test(e)?"REFACTORING":/\b(design|architect|schema|blueprint|structure)\b/i.test(e)?"ARCHITECTURE":/\b(review|check|audit|verify)\b/i.test(e)?"REVIEW":"IMPLEMENTATION"}function nh(n){let e=n.trim(),t=e.toLowerCase();if(!e)return 0;let r=/[\w-]+\.(ts|js|tsx|jsx|py|json|yaml|yml|md|css|html|env|vue|svelte|go|rs|sh|toml)/i.test(e)?1:0,o=/\b(read_file|write_file|run_command|edit_file|search_codebase|list_dir|create_dir|delete_file|patch_file|search_and_replace)\b/i.test(e)?1:0,a=e.startsWith("/")?1:0,c=/\b(something|fix\s+it|make\s+better|do\s+stuff|change\s+things|some\s+file|مشكلة|شيء)\b/i.test(t)?1:0,d=.4*r+.3*o+.3*a-.5*c;return Math.max(0,Math.min(1,d))}var sh=N(()=>{"use strict"});var hr,ut,gr,mr,rh=N(()=>{"use strict";hr=O(require("fs")),ut=O(require("fs/promises")),gr=O(require("path")),mr=class{stack=[];workingDir;maxEntries;nextGroupId=1;constructor(e,t=200){this.workingDir=e,this.maxEntries=t}async record(e,t,s,r="hablas",i){let o=gr.resolve(this.workingDir,e),a=null;try{hr.existsSync(o)&&(a=await ut.readFile(o,"utf-8"))}catch{}let l={id:`undo_${Date.now()}_${this.stack.length}`,filePath:e,absolutePath:o,originalContent:a,newContent:t,toolName:s,agent:r,timestamp:Date.now(),undone:!1,groupId:i};return this.stack.push(l),this.stack.length>this.maxEntries&&(this.stack=this.stack.slice(-this.maxEntries)),l.id}beginGroup(){return`group_${this.nextGroupId++}`}async undo(e=1){let t=[],r=this.stack.filter(i=>!i.undone).reverse().slice(0,e);for(let i of r)try{i.originalContent===null?(hr.existsSync(i.absolutePath)&&await ut.unlink(i.absolutePath),t.push({file:i.filePath,success:!0})):(await ut.mkdir(gr.dirname(i.absolutePath),{recursive:!0}),await ut.writeFile(i.absolutePath,i.originalContent,"utf-8"),t.push({file:i.filePath,success:!0})),i.undone=!0}catch(o){t.push({file:i.filePath,success:!1,error:o.message})}return t}async undoGroup(e){let t=this.stack.filter(r=>r.groupId===e&&!r.undone).reverse(),s=[];for(let r of t)try{r.originalContent===null?hr.existsSync(r.absolutePath)&&await ut.unlink(r.absolutePath):await ut.writeFile(r.absolutePath,r.originalContent,"utf-8"),r.undone=!0,s.push({file:r.filePath,success:!0})}catch(i){s.push({file:r.filePath,success:!1,error:i.message})}return s}async undoAll(){return this.undo(this.getUndoableCount())}getUndoableCount(){return this.stack.filter(e=>!e.undone).length}getRecent(e=15){return this.stack.filter(t=>!t.undone).slice(-e).reverse()}getModifiedFiles(){let e=new Set;for(let t of this.stack.filter(s=>!s.undone))e.add(t.filePath);return Array.from(e)}formatList(e=15){let t=this.getRecent(e);if(t.length===0)return" No changes to undo";let s=[];for(let i=0;i<t.length;i++){let o=t[i],a=this.formatAge(o.timestamp),l=o.originalContent===null?"created":"modified",c=o.agent!=="hablas"?` [@${o.agent}]`:"";s.push(` ${i+1}. ${o.filePath} \u2014 ${l} by ${o.toolName}${c} (${a})`)}let r=this.getUndoableCount();return r>e&&s.push(` ... and ${r-e} more`),s.join(`
|
|
915
|
+
`)}formatAge(e){let t=Date.now()-e,s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;let r=Math.floor(s/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}size(){return this.stack.length}clear(){this.stack=[]}}});var Tt={};Pe(Tt,{activeCollabManager:()=>O_,runSingleCommand:()=>L_,startRepl:()=>Ta});async function M_(n,e=10){let t=n.split(/(\s+)/);for(let s of t)process.stdout.write(s),await new Promise(r=>setTimeout(r,e))}async function ah(n,e,t,s,r){let{interactive:i,autoMode:o,input:a,logger:l,abortSignal:c,onToolCall:d,skipTools:f}=r,h=r.reactEngine??Gn(),m=r.errorRecovery??Vn(),p=new Je("Hablas is thinking");p.start();let g=S=>{p&&(p.stop(S),p=null)},_=Hp({autoMode:o,interactive:i,confirm:a?S=>a.confirm(S):void 0,confirmDangerous:a?S=>a.confirmDangerous(S):void 0});await ir({identity:{name:"Hablas",title:"Team Leader",role:"hablas"},client:e,registry:t,session:n,contextManager:s,reactEngine:h,errorRecovery:m,logger:l,io:{onAssistantText:async S=>{g(),console.log(Pn("Hablas","Team Leader")),await M_(In(S))},onToolStart:(S,k)=>{g(),console.log(zc(S,k)),p=new Je("Continuing"),p.start()},onToolEnd:(S,k,y,v)=>{g(),console.log(Yc(k,y,v))},onNotice:(S,k)=>{g(),console.log(k==="retry"?u.muted(` \u21BB ${S}`):B(S))},onError:S=>{g(),console.log(sn(S,"Check your connection or model settings."))},onToolCall:()=>{d&&d()}},safetyPolicy:_,abortSignal:c,skipTools:f,maxIterations:I_}),g()}async function Ta(n,e){bd();let t=n.workingDirectory==="."?process.cwd():n.workingDirectory,s=He(n),r=new Nn(t,n),i=new Bt(n),o=new Ms(t),a=Ds(),l=new Bn(t),c=new yn(t),d=new pr,f=new or(n);f.setToolRegistry(r);let h=new mr(t),m=new ar,p=new fr(m).attach(),g=new cr(n,{tokenBudget:500,maxChars:140});f.setChannel(m);let _=await on(t,n),A=a.getActive(),S=A?A.systemPrompt:Ln,k=an(S,_,l,c),y=new Ut(k,n.historySize),v=Gn(),b=Vn(3),w=Tn(),x=0,T=0,L=Date.now(),$=n.autoMode||!1,F=0,j=new AbortController;process.on("SIGINT",()=>{let C=Date.now();C-F<P_&&process.exit(0),F=C,j.abort(),j=new AbortController,console.log(B("Operation cancelled"))}),console.log(Kc(n.model,t)),console.log(qc()),console.log();let z=!0;for(;z;)try{let C=await o.prompt(` ${u.primary("\u203A")} `);if(!C.trim())continue;if(C.startsWith("/")){if(await xu(C,n,s,r,i,y,t,o,x,a,void 0,l,pe=>{s=pe},c,d,h,f)==="quit")break;continue}let E=dc(C),K=lh(E,t);x++,console.log(Jc(x));let D=th(K),Q=nh(K),me=gi(K),ve="SOLO";if(!me&&D!=="QUESTION"&&Q<.8){let _e=Zp(K);_e!=="FILE"&&_e!=="COMPONENT"&&(ve="TEAM")}if(ve==="TEAM"){let _e=wc(K),pe=xc(K,_e),Oe={taskTitle:K.length>40?K.slice(0,37)+"...":K,currentPhase:"Strategic Execution",activeAgent:"Hablas",activeAgentTitle:"Team Leader",currentActivity:"Coordinating team",roster:{Hablas:"active",Emma:_e.includes("emma")?"pending":"done",Bob:_e.includes("bob")?"pending":"done",Alex:_e.includes("alex")?"pending":"done",David:_e.includes("david")?"pending":"done"}};console.log(`
|
|
916
|
+
`+eu(Oe));let ue=r.getOllamaTools(),q=new ur(m,f,g,n),{finalSynthesis:we}=await q.run(K,pe,ue,{abortSignal:j?.signal});console.log(Pn("Hablas","Team Leader")),console.log(In(we)),y.addAssistantMessage(we);continue}y.addUserMessage(K),j=new AbortController,v.startTurn(),b.resetTurn(),await ah(y,s,r,i,{interactive:!0,autoMode:$,input:o,logger:e,config:n,abortSignal:j.signal,reactEngine:v,errorRecovery:b,onToolCall:()=>{T++,w=Ai(w,"tool_call"),_i(w)}})}catch(C){console.log($e(C.message))}}async function L_(n,e,t){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,r=He(e),i=new Nn(s,e),o=new Bt(e),a=new Bn(s),l=await on(s,e),c=an(Ln,l,a),d=new Ut(c,e.historySize);d.addUserMessage(lh(n,s)),await ah(d,r,i,o,{interactive:!1,autoMode:e.autoMode||!1,logger:t,config:e})}function lh(n,e){let t=/#([\w./-]+)/g,s=n,r;for(;(r=t.exec(n))!==null;){let i=r[1],o=oh.resolve(e,i);ih.existsSync(o)&&(s=s.replace(`#${i}`,i))}return s}var ih,oh,O_,P_,I_,wt=N(()=>{"use strict";Su();ih=O(require("fs")),oh=O(require("path"));$n();fd();Xi();Zi();gd();Ls();So();xd();ii();En();Kp();Wp();Gp();Jp();Qp();Rn();$a();Xp();eh();sh();rn();rh();ba();wa();ka();O_=null,P_=1500,I_=150});function At(n){let e=Oa.join(ch.homedir(),".hablas","logs");yr.existsSync(e)||yr.mkdirSync(e,{recursive:!0});let t=Oa.join(e,`session-${Date.now()}.log`);return(0,Ra.default)({level:"info"},Ra.default.destination({dest:t,sync:!1}))}var Ra,Oa,ch,yr,Pa=N(()=>{"use strict";Ra=O(ga()),Oa=O(require("path")),ch=O(require("os")),yr=O(require("fs"))});var Jn=H((jR,hh)=>{"use strict";var D_=require("path"),dt="\\\\/",uh=`[^${dt}]`,N_=0,kt="\\.",F_="\\+",H_="\\?",br="\\/",j_="(?=.)",dh="[^/]",Ia=`(?:${br}|$)`,fh=`(?:^|${br})`,Ma=`${kt}{1,2}${Ia}`,B_=`(?!${kt})`,U_=`(?!${fh}${Ma})`,K_=`(?!${kt}{0,1}${Ia})`,q_=`(?!${Ma})`,W_=`[^.${br}]`,G_=`${dh}*?`,ph={DOT_LITERAL:kt,PLUS_LITERAL:F_,QMARK_LITERAL:H_,SLASH_LITERAL:br,ONE_CHAR:j_,QMARK:dh,END_ANCHOR:Ia,DOTS_SLASH:Ma,NO_DOT:B_,NO_DOTS:U_,NO_DOT_SLASH:K_,NO_DOTS_SLASH:q_,QMARK_NO_DOT:W_,STAR:G_,START_ANCHOR:fh},V_={...ph,SLASH_LITERAL:`[${dt}]`,QMARK:uh,STAR:`${uh}*?`,DOTS_SLASH:`${kt}{1,2}(?:[${dt}]|$)`,NO_DOT:`(?!${kt})`,NO_DOTS:`(?!(?:^|[${dt}])${kt}{1,2}(?:[${dt}]|$))`,NO_DOT_SLASH:`(?!${kt}{0,1}(?:[${dt}]|$))`,NO_DOTS_SLASH:`(?!${kt}{1,2}(?:[${dt}]|$))`,QMARK_NO_DOT:`[^.${dt}]`,START_ANCHOR:`(?:^|[${dt}])`,END_ANCHOR:`(?:[${dt}]|$)`},z_={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};hh.exports={DEFAULT_MAX_EXTGLOB_RECURSION:N_,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:z_,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:D_.sep,extglobChars(n){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${n.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(n){return n===!0?V_:ph}}});var vr=H(Re=>{"use strict";var Y_=require("path"),J_=process.platform==="win32",{REGEX_BACKSLASH:Q_,REGEX_REMOVE_BACKSLASH:X_,REGEX_SPECIAL_CHARS:Z_,REGEX_SPECIAL_CHARS_GLOBAL:eA}=Jn();Re.isObject=n=>n!==null&&typeof n=="object"&&!Array.isArray(n);Re.hasRegexChars=n=>Z_.test(n);Re.isRegexChar=n=>n.length===1&&Re.hasRegexChars(n);Re.escapeRegex=n=>n.replace(eA,"\\$1");Re.toPosixSlashes=n=>n.replace(Q_,"/");Re.removeBackslashes=n=>n.replace(X_,e=>e==="\\"?"":e);Re.supportsLookbehinds=()=>{let n=process.version.slice(1).split(".").map(Number);return n.length===3&&n[0]>=9||n[0]===8&&n[1]>=10};Re.isWindows=n=>n&&typeof n.windows=="boolean"?n.windows:J_===!0||Y_.sep==="\\";Re.escapeLast=(n,e,t)=>{let s=n.lastIndexOf(e,t);return s===-1?n:n[s-1]==="\\"?Re.escapeLast(n,e,s-1):`${n.slice(0,s)}\\${n.slice(s)}`};Re.removePrefix=(n,e={})=>{let t=n;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Re.wrapOutput=(n,e={},t={})=>{let s=t.contains?"":"^",r=t.contains?"":"$",i=`${s}(?:${n})${r}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Sh=H((UR,xh)=>{"use strict";var mh=vr(),{CHAR_ASTERISK:La,CHAR_AT:tA,CHAR_BACKWARD_SLASH:Qn,CHAR_COMMA:nA,CHAR_DOT:Da,CHAR_EXCLAMATION_MARK:Na,CHAR_FORWARD_SLASH:wh,CHAR_LEFT_CURLY_BRACE:Fa,CHAR_LEFT_PARENTHESES:Ha,CHAR_LEFT_SQUARE_BRACKET:sA,CHAR_PLUS:rA,CHAR_QUESTION_MARK:gh,CHAR_RIGHT_CURLY_BRACE:iA,CHAR_RIGHT_PARENTHESES:yh,CHAR_RIGHT_SQUARE_BRACKET:oA}=Jn(),bh=n=>n===wh||n===Qn,vh=n=>{n.isPrefix!==!0&&(n.depth=n.isGlobstar?1/0:1)},aA=(n,e)=>{let t=e||{},s=n.length-1,r=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],l=n,c=-1,d=0,f=0,h=!1,m=!1,p=!1,g=!1,_=!1,A=!1,S=!1,k=!1,y=!1,v=!1,b=0,w,x,T={value:"",depth:0,isGlob:!1},L=()=>c>=s,$=()=>l.charCodeAt(c+1),F=()=>(w=x,l.charCodeAt(++c));for(;c<s;){x=F();let K;if(x===Qn){S=T.backslashes=!0,x=F(),x===Fa&&(A=!0);continue}if(A===!0||x===Fa){for(b++;L()!==!0&&(x=F());){if(x===Qn){S=T.backslashes=!0,F();continue}if(x===Fa){b++;continue}if(A!==!0&&x===Da&&(x=F())===Da){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(A!==!0&&x===nA){if(h=T.isBrace=!0,p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===iA&&(b--,b===0)){A=!1,h=T.isBrace=!0,v=!0;break}}if(r===!0)continue;break}if(x===wh){if(i.push(c),o.push(T),T={value:"",depth:0,isGlob:!1},v===!0)continue;if(w===Da&&c===d+1){d+=2;continue}f=c+1;continue}if(t.noext!==!0&&(x===rA||x===tA||x===La||x===gh||x===Na)===!0&&$()===Ha){if(p=T.isGlob=!0,g=T.isExtglob=!0,v=!0,x===Na&&c===d&&(y=!0),r===!0){for(;L()!==!0&&(x=F());){if(x===Qn){S=T.backslashes=!0,x=F();continue}if(x===yh){p=T.isGlob=!0,v=!0;break}}continue}break}if(x===La){if(w===La&&(_=T.isGlobstar=!0),p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===gh){if(p=T.isGlob=!0,v=!0,r===!0)continue;break}if(x===sA){for(;L()!==!0&&(K=F());){if(K===Qn){S=T.backslashes=!0,F();continue}if(K===oA){m=T.isBracket=!0,p=T.isGlob=!0,v=!0;break}}if(r===!0)continue;break}if(t.nonegate!==!0&&x===Na&&c===d){k=T.negated=!0,d++;continue}if(t.noparen!==!0&&x===Ha){if(p=T.isGlob=!0,r===!0){for(;L()!==!0&&(x=F());){if(x===Ha){S=T.backslashes=!0,x=F();continue}if(x===yh){v=!0;break}}continue}break}if(p===!0){if(v=!0,r===!0)continue;break}}t.noext===!0&&(g=!1,p=!1);let j=l,z="",C="";d>0&&(z=l.slice(0,d),l=l.slice(d),f-=d),j&&p===!0&&f>0?(j=l.slice(0,f),C=l.slice(f)):p===!0?(j="",C=l):j=l,j&&j!==""&&j!=="/"&&j!==l&&bh(j.charCodeAt(j.length-1))&&(j=j.slice(0,-1)),t.unescape===!0&&(C&&(C=mh.removeBackslashes(C)),j&&S===!0&&(j=mh.removeBackslashes(j)));let E={prefix:z,input:n,start:d,base:j,glob:C,isBrace:h,isBracket:m,isGlob:p,isExtglob:g,isGlobstar:_,negated:k,negatedExtglob:y};if(t.tokens===!0&&(E.maxDepth=0,bh(x)||o.push(T),E.tokens=o),t.parts===!0||t.tokens===!0){let K;for(let D=0;D<i.length;D++){let Q=K?K+1:d,me=i[D],ve=n.slice(Q,me);t.tokens&&(D===0&&d!==0?(o[D].isPrefix=!0,o[D].value=z):o[D].value=ve,vh(o[D]),E.maxDepth+=o[D].depth),(D!==0||ve!=="")&&a.push(ve),K=me}if(K&&K+1<n.length){let D=n.slice(K+1);a.push(D),t.tokens&&(o[o.length-1].value=D,vh(o[o.length-1]),E.maxDepth+=o[o.length-1].depth)}E.slashes=i,E.parts=a}return E};xh.exports=aA});var Eh=H((KR,$h)=>{"use strict";var Xn=Jn(),ke=vr(),{MAX_LENGTH:wr,POSIX_REGEX_SOURCE:lA,REGEX_NON_SPECIAL_CHARS:cA,REGEX_SPECIAL_CHARS_BACKREF:uA,REPLACEMENTS:_h}=Xn,dA=(n,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...n,e);n.sort();let t=`[${n.join("-")}]`;try{new RegExp(t)}catch{return n.map(r=>ke.escapeRegex(r)).join("..")}return t},bn=(n,e)=>`Missing ${n}: "${e}" - use "\\\\${e}" to match literal characters`,Ah=n=>{let e=[],t=0,s=0,r=0,i="",o=!1;for(let a of n){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){r=r===1?0:1,i+=a;continue}if(r===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")s++;else if(a===")"&&s>0)s--;else if(a==="|"&&s===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},fA=n=>{let e=!1;for(let t of n){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},kh=n=>{let e=n.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(fA(e))return e.replace(/\\(.)/g,"$1")},pA=n=>{let e=n.map(kh).filter(Boolean);for(let t=0;t<e.length;t++)for(let s=t+1;s<e.length;s++){let r=e[t],i=e[s],o=r[0];if(!(!o||r!==o.repeat(r.length)||i!==o.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},ja=(n,e=!0)=>{if(n[0]!=="+"&&n[0]!=="*"||n[1]!=="(")return;let t=0,s=0,r=0,i=!1;for(let o=1;o<n.length;o++){let a=n[o];if(i===!0){i=!1;continue}if(a==="\\"){i=!0;continue}if(a==='"'){r=r===1?0:1;continue}if(r!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){s++;continue}if(a===")"&&(s--,s===0))return e===!0&&o!==n.length-1?void 0:{type:n[0],body:n.slice(2,o),end:o}}}}},hA=n=>{let e=0,t=[];for(;e<n.length;){let r=ja(n.slice(e),!1);if(!r||r.type!=="*")return;let i=Ah(r.body).map(a=>a.trim());if(i.length!==1)return;let o=kh(i[0]);if(!o||o.length!==1)return;t.push(o),e+=r.end+1}return t.length<1?void 0:`${t.length===1?ke.escapeRegex(t[0]):`[${t.map(r=>ke.escapeRegex(r)).join("")}]`}*`},mA=n=>{let e=0,t=n.trim(),s=ja(t);for(;s;)e++,t=s.body.trim(),s=ja(t);return e},gA=(n,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Xn.DEFAULT_MAX_EXTGLOB_RECURSION,s=Ah(n).map(r=>r.trim());if(s.length>1&&(s.some(r=>r==="")||s.some(r=>/^[*?]+$/.test(r))||pA(s)))return{risky:!0};for(let r of s){let i=hA(r);if(i)return{risky:!0,safeOutput:i};if(mA(r)>t)return{risky:!0}}return{risky:!1}},Ba=(n,e)=>{if(typeof n!="string")throw new TypeError("Expected a string");n=_h[n]||n;let t={...e},s=typeof t.maxLength=="number"?Math.min(wr,t.maxLength):wr,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",l=ke.isWindows(e),c=Xn.globChars(l),d=Xn.extglobChars(c),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:m,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:_,NO_DOT_SLASH:A,NO_DOTS_SLASH:S,QMARK:k,QMARK_NO_DOT:y,STAR:v,START_ANCHOR:b}=c,w=M=>`(${a}(?:(?!${b}${M.dot?g:f}).)*?)`,x=t.dot?"":_,T=t.dot?k:y,L=t.bash===!0?w(t):v;t.capture&&(L=`(${L})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={input:n,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};n=ke.removePrefix(n,$),r=n.length;let F=[],j=[],z=[],C=i,E,K=()=>$.index===r-1,D=$.peek=(M=1)=>n[$.index+M],Q=$.advance=()=>n[++$.index]||"",me=()=>n.slice($.index+1),ve=(M="",ie=0)=>{$.consumed+=M,$.index+=ie},_e=M=>{$.output+=M.output!=null?M.output:M.value,ve(M.value)},pe=()=>{let M=1;for(;D()==="!"&&(D(2)!=="("||D(3)==="?");)Q(),$.start++,M++;return M%2===0?!1:($.negated=!0,$.start++,!0)},Oe=M=>{$[M]++,z.push(M)},ue=M=>{$[M]--,z.pop()},q=M=>{if(C.type==="globstar"){let ie=$.braces>0&&(M.type==="comma"||M.type==="brace"),I=M.extglob===!0||F.length&&(M.type==="pipe"||M.type==="paren");M.type!=="slash"&&M.type!=="paren"&&!ie&&!I&&($.output=$.output.slice(0,-C.output.length),C.type="star",C.value="*",C.output=L,$.output+=C.output)}if(F.length&&M.type!=="paren"&&(F[F.length-1].inner+=M.value),(M.value||M.output)&&_e(M),C&&C.type==="text"&&M.type==="text"){C.value+=M.value,C.output=(C.output||"")+M.value;return}M.prev=C,o.push(M),C=M},we=(M,ie)=>{let I={...d[ie],conditions:1,inner:""};I.prev=C,I.parens=$.parens,I.output=$.output,I.startIndex=$.index,I.tokensIndex=o.length;let Y=(t.capture?"(":"")+I.open;Oe("parens"),q({type:M,value:ie,output:$.output?"":p}),q({type:"paren",extglob:!0,value:Q(),output:Y}),F.push(I)},kg=M=>{let ie=n.slice(M.startIndex,$.index+1),I=n.slice(M.startIndex+2,$.index),Y=gA(I,t);if((M.type==="plus"||M.type==="star")&&Y.risky){let ee=Y.safeOutput?(M.output?"":p)+(t.capture?`(${Y.safeOutput})`:Y.safeOutput):void 0,rt=o[M.tokensIndex];rt.type="text",rt.value=ie,rt.output=ee||ke.escapeRegex(ie);for(let it=M.tokensIndex+1;it<o.length;it++)o[it].value="",o[it].output="",delete o[it].suffix;$.output=M.output+rt.output,$.backtrack=!0,q({type:"paren",extglob:!0,value:E,output:""}),ue("parens");return}let ne=M.close+(t.capture?")":""),he;if(M.type==="negate"){let ee=L;if(M.inner&&M.inner.length>1&&M.inner.includes("/")&&(ee=w(t)),(ee!==L||K()||/^\)+$/.test(me()))&&(ne=M.close=`)$))${ee}`),M.inner.includes("*")&&(he=me())&&/^\.[^\\/.]+$/.test(he)){let rt=Ba(he,{...e,fastpaths:!1}).output;ne=M.close=`)${rt})${ee})`}M.prev.type==="bos"&&($.negatedExtglob=!0)}q({type:"paren",extglob:!0,value:E,output:ne}),ue("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(n)){let M=!1,ie=n.replace(uA,(I,Y,ne,he,ee,rt)=>he==="\\"?(M=!0,I):he==="?"?Y?Y+he+(ee?k.repeat(ee.length):""):rt===0?T+(ee?k.repeat(ee.length):""):k.repeat(ne.length):he==="."?f.repeat(ne.length):he==="*"?Y?Y+he+(ee?L:""):L:Y?I:`\\${I}`);return M===!0&&(t.unescape===!0?ie=ie.replace(/\\/g,""):ie=ie.replace(/\\+/g,I=>I.length%2===0?"\\\\":I?"\\":"")),ie===n&&t.contains===!0?($.output=n,$):($.output=ke.wrapOutput(ie,$,e),$)}for(;!K();){if(E=Q(),E==="\0")continue;if(E==="\\"){let I=D();if(I==="/"&&t.bash!==!0||I==="."||I===";")continue;if(!I){E+="\\",q({type:"text",value:E});continue}let Y=/^\\+/.exec(me()),ne=0;if(Y&&Y[0].length>2&&(ne=Y[0].length,$.index+=ne,ne%2!==0&&(E+="\\")),t.unescape===!0?E=Q():E+=Q(),$.brackets===0){q({type:"text",value:E});continue}}if($.brackets>0&&(E!=="]"||C.value==="["||C.value==="[^")){if(t.posix!==!1&&E===":"){let I=C.value.slice(1);if(I.includes("[")&&(C.posix=!0,I.includes(":"))){let Y=C.value.lastIndexOf("["),ne=C.value.slice(0,Y),he=C.value.slice(Y+2),ee=lA[he];if(ee){C.value=ne+ee,$.backtrack=!0,Q(),!i.output&&o.indexOf(C)===1&&(i.output=p);continue}}}(E==="["&&D()!==":"||E==="-"&&D()==="]")&&(E=`\\${E}`),E==="]"&&(C.value==="["||C.value==="[^")&&(E=`\\${E}`),t.posix===!0&&E==="!"&&C.value==="["&&(E="^"),C.value+=E,_e({value:E});continue}if($.quotes===1&&E!=='"'){E=ke.escapeRegex(E),C.value+=E,_e({value:E});continue}if(E==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&q({type:"text",value:E});continue}if(E==="("){Oe("parens"),q({type:"paren",value:E});continue}if(E===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(bn("opening","("));let I=F[F.length-1];if(I&&$.parens===I.parens+1){kg(F.pop());continue}q({type:"paren",value:E,output:$.parens?")":"\\)"}),ue("parens");continue}if(E==="["){if(t.nobracket===!0||!me().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(bn("closing","]"));E=`\\${E}`}else Oe("brackets");q({type:"bracket",value:E});continue}if(E==="]"){if(t.nobracket===!0||C&&C.type==="bracket"&&C.value.length===1){q({type:"text",value:E,output:`\\${E}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(bn("opening","["));q({type:"text",value:E,output:`\\${E}`});continue}ue("brackets");let I=C.value.slice(1);if(C.posix!==!0&&I[0]==="^"&&!I.includes("/")&&(E=`/${E}`),C.value+=E,_e({value:E}),t.literalBrackets===!1||ke.hasRegexChars(I))continue;let Y=ke.escapeRegex(C.value);if($.output=$.output.slice(0,-C.value.length),t.literalBrackets===!0){$.output+=Y,C.value=Y;continue}C.value=`(${a}${Y}|${C.value})`,$.output+=C.value;continue}if(E==="{"&&t.nobrace!==!0){Oe("braces");let I={type:"brace",value:E,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};j.push(I),q(I);continue}if(E==="}"){let I=j[j.length-1];if(t.nobrace===!0||!I){q({type:"text",value:E,output:E});continue}let Y=")";if(I.dots===!0){let ne=o.slice(),he=[];for(let ee=ne.length-1;ee>=0&&(o.pop(),ne[ee].type!=="brace");ee--)ne[ee].type!=="dots"&&he.unshift(ne[ee].value);Y=dA(he,t),$.backtrack=!0}if(I.comma!==!0&&I.dots!==!0){let ne=$.output.slice(0,I.outputIndex),he=$.tokens.slice(I.tokensIndex);I.value=I.output="\\{",E=Y="\\}",$.output=ne;for(let ee of he)$.output+=ee.output||ee.value}q({type:"brace",value:E,output:Y}),ue("braces"),j.pop();continue}if(E==="|"){F.length>0&&F[F.length-1].conditions++,q({type:"text",value:E});continue}if(E===","){let I=E,Y=j[j.length-1];Y&&z[z.length-1]==="braces"&&(Y.comma=!0,I="|"),q({type:"comma",value:E,output:I});continue}if(E==="/"){if(C.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),C=i;continue}q({type:"slash",value:E,output:m});continue}if(E==="."){if($.braces>0&&C.type==="dot"){C.value==="."&&(C.output=f);let I=j[j.length-1];C.type="dots",C.output+=E,C.value+=E,I.dots=!0;continue}if($.braces+$.parens===0&&C.type!=="bos"&&C.type!=="slash"){q({type:"text",value:E,output:f});continue}q({type:"dot",value:E,output:f});continue}if(E==="?"){if(!(C&&C.value==="(")&&t.noextglob!==!0&&D()==="("&&D(2)!=="?"){we("qmark",E);continue}if(C&&C.type==="paren"){let Y=D(),ne=E;if(Y==="<"&&!ke.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(C.value==="("&&!/[!=<:]/.test(Y)||Y==="<"&&!/<([!=]|\w+>)/.test(me()))&&(ne=`\\${E}`),q({type:"text",value:E,output:ne});continue}if(t.dot!==!0&&(C.type==="slash"||C.type==="bos")){q({type:"qmark",value:E,output:y});continue}q({type:"qmark",value:E,output:k});continue}if(E==="!"){if(t.noextglob!==!0&&D()==="("&&(D(2)!=="?"||!/[!=<:]/.test(D(3)))){we("negate",E);continue}if(t.nonegate!==!0&&$.index===0){pe();continue}}if(E==="+"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){we("plus",E);continue}if(C&&C.value==="("||t.regex===!1){q({type:"plus",value:E,output:h});continue}if(C&&(C.type==="bracket"||C.type==="paren"||C.type==="brace")||$.parens>0){q({type:"plus",value:E});continue}q({type:"plus",value:h});continue}if(E==="@"){if(t.noextglob!==!0&&D()==="("&&D(2)!=="?"){q({type:"at",extglob:!0,value:E,output:""});continue}q({type:"text",value:E});continue}if(E!=="*"){(E==="$"||E==="^")&&(E=`\\${E}`);let I=cA.exec(me());I&&(E+=I[0],$.index+=I[0].length),q({type:"text",value:E});continue}if(C&&(C.type==="globstar"||C.star===!0)){C.type="star",C.star=!0,C.value+=E,C.output=L,$.backtrack=!0,$.globstar=!0,ve(E);continue}let M=me();if(t.noextglob!==!0&&/^\([^?]/.test(M)){we("star",E);continue}if(C.type==="star"){if(t.noglobstar===!0){ve(E);continue}let I=C.prev,Y=I.prev,ne=I.type==="slash"||I.type==="bos",he=Y&&(Y.type==="star"||Y.type==="globstar");if(t.bash===!0&&(!ne||M[0]&&M[0]!=="/")){q({type:"star",value:E,output:""});continue}let ee=$.braces>0&&(I.type==="comma"||I.type==="brace"),rt=F.length&&(I.type==="pipe"||I.type==="paren");if(!ne&&I.type!=="paren"&&!ee&&!rt){q({type:"star",value:E,output:""});continue}for(;M.slice(0,3)==="/**";){let it=n[$.index+4];if(it&&it!=="/")break;M=M.slice(3),ve("/**",3)}if(I.type==="bos"&&K()){C.type="globstar",C.value+=E,C.output=w(t),$.output=C.output,$.globstar=!0,ve(E);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&!he&&K()){$.output=$.output.slice(0,-(I.output+C.output).length),I.output=`(?:${I.output}`,C.type="globstar",C.output=w(t)+(t.strictSlashes?")":"|$)"),C.value+=E,$.globstar=!0,$.output+=I.output+C.output,ve(E);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&M[0]==="/"){let it=M[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(I.output+C.output).length),I.output=`(?:${I.output}`,C.type="globstar",C.output=`${w(t)}${m}|${m}${it})`,C.value+=E,$.output+=I.output+C.output,$.globstar=!0,ve(E+Q()),q({type:"slash",value:"/",output:""});continue}if(I.type==="bos"&&M[0]==="/"){C.type="globstar",C.value+=E,C.output=`(?:^|${m}|${w(t)}${m})`,$.output=C.output,$.globstar=!0,ve(E+Q()),q({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-C.output.length),C.type="globstar",C.output=w(t),C.value+=E,$.output+=C.output,$.globstar=!0,ve(E);continue}let ie={type:"star",value:E,output:L};if(t.bash===!0){ie.output=".*?",(C.type==="bos"||C.type==="slash")&&(ie.output=x+ie.output),q(ie);continue}if(C&&(C.type==="bracket"||C.type==="paren")&&t.regex===!0){ie.output=E,q(ie);continue}($.index===$.start||C.type==="slash"||C.type==="dot")&&(C.type==="dot"?($.output+=A,C.output+=A):t.dot===!0?($.output+=S,C.output+=S):($.output+=x,C.output+=x),D()!=="*"&&($.output+=p,C.output+=p)),q(ie)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(bn("closing","]"));$.output=ke.escapeLast($.output,"["),ue("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(bn("closing",")"));$.output=ke.escapeLast($.output,"("),ue("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(bn("closing","}"));$.output=ke.escapeLast($.output,"{"),ue("braces")}if(t.strictSlashes!==!0&&(C.type==="star"||C.type==="bracket")&&q({type:"maybe_slash",value:"",output:`${m}?`}),$.backtrack===!0){$.output="";for(let M of $.tokens)$.output+=M.output!=null?M.output:M.value,M.suffix&&($.output+=M.suffix)}return $};Ba.fastpaths=(n,e)=>{let t={...e},s=typeof t.maxLength=="number"?Math.min(wr,t.maxLength):wr,r=n.length;if(r>s)throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${s}`);n=_h[n]||n;let i=ke.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:l,DOTS_SLASH:c,NO_DOT:d,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:m,START_ANCHOR:p}=Xn.globChars(i),g=t.dot?f:d,_=t.dot?h:d,A=t.capture?"":"?:",S={negated:!1,prefix:""},k=t.bash===!0?".*?":m;t.capture&&(k=`(${k})`);let y=x=>x.noglobstar===!0?k:`(${A}(?:(?!${p}${x.dot?c:o}).)*?)`,v=x=>{switch(x){case"*":return`${g}${l}${k}`;case".*":return`${o}${l}${k}`;case"*.*":return`${g}${k}${o}${l}${k}`;case"*/*":return`${g}${k}${a}${l}${_}${k}`;case"**":return g+y(t);case"**/*":return`(?:${g}${y(t)}${a})?${_}${l}${k}`;case"**/*.*":return`(?:${g}${y(t)}${a})?${_}${k}${o}${l}${k}`;case"**/.*":return`(?:${g}${y(t)}${a})?${o}${l}${k}`;default:{let T=/^(.*?)\.(\w+)$/.exec(x);if(!T)return;let L=v(T[1]);return L?L+o+T[2]:void 0}}},b=ke.removePrefix(n,S),w=v(b);return w&&t.strictSlashes!==!0&&(w+=`${a}?`),w};$h.exports=Ba});var Th=H((qR,Ch)=>{"use strict";var yA=require("path"),bA=Sh(),Ua=Eh(),Ka=vr(),vA=Jn(),wA=n=>n&&typeof n=="object"&&!Array.isArray(n),ce=(n,e,t=!1)=>{if(Array.isArray(n)){let d=n.map(h=>ce(h,e,t));return h=>{for(let m of d){let p=m(h);if(p)return p}return!1}}let s=wA(n)&&n.tokens&&n.input;if(n===""||typeof n!="string"&&!s)throw new TypeError("Expected pattern to be a non-empty string");let r=e||{},i=Ka.isWindows(e),o=s?ce.compileRe(n,e):ce.makeRe(n,e,!1,!0),a=o.state;delete o.state;let l=()=>!1;if(r.ignore){let d={...e,ignore:null,onMatch:null,onResult:null};l=ce(r.ignore,d,t)}let c=(d,f=!1)=>{let{isMatch:h,match:m,output:p}=ce.test(d,o,e,{glob:n,posix:i}),g={glob:n,state:a,regex:o,posix:i,input:d,output:p,match:m,isMatch:h};return typeof r.onResult=="function"&&r.onResult(g),h===!1?(g.isMatch=!1,f?g:!1):l(d)?(typeof r.onIgnore=="function"&&r.onIgnore(g),g.isMatch=!1,f?g:!1):(typeof r.onMatch=="function"&&r.onMatch(g),f?g:!0)};return t&&(c.state=a),c};ce.test=(n,e,t,{glob:s,posix:r}={})=>{if(typeof n!="string")throw new TypeError("Expected input to be a string");if(n==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(r?Ka.toPosixSlashes:null),a=n===s,l=a&&o?o(n):n;return a===!1&&(l=o?o(n):n,a=l===s),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=ce.matchBase(n,e,t,r):a=e.exec(l)),{isMatch:!!a,match:a,output:l}};ce.matchBase=(n,e,t,s=Ka.isWindows(t))=>(e instanceof RegExp?e:ce.makeRe(e,t)).test(yA.basename(n));ce.isMatch=(n,e,t)=>ce(e,t)(n);ce.parse=(n,e)=>Array.isArray(n)?n.map(t=>ce.parse(t,e)):Ua(n,{...e,fastpaths:!1});ce.scan=(n,e)=>bA(n,e);ce.compileRe=(n,e,t=!1,s=!1)=>{if(t===!0)return n.output;let r=e||{},i=r.contains?"":"^",o=r.contains?"":"$",a=`${i}(?:${n.output})${o}`;n&&n.negated===!0&&(a=`^(?!${a}).*$`);let l=ce.toRegex(a,e);return s===!0&&(l.state=n),l};ce.makeRe=(n,e={},t=!1,s=!1)=>{if(!n||typeof n!="string")throw new TypeError("Expected a non-empty string");let r={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(n[0]==="."||n[0]==="*")&&(r.output=Ua.fastpaths(n,e)),r.output||(r=Ua(n,e)),ce.compileRe(r,e,t,s)};ce.toRegex=(n,e)=>{try{let t=e||{};return new RegExp(n,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ce.constants=vA;Ch.exports=ce});var qa=H((WR,Rh)=>{"use strict";Rh.exports=Th()});var Fh=H((GR,Nh)=>{"use strict";var es=require("fs"),{Readable:xA}=require("stream"),Zn=require("path"),{promisify:Ar}=require("util"),Wa=qa(),SA=Ar(es.readdir),_A=Ar(es.stat),Oh=Ar(es.lstat),AA=Ar(es.realpath),kA="!",Lh="READDIRP_RECURSIVE_ERROR",$A=new Set(["ENOENT","EPERM","EACCES","ELOOP",Lh]),Ga="files",Dh="directories",Sr="files_directories",xr="all",Ph=[Ga,Dh,Sr,xr],EA=n=>$A.has(n.code),[Ih,CA]=process.versions.node.split(".").slice(0,2).map(n=>Number.parseInt(n,10)),TA=process.platform==="win32"&&(Ih>10||Ih===10&&CA>=5),Mh=n=>{if(n!==void 0){if(typeof n=="function")return n;if(typeof n=="string"){let e=Wa(n.trim());return t=>e(t.basename)}if(Array.isArray(n)){let e=[],t=[];for(let s of n){let r=s.trim();r.charAt(0)===kA?t.push(Wa(r.slice(1))):e.push(Wa(r))}return t.length>0?e.length>0?s=>e.some(r=>r(s.basename))&&!t.some(r=>r(s.basename)):s=>!t.some(r=>r(s.basename)):s=>e.some(r=>r(s.basename))}}},_r=class n extends xA{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Ga,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...n.defaultOptions,...e},{root:s,type:r}=t;this._fileFilter=Mh(t.fileFilter),this._directoryFilter=Mh(t.directoryFilter);let i=t.lstat?Oh:_A;TA?this._stat=o=>i(o,{bigint:!0}):this._stat=i,this._maxDepth=t.depth,this._wantsDir=[Dh,Sr,xr].includes(r),this._wantsFile=[Ga,Sr,xr].includes(r),this._wantsEverything=r===xr,this._root=Zn.resolve(s),this._isDirent="Dirent"in es&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(s,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:s,files:r=[]}=this.parent||{};if(r.length>0){let i=r.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(i)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(s<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,s+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let i=this.parents.pop();if(!i){this.push(null);break}if(this.parent=await i,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let s;try{s=await SA(e,this._rdOptions)}catch(r){this._onError(r)}return{files:s,depth:t,path:e}}async _formatEntry(e,t){let s;try{let r=this._isDirent?e.name:e,i=Zn.resolve(Zn.join(t,r));s={path:Zn.relative(this._root,i),fullPath:i,basename:r},s[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(r){this._onError(r)}return s}_onError(e){EA(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let s=e.fullPath;try{let r=await AA(s),i=await Oh(r);if(i.isFile())return"file";if(i.isDirectory()){let o=r.length;if(s.startsWith(r)&&s.substr(o,1)===Zn.sep){let a=new Error(`Circular symlink detected: "${s}" points to "${r}"`);return a.code=Lh,this._onError(a)}return"directory"}}catch(r){this._onError(r)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},vn=(n,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=Sr),t&&(e.type=t),n){if(typeof n!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!Ph.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Ph.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=n,new _r(e)},RA=(n,e={})=>new Promise((t,s)=>{let r=[];vn(n,e).on("data",i=>r.push(i)).on("end",()=>t(r)).on("error",i=>s(i))});vn.promise=RA;vn.ReaddirpStream=_r;vn.default=vn;Nh.exports=vn});var Va=H((VR,Hh)=>{Hh.exports=function(n,e){if(typeof n!="string")throw new TypeError("expected path to be a string");if(n==="\\"||n==="/")return"/";var t=n.length;if(t<=1)return n;var s="";if(t>4&&n[3]==="\\"){var r=n[2];(r==="?"||r===".")&&n.slice(0,2)==="\\\\"&&(n=n.slice(2),s="//")}var i=n.split(/[/\\]+/);return e!==!1&&i[i.length-1]===""&&i.pop(),s+i.join("/")}});var Wh=H((Kh,qh)=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Uh=qa(),OA=Va(),jh="!",PA={returnIndex:!1},IA=n=>Array.isArray(n)?n:[n],MA=(n,e)=>{if(typeof n=="function")return n;if(typeof n=="string"){let t=Uh(n,e);return s=>n===s||t(s)}return n instanceof RegExp?t=>n.test(t):t=>!1},Bh=(n,e,t,s)=>{let r=Array.isArray(t),i=r?t[0]:t;if(!r&&typeof i!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(i));let o=OA(i,!1);for(let l=0;l<e.length;l++){let c=e[l];if(c(o))return s?-1:!1}let a=r&&[o].concat(t.slice(1));for(let l=0;l<n.length;l++){let c=n[l];if(r?c(...a):c(o))return s?l:!0}return s?-1:!1},za=(n,e,t=PA)=>{if(n==null)throw new TypeError("anymatch: specify first argument");let s=typeof t=="boolean"?{returnIndex:t}:t,r=s.returnIndex||!1,i=IA(n),o=i.filter(l=>typeof l=="string"&&l.charAt(0)===jh).map(l=>l.slice(1)).map(l=>Uh(l,s)),a=i.filter(l=>typeof l!="string"||typeof l=="string"&&l.charAt(0)!==jh).map(l=>MA(l,s));return e==null?(l,c=!1)=>Bh(a,o,l,typeof c=="boolean"?c:!1):Bh(a,o,e,r)};za.default=za;qh.exports=za});var Vh=H((zR,Gh)=>{Gh.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var Ya=H((YR,Yh)=>{var LA=Vh(),zh={"{":"}","(":")","[":"]"},DA=function(n){if(n[0]==="!")return!0;for(var e=0,t=-2,s=-2,r=-2,i=-2,o=-2;e<n.length;){if(n[e]==="*"||n[e+1]==="?"&&/[\].+)]/.test(n[e])||s!==-1&&n[e]==="["&&n[e+1]!=="]"&&(s<e&&(s=n.indexOf("]",e)),s>e&&(o===-1||o>s||(o=n.indexOf("\\",e),o===-1||o>s)))||r!==-1&&n[e]==="{"&&n[e+1]!=="}"&&(r=n.indexOf("}",e),r>e&&(o=n.indexOf("\\",e),o===-1||o>r))||i!==-1&&n[e]==="("&&n[e+1]==="?"&&/[:!=]/.test(n[e+2])&&n[e+3]!==")"&&(i=n.indexOf(")",e),i>e&&(o=n.indexOf("\\",e),o===-1||o>i))||t!==-1&&n[e]==="("&&n[e+1]!=="|"&&(t<e&&(t=n.indexOf("|",e)),t!==-1&&n[t+1]!==")"&&(i=n.indexOf(")",t),i>t&&(o=n.indexOf("\\",t),o===-1||o>i))))return!0;if(n[e]==="\\"){var a=n[e+1];e+=2;var l=zh[a];if(l){var c=n.indexOf(l,e);c!==-1&&(e=c+1)}if(n[e]==="!")return!0}else e++}return!1},NA=function(n){if(n[0]==="!")return!0;for(var e=0;e<n.length;){if(/[*?{}()[\]]/.test(n[e]))return!0;if(n[e]==="\\"){var t=n[e+1];e+=2;var s=zh[t];if(s){var r=n.indexOf(s,e);r!==-1&&(e=r+1)}if(n[e]==="!")return!0}else e++}return!1};Yh.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(LA(e))return!0;var s=DA;return t&&t.strict===!1&&(s=NA),s(e)}});var Qh=H((JR,Jh)=>{"use strict";var FA=Ya(),HA=require("path").posix.dirname,jA=require("os").platform()==="win32",Ja="/",BA=/\\/g,UA=/[\{\[].*[\}\]]$/,KA=/(^|[^\\])([\{\[]|\([^\)]+$)/,qA=/\\([\!\*\?\|\[\]\(\)\{\}])/g;Jh.exports=function(e,t){var s=Object.assign({flipBackslashes:!0},t);s.flipBackslashes&&jA&&e.indexOf(Ja)<0&&(e=e.replace(BA,Ja)),UA.test(e)&&(e+=Ja),e+="a";do e=HA(e);while(FA(e)||KA.test(e));return e.replace(qA,"$1")}});var kr=H(Ge=>{"use strict";Ge.isInteger=n=>typeof n=="number"?Number.isInteger(n):typeof n=="string"&&n.trim()!==""?Number.isInteger(Number(n)):!1;Ge.find=(n,e)=>n.nodes.find(t=>t.type===e);Ge.exceedsLimit=(n,e,t=1,s)=>s===!1||!Ge.isInteger(n)||!Ge.isInteger(e)?!1:(Number(e)-Number(n))/Number(t)>=s;Ge.escapeNode=(n,e=0,t)=>{let s=n.nodes[e];s&&(t&&s.type===t||s.type==="open"||s.type==="close")&&s.escaped!==!0&&(s.value="\\"+s.value,s.escaped=!0)};Ge.encloseBrace=n=>n.type!=="brace"?!1:n.commas>>0+n.ranges>>0===0?(n.invalid=!0,!0):!1;Ge.isInvalidBrace=n=>n.type!=="brace"?!1:n.invalid===!0||n.dollar?!0:n.commas>>0+n.ranges>>0===0||n.open!==!0||n.close!==!0?(n.invalid=!0,!0):!1;Ge.isOpenOrClose=n=>n.type==="open"||n.type==="close"?!0:n.open===!0||n.close===!0;Ge.reduce=n=>n.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);Ge.flatten=(...n)=>{let e=[],t=s=>{for(let r=0;r<s.length;r++){let i=s[r];if(Array.isArray(i)){t(i);continue}i!==void 0&&e.push(i)}return e};return t(n),e}});var $r=H((XR,Zh)=>{"use strict";var Xh=kr();Zh.exports=(n,e={})=>{let t=(s,r={})=>{let i=e.escapeInvalid&&Xh.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a="";if(s.value)return(i||o)&&Xh.isOpenOrClose(s)?"\\"+s.value:s.value;if(s.value)return s.value;if(s.nodes)for(let l of s.nodes)a+=t(l);return a};return t(n)}});var tm=H((ZR,em)=>{"use strict";em.exports=function(n){return typeof n=="number"?n-n===0:typeof n=="string"&&n.trim()!==""?Number.isFinite?Number.isFinite(+n):isFinite(+n):!1}});var um=H((eO,cm)=>{"use strict";var nm=tm(),Yt=(n,e,t)=>{if(nm(n)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||n===e)return String(n);if(nm(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let s={relaxZeros:!0,...t};typeof s.strictZeros=="boolean"&&(s.relaxZeros=s.strictZeros===!1);let r=String(s.relaxZeros),i=String(s.shorthand),o=String(s.capture),a=String(s.wrap),l=n+":"+e+"="+r+i+o+a;if(Yt.cache.hasOwnProperty(l))return Yt.cache[l].result;let c=Math.min(n,e),d=Math.max(n,e);if(Math.abs(c-d)===1){let g=n+"|"+e;return s.capture?`(${g})`:s.wrap===!1?g:`(?:${g})`}let f=lm(n)||lm(e),h={min:n,max:e,a:c,b:d},m=[],p=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),c<0){let g=d<0?Math.abs(d):1;p=sm(g,Math.abs(c),h,s),c=h.a=0}return d>=0&&(m=sm(c,d,h,s)),h.negatives=p,h.positives=m,h.result=WA(p,m,s),s.capture===!0?h.result=`(${h.result})`:s.wrap!==!1&&m.length+p.length>1&&(h.result=`(?:${h.result})`),Yt.cache[l]=h,h.result};function WA(n,e,t){let s=Qa(n,e,"-",!1,t)||[],r=Qa(e,n,"",!1,t)||[],i=Qa(n,e,"-?",!0,t)||[];return s.concat(i).concat(r).join("|")}function GA(n,e){let t=1,s=1,r=im(n,t),i=new Set([e]);for(;n<=r&&r<=e;)i.add(r),t+=1,r=im(n,t);for(r=om(e+1,s)-1;n<r&&r<=e;)i.add(r),s+=1,r=om(e+1,s)-1;return i=[...i],i.sort(YA),i}function VA(n,e,t){if(n===e)return{pattern:n,count:[],digits:0};let s=zA(n,e),r=s.length,i="",o=0;for(let a=0;a<r;a++){let[l,c]=s[a];l===c?i+=l:l!=="0"||c!=="9"?i+=JA(l,c,t):o++}return o&&(i+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:i,count:[o],digits:r}}function sm(n,e,t,s){let r=GA(n,e),i=[],o=n,a;for(let l=0;l<r.length;l++){let c=r[l],d=VA(String(o),String(c),s),f="";if(!t.isPadded&&a&&a.pattern===d.pattern){a.count.length>1&&a.count.pop(),a.count.push(d.count[0]),a.string=a.pattern+am(a.count),o=c+1;continue}t.isPadded&&(f=QA(c,t,s)),d.string=f+d.pattern+am(d.count),i.push(d),o=c+1,a=d}return i}function Qa(n,e,t,s,r){let i=[];for(let o of n){let{string:a}=o;!s&&!rm(e,"string",a)&&i.push(t+a),s&&rm(e,"string",a)&&i.push(t+a)}return i}function zA(n,e){let t=[];for(let s=0;s<n.length;s++)t.push([n[s],e[s]]);return t}function YA(n,e){return n>e?1:e>n?-1:0}function rm(n,e,t){return n.some(s=>s[e]===t)}function im(n,e){return Number(String(n).slice(0,-e)+"9".repeat(e))}function om(n,e){return n-n%Math.pow(10,e)}function am(n){let[e=0,t=""]=n;return t||e>1?`{${e+(t?","+t:"")}}`:""}function JA(n,e,t){return`[${n}${e-n===1?"":"-"}${e}]`}function lm(n){return/^-?(0+)\d/.test(n)}function QA(n,e,t){if(!e.isPadded)return n;let s=Math.abs(e.maxLen-String(n).length),r=t.relaxZeros!==!1;switch(s){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:return r?`0{0,${s}}`:`0{${s}}`}}Yt.cache={};Yt.clearCache=()=>Yt.cache={};cm.exports=Yt});var el=H((tO,ym)=>{"use strict";var XA=require("util"),fm=um(),dm=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),ZA=n=>e=>n===!0?Number(e):String(e),Xa=n=>typeof n=="number"||typeof n=="string"&&n!=="",ts=n=>Number.isInteger(+n),Za=n=>{let e=`${n}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},ek=(n,e,t)=>typeof n=="string"||typeof e=="string"?!0:t.stringify===!0,tk=(n,e,t)=>{if(e>0){let s=n[0]==="-"?"-":"";s&&(n=n.slice(1)),n=s+n.padStart(s?e-1:e,"0")}return t===!1?String(n):n},Cr=(n,e)=>{let t=n[0]==="-"?"-":"";for(t&&(n=n.slice(1),e--);n.length<e;)n="0"+n;return t?"-"+n:n},nk=(n,e,t)=>{n.negatives.sort((a,l)=>a<l?-1:a>l?1:0),n.positives.sort((a,l)=>a<l?-1:a>l?1:0);let s=e.capture?"":"?:",r="",i="",o;return n.positives.length&&(r=n.positives.map(a=>Cr(String(a),t)).join("|")),n.negatives.length&&(i=`-(${s}${n.negatives.map(a=>Cr(String(a),t)).join("|")})`),r&&i?o=`${r}|${i}`:o=r||i,e.wrap?`(${s}${o})`:o},pm=(n,e,t,s)=>{if(t)return fm(n,e,{wrap:!1,...s});let r=String.fromCharCode(n);if(n===e)return r;let i=String.fromCharCode(e);return`[${r}-${i}]`},hm=(n,e,t)=>{if(Array.isArray(n)){let s=t.wrap===!0,r=t.capture?"":"?:";return s?`(${r}${n.join("|")})`:n.join("|")}return fm(n,e,t)},mm=(...n)=>new RangeError("Invalid range arguments: "+XA.inspect(...n)),gm=(n,e,t)=>{if(t.strictRanges===!0)throw mm([n,e]);return[]},sk=(n,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${n}" to be a number`);return[]},rk=(n,e,t=1,s={})=>{let r=Number(n),i=Number(e);if(!Number.isInteger(r)||!Number.isInteger(i)){if(s.strictRanges===!0)throw mm([n,e]);return[]}r===0&&(r=0),i===0&&(i=0);let o=r>i,a=String(n),l=String(e),c=String(t);t=Math.max(Math.abs(t),1);let d=Za(a)||Za(l)||Za(c),f=d?Math.max(a.length,l.length,c.length):0,h=d===!1&&ek(n,e,s)===!1,m=s.transform||ZA(h);if(s.toRegex&&t===1)return pm(Cr(n,f),Cr(e,f),!0,s);let p={negatives:[],positives:[]},g=S=>p[S<0?"negatives":"positives"].push(Math.abs(S)),_=[],A=0;for(;o?r>=i:r<=i;)s.toRegex===!0&&t>1?g(r):_.push(tk(m(r,A),f,h)),r=o?r-t:r+t,A++;return s.toRegex===!0?t>1?nk(p,s,f):hm(_,null,{wrap:!1,...s}):_},ik=(n,e,t=1,s={})=>{if(!ts(n)&&n.length>1||!ts(e)&&e.length>1)return gm(n,e,s);let r=s.transform||(h=>String.fromCharCode(h)),i=`${n}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=i>o,l=Math.min(i,o),c=Math.max(i,o);if(s.toRegex&&t===1)return pm(l,c,!1,s);let d=[],f=0;for(;a?i>=o:i<=o;)d.push(r(i,f)),i=a?i-t:i+t,f++;return s.toRegex===!0?hm(d,null,{wrap:!1,options:s}):d},Er=(n,e,t,s={})=>{if(e==null&&Xa(n))return[n];if(!Xa(n)||!Xa(e))return gm(n,e,s);if(typeof t=="function")return Er(n,e,1,{transform:t});if(dm(t))return Er(n,e,0,t);let r={...s};return r.capture===!0&&(r.wrap=!0),t=t||r.step||1,ts(t)?ts(n)&&ts(e)?rk(n,e,t,r):ik(n,e,Math.max(Math.abs(t),1),r):t!=null&&!dm(t)?sk(t,r):Er(n,e,1,t)};ym.exports=Er});var wm=H((nO,vm)=>{"use strict";var ok=el(),bm=kr(),ak=(n,e={})=>{let t=(s,r={})=>{let i=bm.isInvalidBrace(r),o=s.invalid===!0&&e.escapeInvalid===!0,a=i===!0||o===!0,l=e.escapeInvalid===!0?"\\":"",c="";if(s.isOpen===!0)return l+s.value;if(s.isClose===!0)return console.log("node.isClose",l,s.value),l+s.value;if(s.type==="open")return a?l+s.value:"(";if(s.type==="close")return a?l+s.value:")";if(s.type==="comma")return s.prev.type==="comma"?"":a?s.value:"|";if(s.value)return s.value;if(s.nodes&&s.ranges>0){let d=bm.reduce(s.nodes),f=ok(...d,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return d.length>1&&f.length>1?`(${f})`:f}if(s.nodes)for(let d of s.nodes)c+=t(d,s);return c};return t(n)};vm.exports=ak});var _m=H((sO,Sm)=>{"use strict";var lk=el(),xm=$r(),wn=kr(),Jt=(n="",e="",t=!1)=>{let s=[];if(n=[].concat(n),e=[].concat(e),!e.length)return n;if(!n.length)return t?wn.flatten(e).map(r=>`{${r}}`):e;for(let r of n)if(Array.isArray(r))for(let i of r)s.push(Jt(i,e,t));else for(let i of e)t===!0&&typeof i=="string"&&(i=`{${i}}`),s.push(Array.isArray(i)?Jt(r,i,t):r+i);return wn.flatten(s)},ck=(n,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,s=(r,i={})=>{r.queue=[];let o=i,a=i.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(r.invalid||r.dollar){a.push(Jt(a.pop(),xm(r,e)));return}if(r.type==="brace"&&r.invalid!==!0&&r.nodes.length===2){a.push(Jt(a.pop(),["{}"]));return}if(r.nodes&&r.ranges>0){let f=wn.reduce(r.nodes);if(wn.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=lk(...f,e);h.length===0&&(h=xm(r,e)),a.push(Jt(a.pop(),h)),r.nodes=[];return}let l=wn.encloseBrace(r),c=r.queue,d=r;for(;d.type!=="brace"&&d.type!=="root"&&d.parent;)d=d.parent,c=d.queue;for(let f=0;f<r.nodes.length;f++){let h=r.nodes[f];if(h.type==="comma"&&r.type==="brace"){f===1&&c.push(""),c.push("");continue}if(h.type==="close"){a.push(Jt(a.pop(),c,l));continue}if(h.value&&h.type!=="open"){c.push(Jt(c.pop(),h.value));continue}h.nodes&&s(h,r)}return c};return wn.flatten(s(n))};Sm.exports=ck});var km=H((rO,Am)=>{"use strict";Am.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
917
|
+
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Rm=H((iO,Tm)=>{"use strict";var uk=$r(),{MAX_LENGTH:$m,CHAR_BACKSLASH:tl,CHAR_BACKTICK:dk,CHAR_COMMA:fk,CHAR_DOT:pk,CHAR_LEFT_PARENTHESES:hk,CHAR_RIGHT_PARENTHESES:mk,CHAR_LEFT_CURLY_BRACE:gk,CHAR_RIGHT_CURLY_BRACE:yk,CHAR_LEFT_SQUARE_BRACKET:Em,CHAR_RIGHT_SQUARE_BRACKET:Cm,CHAR_DOUBLE_QUOTE:bk,CHAR_SINGLE_QUOTE:vk,CHAR_NO_BREAK_SPACE:wk,CHAR_ZERO_WIDTH_NOBREAK_SPACE:xk}=km(),Sk=(n,e={})=>{if(typeof n!="string")throw new TypeError("Expected a string");let t=e||{},s=typeof t.maxLength=="number"?Math.min($m,t.maxLength):$m;if(n.length>s)throw new SyntaxError(`Input length (${n.length}), exceeds max characters (${s})`);let r={type:"root",input:n,nodes:[]},i=[r],o=r,a=r,l=0,c=n.length,d=0,f=0,h,m=()=>n[d++],p=g=>{if(g.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&g.type==="text"){a.value+=g.value;return}return o.nodes.push(g),g.parent=o,g.prev=a,a=g,g};for(p({type:"bos"});d<c;)if(o=i[i.length-1],h=m(),!(h===xk||h===wk)){if(h===tl){p({type:"text",value:(e.keepEscaping?h:"")+m()});continue}if(h===Cm){p({type:"text",value:"\\"+h});continue}if(h===Em){l++;let g;for(;d<c&&(g=m());){if(h+=g,g===Em){l++;continue}if(g===tl){h+=m();continue}if(g===Cm&&(l--,l===0))break}p({type:"text",value:h});continue}if(h===hk){o=p({type:"paren",nodes:[]}),i.push(o),p({type:"text",value:h});continue}if(h===mk){if(o.type!=="paren"){p({type:"text",value:h});continue}o=i.pop(),p({type:"text",value:h}),o=i[i.length-1];continue}if(h===bk||h===vk||h===dk){let g=h,_;for(e.keepQuotes!==!0&&(h="");d<c&&(_=m());){if(_===tl){h+=_+m();continue}if(_===g){e.keepQuotes===!0&&(h+=_);break}h+=_}p({type:"text",value:h});continue}if(h===gk){f++;let _={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=p(_),i.push(o),p({type:"open",value:h});continue}if(h===yk){if(o.type!=="brace"){p({type:"text",value:h});continue}let g="close";o=i.pop(),o.close=!0,p({type:g,value:h}),f--,o=i[i.length-1];continue}if(h===fk&&f>0){if(o.ranges>0){o.ranges=0;let g=o.nodes.shift();o.nodes=[g,{type:"text",value:uk(o)}]}p({type:"comma",value:h}),o.commas++;continue}if(h===pk&&f>0&&o.commas===0){let g=o.nodes;if(f===0||g.length===0){p({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){g.pop();let _=g[g.length-1];_.value+=a.value+h,a=_,o.ranges--;continue}p({type:"dot",value:h});continue}p({type:"text",value:h})}do if(o=i.pop(),o.type!=="root"){o.nodes.forEach(A=>{A.nodes||(A.type==="open"&&(A.isOpen=!0),A.type==="close"&&(A.isClose=!0),A.nodes||(A.type="text"),A.invalid=!0)});let g=i[i.length-1],_=g.nodes.indexOf(o);g.nodes.splice(_,1,...o.nodes)}while(i.length>0);return p({type:"eos"}),r};Tm.exports=Sk});var Im=H((oO,Pm)=>{"use strict";var Om=$r(),_k=wm(),Ak=_m(),kk=Rm(),De=(n,e={})=>{let t=[];if(Array.isArray(n))for(let s of n){let r=De.create(s,e);Array.isArray(r)?t.push(...r):t.push(r)}else t=[].concat(De.create(n,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};De.parse=(n,e={})=>kk(n,e);De.stringify=(n,e={})=>Om(typeof n=="string"?De.parse(n,e):n,e);De.compile=(n,e={})=>(typeof n=="string"&&(n=De.parse(n,e)),_k(n,e));De.expand=(n,e={})=>{typeof n=="string"&&(n=De.parse(n,e));let t=Ak(n,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};De.create=(n,e={})=>n===""||n.length<3?[n]:e.expand!==!0?De.compile(n,e):De.expand(n,e);Pm.exports=De});var Mm=H((aO,$k)=>{$k.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var Dm=H((lO,Lm)=>{Lm.exports=Mm()});var Fm=H((cO,Nm)=>{"use strict";var Ek=require("path"),Ck=Dm(),Tk=new Set(Ck);Nm.exports=n=>Tk.has(Ek.extname(n).slice(1).toLowerCase())});var Tr=H(U=>{"use strict";var{sep:Rk}=require("path"),{platform:nl}=process,Ok=require("os");U.EV_ALL="all";U.EV_READY="ready";U.EV_ADD="add";U.EV_CHANGE="change";U.EV_ADD_DIR="addDir";U.EV_UNLINK="unlink";U.EV_UNLINK_DIR="unlinkDir";U.EV_RAW="raw";U.EV_ERROR="error";U.STR_DATA="data";U.STR_END="end";U.STR_CLOSE="close";U.FSEVENT_CREATED="created";U.FSEVENT_MODIFIED="modified";U.FSEVENT_DELETED="deleted";U.FSEVENT_MOVED="moved";U.FSEVENT_CLONED="cloned";U.FSEVENT_UNKNOWN="unknown";U.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;U.FSEVENT_TYPE_FILE="file";U.FSEVENT_TYPE_DIRECTORY="directory";U.FSEVENT_TYPE_SYMLINK="symlink";U.KEY_LISTENERS="listeners";U.KEY_ERR="errHandlers";U.KEY_RAW="rawEmitters";U.HANDLER_KEYS=[U.KEY_LISTENERS,U.KEY_ERR,U.KEY_RAW];U.DOT_SLASH=`.${Rk}`;U.BACK_SLASH_RE=/\\/g;U.DOUBLE_SLASH_RE=/\/\//;U.SLASH_OR_BACK_SLASH_RE=/[/\\]/;U.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;U.REPLACER_RE=/^\.[/\\]/;U.SLASH="/";U.SLASH_SLASH="//";U.BRACE_START="{";U.BANG="!";U.ONE_DOT=".";U.TWO_DOTS="..";U.STAR="*";U.GLOBSTAR="**";U.ROOT_GLOBSTAR="/**/*";U.SLASH_GLOBSTAR="/**";U.DIR_SUFFIX="Dir";U.ANYMATCH_OPTS={dot:!0};U.STRING_TYPE="string";U.FUNCTION_TYPE="function";U.EMPTY_STR="";U.EMPTY_FN=()=>{};U.IDENTITY_FN=n=>n;U.isWindows=nl==="win32";U.isMacos=nl==="darwin";U.isLinux=nl==="linux";U.isIBMi=Ok.type()==="OS400"});var qm=H((dO,Km)=>{"use strict";var $t=require("fs"),ye=require("path"),{promisify:is}=require("util"),Pk=Fm(),{isWindows:Ik,isLinux:Mk,EMPTY_FN:Lk,EMPTY_STR:Dk,KEY_LISTENERS:xn,KEY_ERR:sl,KEY_RAW:ns,HANDLER_KEYS:Nk,EV_CHANGE:Or,EV_ADD:Rr,EV_ADD_DIR:Fk,EV_ERROR:jm,STR_DATA:Hk,STR_END:jk,BRACE_START:Bk,STAR:Uk}=Tr(),Kk="watch",qk=is($t.open),Bm=is($t.stat),Wk=is($t.lstat),Gk=is($t.close),rl=is($t.realpath),Vk={lstat:Wk,stat:Bm},ol=(n,e)=>{n instanceof Set?n.forEach(e):e(n)},ss=(n,e,t)=>{let s=n[e];s instanceof Set||(n[e]=s=new Set([s])),s.add(t)},zk=n=>e=>{let t=n[e];t instanceof Set?t.clear():delete n[e]},rs=(n,e,t)=>{let s=n[e];s instanceof Set?s.delete(t):s===t&&delete n[e]},Um=n=>n instanceof Set?n.size===0:!n,Pr=new Map;function Hm(n,e,t,s,r){let i=(o,a)=>{t(n),r(o,a,{watchedPath:n}),a&&n!==a&&Ir(ye.resolve(n,a),xn,ye.join(n,a))};try{return $t.watch(n,e,i)}catch(o){s(o)}}var Ir=(n,e,t,s,r)=>{let i=Pr.get(n);i&&ol(i[e],o=>{o(t,s,r)})},Yk=(n,e,t,s)=>{let{listener:r,errHandler:i,rawEmitter:o}=s,a=Pr.get(e),l;if(!t.persistent)return l=Hm(n,t,r,i,o),l.close.bind(l);if(a)ss(a,xn,r),ss(a,sl,i),ss(a,ns,o);else{if(l=Hm(n,t,Ir.bind(null,e,xn),i,Ir.bind(null,e,ns)),!l)return;l.on(jm,async c=>{let d=Ir.bind(null,e,sl);if(a.watcherUnusable=!0,Ik&&c.code==="EPERM")try{let f=await qk(n,"r");await Gk(f),d(c)}catch{}else d(c)}),a={listeners:r,errHandlers:i,rawEmitters:o,watcher:l},Pr.set(e,a)}return()=>{rs(a,xn,r),rs(a,sl,i),rs(a,ns,o),Um(a.listeners)&&(a.watcher.close(),Pr.delete(e),Nk.forEach(zk(a)),a.watcher=void 0,Object.freeze(a))}},il=new Map,Jk=(n,e,t,s)=>{let{listener:r,rawEmitter:i}=s,o=il.get(e),a=new Set,l=new Set,c=o&&o.options;return c&&(c.persistent<t.persistent||c.interval>t.interval)&&(a=o.listeners,l=o.rawEmitters,$t.unwatchFile(e),o=void 0),o?(ss(o,xn,r),ss(o,ns,i)):(o={listeners:r,rawEmitters:i,options:t,watcher:$t.watchFile(e,t,(d,f)=>{ol(o.rawEmitters,m=>{m(Or,e,{curr:d,prev:f})});let h=d.mtimeMs;(d.size!==f.size||h>f.mtimeMs||h===0)&&ol(o.listeners,m=>m(n,d))})},il.set(e,o)),()=>{rs(o,xn,r),rs(o,ns,i),Um(o.listeners)&&(il.delete(e),$t.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},al=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let s=this.fsw.options,r=ye.dirname(e),i=ye.basename(e);this.fsw._getWatchedDir(r).add(i);let a=ye.resolve(e),l={persistent:s.persistent};t||(t=Lk);let c;return s.usePolling?(l.interval=s.enableBinaryInterval&&Pk(i)?s.binaryInterval:s.interval,c=Jk(e,a,l,{listener:t,rawEmitter:this.fsw._emitRaw})):c=Yk(e,a,l,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),c}_handleFile(e,t,s){if(this.fsw.closed)return;let r=ye.dirname(e),i=ye.basename(e),o=this.fsw._getWatchedDir(r),a=t;if(o.has(i))return;let l=async(d,f)=>{if(this.fsw._throttle(Kk,e,5)){if(!f||f.mtimeMs===0)try{let h=await Bm(e);if(this.fsw.closed)return;let m=h.atimeMs,p=h.mtimeMs;(!m||m<=p||p!==a.mtimeMs)&&this.fsw._emit(Or,e,h),Mk&&a.ino!==h.ino?(this.fsw._closeFile(d),a=h,this.fsw._addPathCloser(d,this._watchWithNodeFs(e,l))):a=h}catch{this.fsw._remove(r,i)}else if(o.has(i)){let h=f.atimeMs,m=f.mtimeMs;(!h||h<=m||m!==a.mtimeMs)&&this.fsw._emit(Or,e,f),a=f}}},c=this._watchWithNodeFs(e,l);if(!(s&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Rr,e,0))return;this.fsw._emit(Rr,e,t)}return c}async _handleSymlink(e,t,s,r){if(this.fsw.closed)return;let i=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await rl(s)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(r)?this.fsw._symlinkPaths.get(i)!==a&&(this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Or,s,e.stats)):(o.add(r),this.fsw._symlinkPaths.set(i,a),this.fsw._emit(Rr,s,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,s,r,i,o,a){if(e=ye.join(e,Dk),!s.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let l=this.fsw._getWatchedDir(s.path),c=new Set,d=this.fsw._readdirp(e,{fileFilter:f=>s.filterPath(f),directoryFilter:f=>s.filterDir(f),depth:0}).on(Hk,async f=>{if(this.fsw.closed){d=void 0;return}let h=f.path,m=ye.join(e,h);if(c.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,m,h))){if(this.fsw.closed){d=void 0;return}(h===r||!r&&!l.has(h))&&(this.fsw._incrReadyCount(),m=ye.join(i,ye.relative(i,m)),this._addToNodeFs(m,t,s,o+1))}}).on(jm,this._boundHandleError);return new Promise(f=>d.once(jk,()=>{if(this.fsw.closed){d=void 0;return}let h=a?a.clear():!1;f(),l.getChildren().filter(m=>m!==e&&!c.has(m)&&(!s.hasGlob||s.filterPath({fullPath:ye.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),d=void 0,h&&this._handleRead(e,!1,s,r,i,o,a)}))}async _handleDir(e,t,s,r,i,o,a){let l=this.fsw._getWatchedDir(ye.dirname(e)),c=l.has(ye.basename(e));!(s&&this.fsw.options.ignoreInitial)&&!i&&!c&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(Fk,e,t),l.add(ye.basename(e)),this.fsw._getWatchedDir(e);let d,f,h=this.fsw.options.depth;if((h==null||r<=h)&&!this.fsw._symlinkPaths.has(a)){if(!i&&(await this._handleRead(e,s,o,i,e,r,d),this.fsw.closed))return;f=this._watchWithNodeFs(e,(m,p)=>{p&&p.mtimeMs===0||this._handleRead(m,!1,o,i,e,r,d)})}return f}async _addToNodeFs(e,t,s,r,i){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,r);!a.hasGlob&&s&&(a.hasGlob=s.hasGlob,a.globFilter=s.globFilter,a.filterPath=l=>s.filterPath(l),a.filterDir=l=>s.filterDir(l));try{let l=await Vk[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))return o(),!1;let c=this.fsw.options.followSymlinks&&!e.includes(Uk)&&!e.includes(Bk),d;if(l.isDirectory()){let f=ye.resolve(e),h=c?await rl(e):e;if(this.fsw.closed||(d=await this._handleDir(a.watchPath,l,t,r,i,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(l.isSymbolicLink()){let f=c?await rl(e):e;if(this.fsw.closed)return;let h=ye.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(Rr,a.watchPath,l),d=await this._handleDir(h,l,t,r,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(ye.resolve(e),f)}else d=this._handleFile(a.watchPath,l,t);return o(),this.fsw._addPathCloser(e,d),!1}catch(l){if(this.fsw._handleError(l))return o(),e}}};Km.exports=al});var Qm=H((fO,ml)=>{"use strict";var pl=require("fs"),be=require("path"),{promisify:hl}=require("util"),Sn;try{Sn=require("fsevents")}catch(n){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(n)}if(Sn){let n=process.version.match(/v(\d+)\.(\d+)/);if(n&&n[1]&&n[2]){let e=Number.parseInt(n[1],10),t=Number.parseInt(n[2],10);e===8&&t<16&&(Sn=void 0)}}var{EV_ADD:ll,EV_CHANGE:Qk,EV_ADD_DIR:Wm,EV_UNLINK:Mr,EV_ERROR:Xk,STR_DATA:Zk,STR_END:e$,FSEVENT_CREATED:t$,FSEVENT_MODIFIED:n$,FSEVENT_DELETED:s$,FSEVENT_MOVED:r$,FSEVENT_UNKNOWN:i$,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:o$,FSEVENT_TYPE_FILE:a$,FSEVENT_TYPE_DIRECTORY:os,FSEVENT_TYPE_SYMLINK:Jm,ROOT_GLOBSTAR:Gm,DIR_SUFFIX:l$,DOT_SLASH:Vm,FUNCTION_TYPE:cl,EMPTY_FN:c$,IDENTITY_FN:u$}=Tr(),d$=n=>isNaN(n)?{}:{depth:n},dl=hl(pl.stat),f$=hl(pl.lstat),zm=hl(pl.realpath),p$={stat:dl,lstat:f$},Qt=new Map,h$=10,m$=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),g$=(n,e)=>({stop:Sn.watch(n,e)});function y$(n,e,t,s){let r=be.extname(e)?be.dirname(e):e,i=be.dirname(r),o=Qt.get(r);b$(i)&&(r=i);let a=be.resolve(n),l=a!==e,c=(f,h,m)=>{l&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+be.sep))&&t(f,h,m)},d=!1;for(let f of Qt.keys())if(e.indexOf(be.resolve(f)+be.sep)===0){r=f,o=Qt.get(r),d=!0;break}return o||d?o.listeners.add(c):(o={listeners:new Set([c]),rawEmitter:s,watcher:g$(r,(f,h)=>{if(!o.listeners.size||h&o$)return;let m=Sn.getInfo(f,h);o.listeners.forEach(p=>{p(f,h,m)}),o.rawEmitter(m.event,f,m)})},Qt.set(r,o)),()=>{let f=o.listeners;if(f.delete(c),!f.size&&(Qt.delete(r),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var b$=n=>{let e=0;for(let t of Qt.keys())if(t.indexOf(n)===0&&(e++,e>=h$))return!0;return!1},v$=()=>Sn&&Qt.size<128,ul=(n,e)=>{let t=0;for(;!n.indexOf(e)&&(n=be.dirname(n))!==e;)t++;return t},Ym=(n,e)=>n.type===os&&e.isDirectory()||n.type===Jm&&e.isSymbolicLink()||n.type===a$&&e.isFile(),fl=class{constructor(e){this.fsw=e}checkIgnored(e,t){let s=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return s.add(e),t&&t.isDirectory()&&s.add(e+Gm),!0;s.delete(e),s.delete(e+Gm)}addOrChange(e,t,s,r,i,o,a,l){let c=i.has(o)?Qk:ll;this.handleEvent(c,e,t,s,r,i,o,a,l)}async checkExists(e,t,s,r,i,o,a,l){try{let c=await dl(e);if(this.fsw.closed)return;Ym(a,c)?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(Mr,e,t,s,r,i,o,a,l)}catch(c){c.code==="EACCES"?this.addOrChange(e,t,s,r,i,o,a,l):this.handleEvent(Mr,e,t,s,r,i,o,a,l)}}handleEvent(e,t,s,r,i,o,a,l,c){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===Mr){let d=l.type===os;(d||o.has(a))&&this.fsw._remove(i,a,d)}else{if(e===ll){if(l.type===os&&this.fsw._getWatchedDir(t),l.type===Jm&&c.followSymlinks){let f=c.depth===void 0?void 0:ul(s,r)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(i).add(a)}let d=l.type===os?e+l$:e;this.fsw._emit(d,t),d===Wm&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,s,r){if(this.fsw.closed||this.fsw._isIgnored(e))return;let i=this.fsw.options,a=y$(e,t,async(l,c,d)=>{if(this.fsw.closed||i.depth!==void 0&&ul(l,t)>i.depth)return;let f=s(be.join(e,be.relative(e,l)));if(r&&!r(f))return;let h=be.dirname(f),m=be.basename(f),p=this.fsw._getWatchedDir(d.type===os?f:h);if(m$.has(c)||d.event===i$)if(typeof i.ignored===cl){let g;try{g=await dl(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,g))return;Ym(d,g)?this.addOrChange(f,l,t,h,p,m,d,i):this.handleEvent(Mr,f,l,t,h,p,m,d,i)}else this.checkExists(f,l,t,h,p,m,d,i);else switch(d.event){case t$:case n$:return this.addOrChange(f,l,t,h,p,m,d,i);case s$:case r$:return this.checkExists(f,l,t,h,p,m,d,i)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,s,r){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let i=await zm(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(i))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(i||e,o=>{let a=e;return i&&i!==Vm?a=o.replace(i,e):o!==Vm&&(a=be.join(e,o)),s(a)},!1,r)}catch(i){if(this.fsw._handleError(i))return this.fsw._emitReady()}}}emitAdd(e,t,s,r,i){let o=s(e),a=t.isDirectory(),l=this.fsw._getWatchedDir(be.dirname(o)),c=be.basename(o);a&&this.fsw._getWatchedDir(o),!l.has(c)&&(l.add(c),(!r.ignoreInitial||i===!0)&&this.fsw._emit(a?Wm:ll,o,t))}initWatch(e,t,s,r){if(this.fsw.closed)return;let i=this._watchWithFsEvents(s.watchPath,be.resolve(e||s.watchPath),r,s.globFilter);this.fsw._addPathCloser(t,i)}async _addToFsEvents(e,t,s,r){if(this.fsw.closed)return;let i=this.fsw.options,o=typeof t===cl?t:u$,a=this.fsw._getWatchHelpers(e);try{let l=await p$[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,l))throw null;if(l.isDirectory()){if(a.globFilter||this.emitAdd(o(e),l,o,i,s),r&&r>i.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:c=>a.filterPath(c),directoryFilter:c=>a.filterDir(c),...d$(i.depth-(r||0))}).on(Zk,c=>{if(this.fsw.closed||c.stats.isDirectory()&&!a.filterPath(c))return;let d=be.join(a.watchPath,c.path),{fullPath:f}=c;if(a.followSymlinks&&c.stats.isSymbolicLink()){let h=i.depth===void 0?void 0:ul(d,be.resolve(a.watchPath))+1;this._handleFsEventsSymlink(d,f,o,h)}else this.emitAdd(d,c.stats,o,i,s)}).on(Xk,c$).on(e$,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,l,o,i,s),this.fsw._emitReady()}catch(l){(!l||this.fsw._handleError(l))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(i.persistent&&s!==!0)if(typeof t===cl)this.initWatch(void 0,e,a,o);else{let l;try{l=await zm(a.watchPath)}catch{}this.initWatch(l,e,a,o)}}};ml.exports=fl;ml.exports.canUse=v$});var lg=H(Rl=>{"use strict";var{EventEmitter:w$}=require("events"),Cl=require("fs"),Z=require("path"),{promisify:rg}=require("util"),x$=Fh(),xl=Wh().default,S$=Qh(),gl=Ya(),_$=Im(),A$=Va(),k$=qm(),Xm=Qm(),{EV_ALL:yl,EV_READY:$$,EV_ADD:Lr,EV_CHANGE:as,EV_UNLINK:Zm,EV_ADD_DIR:E$,EV_UNLINK_DIR:C$,EV_RAW:T$,EV_ERROR:bl,STR_CLOSE:R$,STR_END:O$,BACK_SLASH_RE:P$,DOUBLE_SLASH_RE:eg,SLASH_OR_BACK_SLASH_RE:I$,DOT_RE:M$,REPLACER_RE:L$,SLASH:vl,SLASH_SLASH:D$,BRACE_START:N$,BANG:Sl,ONE_DOT:ig,TWO_DOTS:F$,GLOBSTAR:H$,SLASH_GLOBSTAR:wl,ANYMATCH_OPTS:_l,STRING_TYPE:Tl,FUNCTION_TYPE:j$,EMPTY_STR:Al,EMPTY_FN:B$,isWindows:U$,isMacos:K$,isIBMi:q$}=Tr(),W$=rg(Cl.stat),G$=rg(Cl.readdir),kl=(n=[])=>Array.isArray(n)?n:[n],og=(n,e=[])=>(n.forEach(t=>{Array.isArray(t)?og(t,e):e.push(t)}),e),tg=n=>{let e=og(kl(n));if(!e.every(t=>typeof t===Tl))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(ag)},ng=n=>{let e=n.replace(P$,vl),t=!1;for(e.startsWith(D$)&&(t=!0);e.match(eg);)e=e.replace(eg,vl);return t&&(e=vl+e),e},ag=n=>ng(Z.normalize(ng(n))),sg=(n=Al)=>e=>typeof e!==Tl?e:ag(Z.isAbsolute(e)?e:Z.join(n,e)),V$=(n,e)=>Z.isAbsolute(n)?n:n.startsWith(Sl)?Sl+Z.join(e,n.slice(1)):Z.join(e,n),st=(n,e)=>n[e]===void 0,$l=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==ig&&e!==F$&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let s=this.path;try{await G$(s)}catch{this._removeWatcher&&this._removeWatcher(Z.dirname(s),Z.basename(s))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},z$="stat",Y$="lstat",El=class{constructor(e,t,s,r){this.fsw=r,this.path=e=e.replace(L$,Al),this.watchPath=t,this.fullWatchPath=Z.resolve(t),this.hasGlob=t!==e,e===Al&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&s?void 0:!1,this.globFilter=this.hasGlob?xl(e,void 0,_l):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=s,this.statMethod=s?z$:Y$}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return Z.join(this.watchPath,Z.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let s=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===j$?this.globFilter(s):!0)&&this.fsw._isntIgnored(s,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(N$)?_$.expand(e):[e]).forEach(r=>{t.push(Z.relative(this.watchPath,r).split(I$))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),s=!1;this.unmatchedGlob=!this.dirParts.some(r=>r.every((i,o)=>(i===H$&&(s=!0),s||!t[0][o]||xl(i,t[0][o],_l))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Dr=class extends w${constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,st(t,"persistent")&&(t.persistent=!0),st(t,"ignoreInitial")&&(t.ignoreInitial=!1),st(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),st(t,"interval")&&(t.interval=100),st(t,"binaryInterval")&&(t.binaryInterval=300),st(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,st(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),Xm.canUse()||(t.useFsEvents=!1),st(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=K$),q$&&(t.usePolling=!0);let r=process.env.CHOKIDAR_USEPOLLING;if(r!==void 0){let l=r.toLowerCase();l==="false"||l==="0"?t.usePolling=!1:l==="true"||l==="1"?t.usePolling=!0:t.usePolling=!!l}let i=process.env.CHOKIDAR_INTERVAL;i&&(t.interval=Number.parseInt(i,10)),st(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),st(t,"followSymlinks")&&(t.followSymlinks=!0),st(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=kl(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=B$,this._readyEmitted=!0,process.nextTick(()=>this.emit($$)))},this._emitRaw=(...l)=>this.emit(T$,...l),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new Xm(this):this._nodeFsHandler=new k$(this),Object.freeze(t)}add(e,t,s){let{cwd:r,disableGlobbing:i}=this.options;this.closed=!1;let o=tg(e);return r&&(o=o.map(a=>{let l=V$(a,r);return i||!gl(a)?l:A$(l)})),o=o.filter(a=>a.startsWith(Sl)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+wl),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let l=await this._nodeFsHandler._addToNodeFs(a,!s,0,0,t);return l&&this._emitReady(),l})).then(a=>{this.closed||a.filter(l=>l).forEach(l=>{this.add(Z.dirname(l),Z.basename(t||l))})})),this}unwatch(e){if(this.closed)return this;let t=tg(e),{cwd:s}=this.options;return t.forEach(r=>{!Z.isAbsolute(r)&&!this._closers.has(r)&&(s&&(r=Z.join(s,r)),r=Z.resolve(r)),this._closePath(r),this._ignoredPaths.add(r),this._watched.has(r)&&this._ignoredPaths.add(r+wl),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(s=>{let r=s();r instanceof Promise&&e.push(r)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,s)=>{let r=this.options.cwd?Z.relative(this.options.cwd,s):s;e[r||ig]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==bl&&this.emit(yl,...t)}async _emit(e,t,s,r,i){if(this.closed)return;let o=this.options;U$&&(t=Z.normalize(t)),o.cwd&&(t=Z.relative(o.cwd,t));let a=[e,t];i!==void 0?a.push(s,r,i):r!==void 0?a.push(s,r):s!==void 0&&a.push(s);let l=o.awaitWriteFinish,c;if(l&&(c=this._pendingWrites.get(t)))return c.lastChange=new Date,this;if(o.atomic){if(e===Zm)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((d,f)=>{this.emit(...d),this.emit(yl,...d),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===Lr&&this._pendingUnlinks.has(t)&&(e=a[0]=as,this._pendingUnlinks.delete(t))}if(l&&(e===Lr||e===as)&&this._readyEmitted){let d=(f,h)=>{f?(e=a[0]=bl,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,l.stabilityThreshold,e,d),this}if(e===as&&!this._throttle(as,t,50))return this;if(o.alwaysStat&&s===void 0&&(e===Lr||e===E$||e===as)){let d=o.cwd?Z.join(o.cwd,t):t,f;try{f=await W$(d)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(bl,e),e||this.closed}_throttle(e,t,s){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e),i=r.get(t);if(i)return i.count++,!1;let o,a=()=>{let c=r.get(t),d=c?c.count:0;return r.delete(t),clearTimeout(o),c&&clearTimeout(c.timeoutObject),d};o=setTimeout(a,s);let l={timeoutObject:o,clear:a,count:0};return r.set(t,l),l}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,s,r){let i,o=e;this.options.cwd&&!Z.isAbsolute(e)&&(o=Z.join(this.options.cwd,e));let a=new Date,l=c=>{Cl.stat(o,(d,f)=>{if(d||!this._pendingWrites.has(e)){d&&d.code!=="ENOENT"&&r(d);return}let h=Number(new Date);c&&f.size!==c.size&&(this._pendingWrites.get(e).lastChange=h);let m=this._pendingWrites.get(e);h-m.lastChange>=t?(this._pendingWrites.delete(e),r(void 0,f)):i=setTimeout(l,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(i),s)}),i=setTimeout(l,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&M$.test(e))return!0;if(!this._userIgnored){let{cwd:s}=this.options,r=this.options.ignored,i=r&&r.map(sg(s)),o=kl(i).filter(l=>typeof l===Tl&&!gl(l)).map(l=>l+wl),a=this._getGlobIgnored().map(sg(s)).concat(i,o);this._userIgnored=xl(a,void 0,_l)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let s=t||this.options.disableGlobbing||!gl(e)?e:S$(e),r=this.options.followSymlinks;return new El(e,s,r,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=Z.resolve(e);return this._watched.has(t)||this._watched.set(t,new $l(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let s=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(s.toString(8)[0],10))}_remove(e,t,s){let r=Z.join(e,t),i=Z.resolve(r);if(s=s??(this._watched.has(r)||this._watched.has(i)),!this._throttle("remove",r,100))return;!s&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(h=>this._remove(r,h));let l=this._getWatchedDir(e),c=l.has(t);l.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let d=r;if(this.options.cwd&&(d=Z.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(d)&&this._pendingWrites.get(d).cancelWait()===Lr)return;this._watched.delete(r),this._watched.delete(i);let f=s?C$:Zm;c&&!this._isIgnored(r)&&this._emit(f,r),this.options.useFsEvents||this._closePath(r)}_closePath(e){this._closeFile(e);let t=Z.dirname(e);this._getWatchedDir(t).remove(Z.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(s=>s()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let s=this._closers.get(e);s||(s=[],this._closers.set(e,s)),s.push(t)}_readdirp(e,t){if(this.closed)return;let s={type:yl,alwaysStat:!0,lstat:!0,...t},r=x$(e,s);return this._streams.add(r),r.once(R$,()=>{r=void 0}),r.once(O$,()=>{r&&(this._streams.delete(r),r=void 0)}),r}};Rl.FSWatcher=Dr;var J$=(n,e)=>{let t=new Dr(e);return t.add(n),t};Rl.watch=J$});var fg={};Pe(fg,{CollaborationManager:()=>Ol,addTeamMember:()=>Z$,formatTeamConfig:()=>e0,initTeamConfig:()=>X$,loadTeamConfig:()=>Q$,saveTeamConfig:()=>dg});function Q$(n){let e=Ve.join(n,".hablas","team.json");if(de.existsSync(e))try{return JSON.parse(de.readFileSync(e,"utf-8"))}catch{return null}return null}function X$(n,e){let t={name:e,members:[]};return dg(n,t),t}function dg(n,e){let t=Ve.join(n,".hablas","team.json"),s=Ve.dirname(t);de.existsSync(s)||de.mkdirSync(s,{recursive:!0}),de.writeFileSync(t,JSON.stringify(e,null,2),"utf-8")}function Z$(n,e,t){return n.members.push({name:e,email:t}),n}function e0(n){return[`Team: ${n.name}`,"Members:",...n.members.map(t=>` - ${t.name} (${t.email})`)].join(`
|
|
918
|
+
`)}var de,Ve,Nr,cg,ug,Ol,pg=N(()=>{"use strict";de=O(require("fs")),Ve=O(require("path")),Nr=O(require("os")),cg=O(require("crypto")),ug=O(lg());rn();Ol=class n{workingDir;config;username;teamKey;projectTeamToken;supabaseUrl="";supabaseKey="";isConfigured=!1;watcher=null;localStatePath;heartbeatInterval=null;syncInterval=null;static HEARTBEAT_MS=12e3;static POLL_ACTIVE_MS=3e3;static POLL_IDLE_MS=2e4;static STALE_MS=75e3;consecutiveHeartbeatFailures=0;announcedOffline=!1;idlePollTicks=0;signalHandler=null;shuttingDown=!1;currentActivity={section:"idle",task:"standby"};knownSessions=new Map;knownLocks=new Map;constructor(e,t,s,r){this.workingDir=e,this.config=t,this.username=s||Nr.userInfo().username||"developer",this.teamKey=r||"default-team",this.localStatePath=Ve.join(this.workingDir,".hablas","collaboration.json");let i=this.getProjectIdentifier();console.log(`
|
|
919
|
+
${u.muted("[Debug] Project Context:")} ${u.highlight(i)}`),this.projectTeamToken=cg.createHash("sha256").update(`${i}:${this.teamKey}`).digest("hex"),console.log(` ${u.muted("[Debug] Session Fingerprint:")} ${u.muted(this.projectTeamToken.slice(0,16))}...
|
|
920
|
+
`),this.loadSupabaseConfig()}async init(){if(!this.isConfigured)return console.log(` ${u.warning("\u26A0")} ${u.secondary("Supabase is not configured in .env. Collaboration mode operates locally.")}`),!1;let e=Ve.dirname(this.localStatePath);return de.existsSync(e)||de.mkdirSync(e,{recursive:!0}),this.saveLocalState([],[]),this.startLoops(),this.startWatcher(),this.registerCleanups(),!0}async shutdown(){this.shuttingDown||(this.shuttingDown=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.syncInterval&&(clearTimeout(this.syncInterval),this.syncInterval=null),this.watcher&&(await this.watcher.close(),this.watcher=null),this.signalHandler&&(process.off("SIGINT",this.signalHandler),process.off("SIGTERM",this.signalHandler),this.signalHandler=null),await this.releaseAllMyLocks(),await this.deleteSession())}async apiRequest(e,t,s,r){if(!this.isConfigured)return{ok:!1,data:null};let i=`${this.supabaseUrl}/rest/v1/${e}`,o={apikey:this.supabaseKey,Authorization:`Bearer ${this.supabaseKey}`,"Content-Type":"application/json"};r?.prefer?o.Prefer=r.prefer:(t==="POST"||t==="PATCH")&&(o.Prefer="return=representation");let a=(r?.retries??0)+1,l=null;for(let c=0;c<a;c++)try{let d=await fetch(i,{method:t,headers:o,body:s?JSON.stringify(s):void 0,signal:AbortSignal.timeout(1e4)});if(!d.ok){let h=await d.text().catch(()=>"");if(l=new Error(`[Supabase ${d.status}] ${h}`),(d.status>=500||d.status===429)&&c<a-1){await this.delay(400*(c+1));continue}return{ok:!1,data:null}}let f=await d.text();return{ok:!0,data:f?JSON.parse(f):null}}catch(d){if(l=d,c<a-1){await this.delay(400*(c+1));continue}}return{ok:!1,data:null}}delay(e){return new Promise(t=>setTimeout(t,e))}async sendHeartbeat(e,t){let s={project_team_token:this.projectTeamToken,developer_name:this.username,last_heartbeat:new Date().toISOString(),active_section:e||"idle",current_task:t||"none"},r="hablas_team_sessions?on_conflict=project_team_token,developer_name",{ok:i}=await this.apiRequest(r,"POST",s,{prefer:"resolution=merge-duplicates,return=minimal",retries:2});return i}async fetchSessions(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async deleteSession(){let e=`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}&developer_name=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async fetchLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}`,{data:t}=await this.apiRequest(e,"GET");return t||[]}async acquireLock(e,t){let s={project_team_token:this.projectTeamToken,file_path:e,locked_by:this.username,lock_context:t||"editing file",created_at:new Date().toISOString()};return await this.apiRequest("hablas_team_locks?on_conflict=project_team_token,file_path","POST",s,{prefer:"resolution=ignore-duplicates,return=minimal",retries:1}),!!(await this.fetchLocks()).find(a=>a.file_path===e&&a.locked_by===this.username)}async releaseLock(e){let t=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&file_path=eq.${encodeURIComponent(e)}&locked_by=eq.${encodeURIComponent(this.username)}`;return await this.apiRequest(t,"DELETE"),!0}async releaseAllMyLocks(){let e=`hablas_team_locks?project_team_token=eq.${this.projectTeamToken}&locked_by=eq.${encodeURIComponent(this.username)}`;await this.apiRequest(e,"DELETE")}async sendMessage(e,t){let s={project_team_token:this.projectTeamToken,sender_name:this.username,receiver_name:e,message_content:t,is_read:!1,created_at:new Date().toISOString()},{ok:r}=await this.apiRequest("hablas_team_messages","POST",s,{retries:1});return r}async fetchUnreadMessages(){let e=`hablas_team_messages?project_team_token=eq.${this.projectTeamToken}&receiver_name=eq.${encodeURIComponent(this.username)}&is_read=eq.false`,t=(await this.apiRequest(e,"GET")).data||[];if(t.length>0)for(let s of t){let r=`hablas_team_messages?id=eq.${s.id}`;await this.apiRequest(r,"PATCH",{is_read:!0})}return t}saveLocalState(e,t){let s={project_team_token:this.projectTeamToken,last_sync:new Date().toISOString(),my_username:this.username,sessions:e,locks:t};de.writeFileSync(this.localStatePath,JSON.stringify(s,null,2),"utf-8")}getLocalState(){if(de.existsSync(this.localStatePath))try{return JSON.parse(de.readFileSync(this.localStatePath,"utf-8"))}catch{}return{sessions:[],locks:[],my_username:this.username}}startLoops(){this.beat("idle","standby"),this.heartbeatInterval=setInterval(()=>{this.beat()},n.HEARTBEAT_MS);let e=t=>{this.syncInterval=setTimeout(async()=>{if(this.shuttingDown)return;await this.syncWithCloud()?this.idlePollTicks=0:this.idlePollTicks++;let r=this.idlePollTicks>=3?n.POLL_IDLE_MS:n.POLL_ACTIVE_MS;e(r)},t)};e(n.POLL_ACTIVE_MS)}setActivity(e,t="working"){this.currentActivity={section:t,task:e.slice(0,120)},this.beat(t,this.currentActivity.task)}async beat(e,t){await this.sendHeartbeat(e??this.currentActivity.section,t??this.currentActivity.task)?(this.announcedOffline&&(console.log(`
|
|
921
|
+
${u.success("\u2713")} ${u.muted("[Team]")} Cloud sync reconnected \u2014 session restored.
|
|
922
|
+
`),this.announcedOffline=!1),this.consecutiveHeartbeatFailures=0):(this.consecutiveHeartbeatFailures++,this.consecutiveHeartbeatFailures>=4&&!this.announcedOffline&&(console.log(`
|
|
923
|
+
${u.warning("\u26A0")} ${u.muted("[Team]")} Cloud sync is unreachable \u2014 retrying in the background. Your session is preserved.
|
|
924
|
+
`),this.announcedOffline=!0))}async syncWithCloud(){let e=await this.apiRequest(`hablas_team_sessions?project_team_token=eq.${this.projectTeamToken}`,"GET");if(!e.ok)return!1;let t=e.data||[],s=await this.fetchLocks(),r=await this.fetchUnreadMessages();for(let c of r)this.renderMessageBox(c.sender_name,c.message_content);let i=Date.now(),o=t.filter(c=>{if(c.developer_name===this.username)return!0;let d=new Date(c.last_heartbeat).getTime();return i-d<=n.STALE_MS}),a=this.getLocalState(),l=r.length>0||JSON.stringify(a.sessions?.map(c=>c.developer_name).sort())!==JSON.stringify(o.map(c=>c.developer_name).sort())||JSON.stringify(a.locks?.map(c=>`${c.file_path}:${c.locked_by}`).sort())!==JSON.stringify(s.map(c=>`${c.file_path}:${c.locked_by}`).sort());return this.saveLocalState(o,s),l}startWatcher(){this.watcher=ug.default.watch(this.localStatePath,{ignoreInitial:!1,persistent:!0}),this.watcher.on("change",()=>{let e=this.getLocalState();this.processStateChanges(e.sessions,e.locks)})}processStateChanges(e,t){let s=new Set;for(let i of e)if(i.developer_name!==this.username)if(s.add(i.developer_name),!this.knownSessions.has(i.developer_name))this.knownSessions.set(i.developer_name,i.current_task||"none"),console.log(`
|
|
925
|
+
${u.success("\u{1F514}")} ${u.muted("[Live Sync]")} ${u.strong(`@${i.developer_name}`)} has joined the session.
|
|
926
|
+
`);else{let o=this.knownSessions.get(i.developer_name);i.current_task&&i.current_task!==o&&i.current_task!=="none"&&(this.knownSessions.set(i.developer_name,i.current_task),console.log(` ${u.accent("\u27F3")} ${u.muted("[Activity]")} ${u.strong(`@${i.developer_name}`)} is now: "${u.secondary(i.current_task)}"
|
|
927
|
+
`))}for(let i of this.knownSessions.keys())s.has(i)||(this.knownSessions.delete(i),console.log(`
|
|
928
|
+
${u.warning("\u{1F44B}")} ${u.muted("[Live Sync]")} ${u.strong(`@${i}`)} has left the session.
|
|
929
|
+
`));let r=new Set;for(let i of t)r.add(i.file_path),this.knownLocks.has(i.file_path)||(this.knownLocks.set(i.file_path,i.locked_by),i.locked_by!==this.username&&console.log(` ${u.error("\u{1F512}")} ${u.muted("[File Locked]")} ${u.strong(`@${i.locked_by}`)} locked ${u.highlight(i.file_path)}`));for(let i of this.knownLocks.keys())if(!r.has(i)){let o=this.knownLocks.get(i);this.knownLocks.delete(i),o!==this.username&&console.log(` ${u.success("\u{1F513}")} ${u.muted("[File Unlocked]")} ${u.strong(`@${o}`)} released lock on ${u.highlight(i)}`)}}renderMessageBox(e,t){let s=Math.min(process.stdout.columns-4,80),r=u.border("\u250C"+"\u2500".repeat(s-2)+"\u2510"),i=u.border("\u2514"+"\u2500".repeat(s-2)+"\u2518"),o=` MESSAGE FROM @${e.toUpperCase()} `,a=Math.max(0,Math.floor((s-2-o.length)/2)),l=u.border("\u2502")+" ".repeat(a)+u.strong(o)+" ".repeat(s-2-o.length-a)+u.border("\u2502"),c=t.replace(/\n/g," "),d=Math.max(0,s-8-c.length),f=u.border("\u2502")+` "${u.secondary(c)}"`+" ".repeat(d)+u.border("\u2502");console.log(`
|
|
930
|
+
`+r),console.log(l),console.log(f),console.log(i+`
|
|
931
|
+
`)}registerCleanups(){this.signalHandler||(this.signalHandler=()=>{this.shutdown()},process.on("SIGTERM",this.signalHandler),process.once("beforeExit",this.signalHandler))}loadSupabaseConfig(){let e=Ve.join(this.workingDir,".env");if(de.existsSync(e))try{let s=de.readFileSync(e,"utf-8").split(`
|
|
932
|
+
`);for(let r of s){let i=r.split("=");if(i.length>=2){let o=i[0].trim(),a=i.slice(1).join("=").trim().replace(/^['"]|['"]$/g,"");o==="SUPABASE_URL"||o==="VITE_SUPABASE_URL"?this.supabaseUrl=a:(o==="SUPABASE_KEY"||o==="SUPABASE_ANON_KEY"||o==="VITE_SUPABASE_ANON_KEY")&&(this.supabaseKey=a)}}}catch{}if(!this.supabaseUrl||!this.supabaseKey){let t="aHR0cHM6Ly93dXVtYXptcGp6dHZ4a3l3Y3Rvci5zdXBhYmFzZS5jbw==",s="c2JfcHVibGlzaGFibGVfVmxmNEtCUzdsaTRjaGFWNE04d19xQV9fbnJuczh1WQ==";this.supabaseUrl=Buffer.from(t,"base64").toString("utf-8"),this.supabaseKey=Buffer.from(s,"base64").toString("utf-8")}this.isConfigured=!!(this.supabaseUrl&&this.supabaseKey),this.isConfigured&&this.syncLlmConfig()}syncLlmConfig(){let e=Ve.join(Nr.homedir(),".hablas","config.json");if(de.existsSync(e))try{let t=JSON.parse(de.readFileSync(e,"utf-8"));!this.config.apiUrl&&t.apiUrl&&(this.config.apiUrl=t.apiUrl,this.config.apiKey=t.apiKey,this.config.provider=t.provider)}catch{}}getProjectIdentifier(){let e="";try{let{execSync:t}=require("child_process"),s=t("git config --get remote.origin.url",{cwd:this.workingDir,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(s){let r=s.match(/[:/]([^/]+\/[^/.]+)(\.git)?$/);r&&r[1]&&(e=r[1].toLowerCase())}}catch{}if(!e)try{let t=Ve.join(this.workingDir,"package.json");if(de.existsSync(t)){let s=JSON.parse(de.readFileSync(t,"utf-8"));s.name&&(e=s.name.toLowerCase())}}catch{}return e||(e=Ve.basename(this.workingDir).toLowerCase()),e.replace(/\s+/g,"")}}});var bg={};Pe(bg,{createApiServer:()=>yg,startApiServer:()=>r0});function t0(){try{return JSON.parse(mg.readFileSync(gg.resolve(__dirname,"..","..","package.json"),"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}function yg(n){let e=At(n),t=s0(n);return hg.createServer(async(r,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.setHeader("Content-Type","application/json"),r.method==="OPTIONS"){i.writeHead(204),i.end();return}if(n.api.apiKey&&(r.headers.authorization||"").replace("Bearer ","")!==n.api.apiKey){i.writeHead(401),i.end(JSON.stringify({error:"Unauthorized",message:"Invalid API key"}));return}let o={};if(r.method==="POST"||r.method==="PUT")try{let l=[];for await(let d of r)l.push(d);let c=Buffer.concat(l).toString();c&&(o=JSON.parse(c))}catch{i.writeHead(400),i.end(JSON.stringify({error:"Bad Request",message:"Invalid JSON body"}));return}let a=t.find(l=>l.method===r.method&&r.url?.startsWith(l.path));if(!a){i.writeHead(404),i.end(JSON.stringify({error:"Not Found",message:`No route for ${r.method} ${r.url}`}));return}try{let l={method:r.method||"GET",path:r.url||"/",body:o,headers:r.headers},c=await a.handler(l);i.writeHead(c.status),i.end(JSON.stringify(c.body))}catch(l){e.error({err:l},"API error"),i.writeHead(500),i.end(JSON.stringify({error:"Internal Server Error",message:String(l)}))}})}function s0(n){return[{method:"GET",path:"/api/v1/health",handler:async()=>({status:200,body:{status:"ok",version:n0,uptime:process.uptime()}})},{method:"GET",path:"/api/v1/agents",handler:async()=>({status:200,body:{agents:[{name:"coder",description:"Code generation and modification",status:"available"},{name:"reviewer",description:"Code review and quality analysis",status:"available"},{name:"architect",description:"System architecture design",status:"available"},{name:"devops",description:"Deployment and infrastructure",status:"available"},{name:"researcher",description:"Documentation and research",status:"available"},{name:"planner",description:"Task decomposition and planning",status:"available"},{name:"debugger",description:"Error analysis and fixing",status:"available"}]}})},{method:"GET",path:"/api/v1/models",handler:async()=>({status:200,body:{current:n.model,provider:n.provider,host:n.ollamaHost}})},{method:"POST",path:"/api/v1/chat",handler:async e=>{let{message:t,agent:s}=e.body;return t?{status:200,body:{response:`[${s||"coder"}] Received: ${t}`,agent:s||"coder",model:n.model}}:{status:400,body:{error:"message field is required"}}}},{method:"POST",path:"/api/v1/plan",handler:async e=>{let{task:t}=e.body;return t?{status:200,body:{plan:{task:t,steps:[{step:1,description:"Analyze requirements",agent:"researcher"},{step:2,description:"Design architecture",agent:"architect"},{step:3,description:"Implement code",agent:"coder"},{step:4,description:"Review and test",agent:"reviewer"}]}}}:{status:400,body:{error:"task field is required"}}}},{method:"POST",path:"/api/v1/execute",handler:async e=>{let{command:t}=e.body;return t?n.api.enabled?{status:200,body:{message:"Command queued for execution",command:t}}:{status:403,body:{error:"API execution not enabled"}}:{status:400,body:{error:"command field is required"}}}},{method:"GET",path:"/api/v1/stats",handler:async()=>({status:200,body:{sessions:0,messages:0,uptime:process.uptime(),model:n.model,provider:n.provider}})}]}function r0(n){return new Promise((e,t)=>{let s=yg(n);s.on("error",t),s.listen(n.api.port,n.api.host,()=>{e(s)})})}var hg,mg,gg,n0,vg=N(()=>{"use strict";hg=O(require("http")),mg=O(require("fs")),gg=O(require("path"));Pa();n0=t0()});var xg={};Pe(xg,{runSetupWizard:()=>a0});function fe(n,e){return new Promise(t=>{n.question(e,s=>t(s))})}function o0(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}async function a0(n){let e=wg.createInterface({input:process.stdin,output:process.stdout});switch(console.log(),console.log(`${Mt}${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${P}`),console.log(`${Mt}${Ne} hablas \u2014 Setup Wizard${P}`),console.log(`${W} Configure your AI provider and model${P}`),console.log(`${Mt}${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${P}`),console.log(),console.log(`${Mt} Choose your setup:${P}`),console.log(),console.log(` ${i0}${Mt}1${P}. ${Mt}Hablas Integrated Engine${P} ${ft}(instant \u2014 no setup needed)${P}`),console.log(` ${W}Pre-configured cloud AI, ready to use immediately${P}`),console.log(),console.log(` ${Ne}${Mt}2${P}. ${Mt}Custom Provider${P} ${W}(bring your own API key)${P}`),console.log(` ${W}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${P}`),console.log(),(await fe(e,` ${W}Your choice (1-2):${P} `)).trim()){case"1":{n.provider=Lt.provider,n.apiUrl=Lt.apiUrl,n.apiKey=o0(),n.model=Lt.model,at(n),ze({name:Lt.name,apiUrl:Lt.apiUrl,apiKey:n.apiKey,models:["stepfun-ai/step-3.7-flash","nvidia/llama-3.3-70b-instruct","deepseek-ai/deepseek-r1"],defaultModel:Lt.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Hablas Integrated Engine activated!${P}`),console.log(`${W} Model: ${Lt.model}${P}`),console.log(`${W} API: ${Lt.apiUrl}${P}`),console.log(`${W} No API key needed \u2014 everything is pre-configured.${P}`);break}case"2":{switch(console.log(),console.log(`${W} Select your provider:${P}`),console.log(` ${Ne}a${P}. Ollama (local, free, private)`),console.log(` ${Ne}b${P}. OpenAI API`),console.log(` ${Ne}c${P}. Groq (fast, free tier)`),console.log(` ${Ne}d${P}. OpenRouter (many models)`),console.log(` ${Ne}e${P}. Together AI`),console.log(` ${Ne}f${P}. DeepSeek`),console.log(` ${Ne}g${P}. Custom OpenAI-compatible API`),console.log(` ${Ne}h${P}. NVIDIA NIM (powerful cloud models)`),console.log(),(await fe(e,` ${W}Your choice (a-h):${P} `)).trim().toLowerCase()){case"a":{n.provider="ollama";let r=await fe(e,` ${W}Ollama host [http://localhost:11434]:${P} `);r.trim()&&(n.ollamaHost=r.trim());let i=await fe(e,` ${W}Model [qwen2.5-coder:7b]:${P} `);i.trim()&&(n.model=i.trim()),at(n),console.log(),console.log(`${ft} \u2713 Configured for Ollama${P}`),console.log(`${W} Model: ${n.model}${P}`),console.log(`${W} Host: ${n.ollamaHost}${P}`),console.log(`${W} Make sure Ollama is running: ollama serve${P}`);break}case"b":{let r=await fe(e,` ${W}OpenAI API Key (sk-...):${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`);break}let i=await fe(e,` ${W}Model [gpt-4o]:${P} `);n.provider="custom",n.apiUrl="https://api.openai.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"gpt-4o",at(n),ze({name:"OpenAI",apiUrl:"https://api.openai.com/v1",apiKey:r.trim(),models:["gpt-4o","gpt-4o-mini","gpt-4-turbo","o1","o3-mini"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for OpenAI${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"c":{let r=await fe(e,` ${W}Groq API Key (gsk_...):${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`);break}let i=await fe(e,` ${W}Model [llama-3.3-70b-versatile]:${P} `);n.provider="custom",n.apiUrl="https://api.groq.com/openai/v1",n.apiKey=r.trim(),n.model=i.trim()||"llama-3.3-70b-versatile",at(n),ze({name:"Groq",apiUrl:"https://api.groq.com/openai/v1",apiKey:r.trim(),models:["llama-3.3-70b-versatile","llama-3.1-70b-versatile","mixtral-8x7b-32768","gemma2-9b-it"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for Groq${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"d":{let r=await fe(e,` ${W}OpenRouter API Key (sk-or-...):${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`);break}let i=await fe(e,` ${W}Model [anthropic/claude-3.5-sonnet]:${P} `);n.provider="custom",n.apiUrl="https://openrouter.ai/api/v1",n.apiKey=r.trim(),n.model=i.trim()||"anthropic/claude-3.5-sonnet",at(n),ze({name:"OpenRouter",apiUrl:"https://openrouter.ai/api/v1",apiKey:r.trim(),models:["openai/gpt-4o","anthropic/claude-3.5-sonnet","google/gemini-2.0-flash-001","deepseek/deepseek-r1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for OpenRouter${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"e":{let r=await fe(e,` ${W}Together API Key:${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`);break}let i=await fe(e,` ${W}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${P} `);n.provider="custom",n.apiUrl="https://api.together.xyz/v1",n.apiKey=r.trim(),n.model=i.trim()||"meta-llama/Llama-3.3-70B-Instruct-Turbo",at(n),ze({name:"Together",apiUrl:"https://api.together.xyz/v1",apiKey:r.trim(),models:["meta-llama/Llama-3.3-70B-Instruct-Turbo","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for Together AI${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"f":{let r=await fe(e,` ${W}DeepSeek API Key:${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`);break}let i=await fe(e,` ${W}Model [deepseek-chat]:${P} `);n.provider="custom",n.apiUrl="https://api.deepseek.com/v1",n.apiKey=r.trim(),n.model=i.trim()||"deepseek-chat",at(n),ze({name:"DeepSeek",apiUrl:"https://api.deepseek.com/v1",apiKey:r.trim(),models:["deepseek-chat","deepseek-coder","deepseek-reasoner"],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for DeepSeek${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"g":{let r=await fe(e,` ${W}Provider name:${P} `);if(!r.trim()){console.log(`${pt} \u26A0 Cancelled${P}`);break}let i=await fe(e,` ${W}API base URL:${P} `);if(!i.trim()){console.log(`${pt} \u26A0 URL is required \u2014 cancelled${P}`);break}let o=await fe(e,` ${W}API Key (leave empty if none):${P} `),a=await fe(e,` ${W}Default model ID:${P} `);n.provider="custom",n.apiUrl=i.trim(),n.apiKey=o.trim(),n.model=a.trim()||"default",at(n),ze({name:r.trim(),apiUrl:i.trim(),apiKey:o.trim(),models:[n.model],defaultModel:n.model,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for ${r.trim()}${P}`),console.log(`${W} URL: ${i.trim()}${P}`),console.log(`${W} Model: ${n.model}${P}`);break}case"h":{let r=await fe(e,` ${W}NVIDIA API Key (nvapi-...):${P} `);if(!r.trim()){console.log(`${pt} \u26A0 No key provided \u2014 cancelled${P}`),console.log(`${W} Get your key at: https://build.nvidia.com/${P}`);break}let{NVIDIA_PROVIDER:i}=await Promise.resolve().then(()=>(kn(),Vl));console.log(),console.log(`${W} Available NVIDIA models:${P}`),i.models.forEach((c,d)=>{console.log(` ${Ne}${d+1}${P}. ${c}`)}),console.log();let o=await fe(e,` ${W}Model number [1]:${P} `),a=parseInt(o.trim())-1,l=i.models[a]||i.defaultModel;n.provider="nvidia",n.apiUrl=i.apiUrl,n.apiKey=r.trim(),n.model=l,at(n),ze({name:"NVIDIA",apiUrl:i.apiUrl,apiKey:r.trim(),models:i.models,defaultModel:l,addedAt:new Date().toISOString()}),console.log(),console.log(`${ft} \u2713 Configured for NVIDIA NIM${P}`),console.log(`${W} Model: ${l}${P}`),console.log(`${W} API: ${i.apiUrl}${P}`);break}default:console.log(`${pt} \u26A0 Invalid choice${P}`)}break}default:console.log(`${pt} \u26A0 Invalid choice \u2014 please select 1 or 2${P}`)}console.log(),console.log(`${W} Run 'hablas' to start chatting!${P}`),console.log(),e.close()}var wg,Ne,ft,pt,W,Mt,P,i0,Lt,Sg=N(()=>{"use strict";wg=O(require("readline"));Ls();ri();Ne="\x1B[36m",ft="\x1B[32m",pt="\x1B[33m",W="\x1B[2m",Mt="\x1B[1m",P="\x1B[0m",i0="\x1B[35m";Lt={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"}});var c0={};Pe(c0,{CLI_VERSION:()=>ls});module.exports=Og(c0);var Wl=O(ql(),1),{program:b0,createCommand:v0,createArgument:w0,createOption:x0,CommanderError:S0,InvalidArgumentError:_0,InvalidOptionArgumentError:A0,Command:Gl,Argument:k0,Option:$0,Help:E0}=Wl.default;wt();Ls();Pa();var _g=O(require("fs")),Ag=O(require("path"));function l0(){try{let n=Ag.resolve(__dirname,"..","package.json");return JSON.parse(_g.readFileSync(n,"utf-8")).version||"0.0.0"}catch{return"0.0.0"}}var ls=l0(),te=new Gl;te.name("hablas").description(`hablas CLI v${ls} by Abdulmoin Hablas \u2014 Multi-agent AI development system. Local-first via Ollama, NVIDIA NIM, or any OpenAI-compatible API.`).version(ls).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 (OpenAI-compatible)").option("--api-key <key>","API key for custom/nvidia provider").option("--auto","Auto mode \u2014 skip all tool confirmations").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--theme <name>","UI theme: dark | light | galaxy | ocean | forest").option("--dashboard","Launch TUI dashboard mode").option("--team","Enable hybrid cooperative sync mode with teammates").option("--user <name>","Teammate username for coordination").option("--team-key <password>","Teammate password/key for secure connection encryption").option("--setup","Run first-time setup wizard");te.command("create <description>").description("Generate a full project from a description").option("--stack <stack>","Tech stack preference").option("--with-tests","Include test generation").option("--with-docker","Include Docker setup").action(async(n,e)=>{let t=te.opts(),s=Ke({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});t.auto&&(s.autoMode=!0);let r=At(s),{runSingleCommand:i}=await Promise.resolve().then(()=>(wt(),Tt)),o=`Generate a complete project: ${n}${e.stack?` using ${e.stack}`:""}${e.withTests?" with comprehensive tests":""}${e.withDocker?" with Docker setup":""}. Create all necessary files.`;await i(o,s,r)});te.command("commit").description("Generate a smart commit message from staged changes").action(async()=>{let n=te.opts(),e=Ke({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),t=At(e),{getGitStatus:s,getDetailedDiff:r,generateCommitPrompt:i}=await Promise.resolve().then(()=>(tn(),On)),o=e.workingDirectory||process.cwd(),a=await s(o);if(!a||a.staged.length===0){console.log(" \u26A0 No staged changes. Use `git add` first.");return}let l=await r(o),c=i(l,a.staged),{runSingleCommand:d}=await Promise.resolve().then(()=>(wt(),Tt));await d(c,e,t)});te.command("pr").description("Generate a PR description from branch commits").option("--base <branch>","Base branch","main").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=At(t),{getGitStatus:r,getRecentCommits:i,generatePRPrompt:o}=await Promise.resolve().then(()=>(tn(),On)),a=t.workingDirectory||process.cwd(),l=await r(a),c=await i(a,20),d=o(c,n.base,l?.branch||"feature"),{runSingleCommand:f}=await Promise.resolve().then(()=>(wt(),Tt));await f(d,t,s)});te.command("changelog").description("Generate changelog from recent commits").option("--version <ver>","Version number",ls).option("-n, --count <n>","Number of commits to include","30").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),s=At(t),{getRecentCommits:r,generateChangelogPrompt:i}=await Promise.resolve().then(()=>(tn(),On)),o=t.workingDirectory||process.cwd(),a=await r(o,parseInt(n.count)),l=i(a,n.version),{runSingleCommand:c}=await Promise.resolve().then(()=>(wt(),Tt));await c(l,t,s)});te.command("security").description("Run security scan on the project").option("--fix","Auto-fix issues where possible").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{runSecurityScan:s,formatScanResults:r}=await Promise.resolve().then(()=>(Ci(),Tc)),i=t.workingDirectory||process.cwd();console.log(`
|
|
1086
933
|
\u{1F512} Running security scan...
|
|
1087
|
-
`);let o=s(i);console.log(r(o))});
|
|
934
|
+
`);let o=s(i);console.log(r(o))});te.command("stats").description("Show developer analytics and usage statistics").action(async()=>{let{loadStats:n,formatStats:e}=await Promise.resolve().then(()=>(Rn(),ki)),t=n();console.log(e(t))});te.command("team").description("Manage team configuration").option("--init <name>","Initialize team config").option("--add <email>","Add team member").option("--share","Share current session").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey}),{loadTeamConfig:s,initTeamConfig:r,addTeamMember:i,saveTeamConfig:o,formatTeamConfig:a}=await Promise.resolve().then(()=>(pg(),fg)),l=t.workingDirectory||process.cwd();if(n.init)r(l,n.init),console.log(`
|
|
1088
935
|
\u2713 Team "${n.init}" initialized.`),console.log(` Config saved to: .hablas/team.json
|
|
1089
|
-
`);else if(n.add){let
|
|
936
|
+
`);else if(n.add){let c=s(l);if(!c){console.log(" \u26A0 No team config found. Run `hablas team --init <name>` first.");return}let d=i(c,n.add.split("@")[0],n.add);o(l,d),console.log(` \u2713 Added ${n.add} to team.`)}else{let c=s(l);if(!c){console.log(" No team config found. Run `hablas team --init <name>` to create one.");return}console.log(a(c))}});te.command("info").description("Show workspace information and detected configuration").action(async()=>{let n=te.opts(),e=Ke({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{scanWorkspace:t,formatWorkspaceInfo:s}=await Promise.resolve().then(()=>(Oi(),Dc)),r=e.workingDirectory||process.cwd();console.log(`
|
|
1090
937
|
\u25C6 Workspace Information
|
|
1091
|
-
`);let i=t(r);console.log(s(i)),console.log("")});
|
|
1092
|
-
\u25C6 Hablas API Server v${
|
|
938
|
+
`);let i=t(r);console.log(s(i)),console.log("")});te.command("api").description("Start the REST API server").option("--port <port>","Port number","8080").option("--key <key>","API key for authentication").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});t.api.enabled=!0,t.api.port=parseInt(n.port),n.key&&(t.api.apiKey=n.key);let{startApiServer:s}=await Promise.resolve().then(()=>(vg(),bg));console.log(`
|
|
939
|
+
\u25C6 Hablas API Server v${ls}`),console.log(" \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"),console.log(` Starting on port ${t.api.port}...`);try{await s(t),console.log(` \u2713 API server running at http://${t.api.host}:${t.api.port}`),console.log(" Endpoints:"),console.log(" GET /api/v1/health \u2014 Health check"),console.log(" GET /api/v1/agents \u2014 List agents"),console.log(" GET /api/v1/models \u2014 List models"),console.log(" POST /api/v1/chat \u2014 Send message"),console.log(" POST /api/v1/plan \u2014 Generate plan"),console.log(" POST /api/v1/execute \u2014 Execute command"),console.log(" GET /api/v1/stats \u2014 Usage stats"),console.log(`
|
|
1093
940
|
Press Ctrl+C to stop.
|
|
1094
|
-
`)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});
|
|
941
|
+
`)}catch(r){console.error(` \u2717 Failed to start API server: ${r}`)}});te.command("run <prompt>").description("Run a single command non-interactively").action(async n=>{let e=te.opts(),t=Ke({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(t.autoMode=!0),e.timeout&&(t.timeout=parseInt(e.timeout,10));let s=At(t),{runSingleCommand:r}=await Promise.resolve().then(()=>(wt(),Tt));await r(n,t,s)});te.command("doctor").description("Run system diagnostics").action(async()=>{let n=te.opts(),e=Ke({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey}),{runDiagnostics:t,renderDiagnostics:s}=await Promise.resolve().then(()=>(mi(),bc)),r=await t({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(s(r))});te.command("plugins").description("Manage plugins").option("--enable <name>","Enable a plugin").option("--disable <name>","Disable a plugin").option("--search <query>","Search plugin marketplace").option("--install <name>","Install a plugin from marketplace").action(async n=>{let{enablePlugin:e,disablePlugin:t,renderPlugins:s,ensurePluginsDir:r}=await Promise.resolve().then(()=>(di(),mc));r(),n.enable?(e(n.enable),console.log(` \u2713 Plugin "${n.enable}" enabled`)):n.disable?(t(n.disable),console.log(` \u26A0 Plugin "${n.disable}" disabled`)):n.search?(console.log(`
|
|
1095
942
|
\u{1F50D} Searching marketplace for "${n.search}"...`),console.log(" (Marketplace: https://registry.hablas.dev/plugins)"),console.log(`
|
|
1096
943
|
Available plugins:`),console.log(" hablas-docker \u2014 Docker integration"),console.log(" hablas-aws \u2014 AWS toolkit"),console.log(" hablas-firebase \u2014 Firebase integration"),console.log(" hablas-supabase \u2014 Supabase toolkit"),console.log(" hablas-stripe \u2014 Stripe payment integration"),console.log(`
|
|
1097
944
|
Install: hablas plugins --install <name>
|
|
@@ -1101,7 +948,7 @@ ${Oe}`),await Gg(n,t);continue}}else M.addUserMessage(Q);Y=new AbortController,S
|
|
|
1101
948
|
\u25C6 Installed Plugins
|
|
1102
949
|
`),console.log(s()),console.log(`
|
|
1103
950
|
Plugins directory: ~/.hablas/plugins/`),console.log(" Search: hablas plugins --search <query>"),console.log(" Install: hablas plugins --install <name>"),console.log(" Enable: hablas plugins --enable <name>"),console.log(` Disable: hablas plugins --disable <name>
|
|
1104
|
-
`))});
|
|
951
|
+
`))});te.action(async()=>{let n=te.opts(),e=Ke({model:n.model,host:n.host,project:n.project,provider:n.provider,apiUrl:n.apiUrl,apiKey:n.apiKey,team:n.team,user:n.user,teamKey:n.teamKey});if(n.auto&&(e.autoMode=!0),n.timeout&&(e.timeout=parseInt(n.timeout,10)),n.theme&&(e.ui.theme=n.theme),n.dashboard&&(e.ui.dashboard=!0),n.setup){let{runSetupWizard:s}=await Promise.resolve().then(()=>(Sg(),xg));await s(e);return}let t=At(e);await Ta(e,t)});te.parse();0&&(module.exports={CLI_VERSION});
|
|
1105
952
|
/*! Bundled license information:
|
|
1106
953
|
|
|
1107
954
|
normalize-path/index.js:
|