hablas-ai 2.5.6 → 2.5.7

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.
Files changed (2) hide show
  1. package/dist/index.js +143 -143
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,149 +1,149 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var iu=Object.create;var si=Object.defineProperty;var ou=Object.getOwnPropertyDescriptor;var au=Object.getOwnPropertyNames;var lu=Object.getPrototypeOf,cu=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var uu=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of au(e))!cu.call(t,n)&&n!==r&&si(t,n,{get:()=>e[n],enumerable:!(s=ou(e,n))||s.enumerable});return t};var k=(t,e,r)=>(r=t!=null?iu(lu(t)):{},uu(e||!t||!t.__esModule?si(r,"default",{value:t,enumerable:!0}):r,t));var Pt=P(is=>{var ar=class extends Error{constructor(e,r,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},ns=class extends ar{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};is.CommanderError=ar;is.InvalidArgumentError=ns});var lr=P(as=>{var{InvalidArgumentError:xu}=Pt(),os=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new xu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Su(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}as.Argument=os;as.humanReadableArgName=Su});var cs=P(vi=>{var{humanReadableArgName:vu}=lr(),ls=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&r.push(s),this.sortSubcommands&&r.sort((n,i)=>n.name().localeCompare(i.name())),r}compareOptions(e,r){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?r.push(s):s.long&&!i?r.push(e.createOption(s.long,s.description)):s.short&&!n&&r.push(e.createOption(s.short,s.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(s=>vu(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((s,n)=>Math.max(s,r.subcommandTerm(n).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((s,n)=>Math.max(s,r.argumentTerm(n).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,r){let s=r.padWidth(e,r),n=r.helpWidth||80,i=2,o=2;function a(f,m){if(m){let g=`${f.padEnd(s+o)}${m}`;return r.wrap(g,n-i,s+o)}return f}function l(f){return f.join(`
2
+ "use strict";var iu=Object.create;var ni=Object.defineProperty;var ou=Object.getOwnPropertyDescriptor;var au=Object.getOwnPropertyNames;var lu=Object.getPrototypeOf,cu=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var uu=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of au(e))!cu.call(t,n)&&n!==r&&ni(t,n,{get:()=>e[n],enumerable:!(s=ou(e,n))||s.enumerable});return t};var k=(t,e,r)=>(r=t!=null?iu(lu(t)):{},uu(e||!t||!t.__esModule?ni(r,"default",{value:t,enumerable:!0}):r,t));var Mt=P(as=>{var lr=class extends Error{constructor(e,r,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},os=class extends lr{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};as.CommanderError=lr;as.InvalidArgumentError=os});var cr=P(cs=>{var{InvalidArgumentError:xu}=Mt(),ls=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new xu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Su(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}cs.Argument=ls;cs.humanReadableArgName=Su});var fs=P(_i=>{var{humanReadableArgName:vu}=cr(),us=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(n=>!n._hidden),s=e._getHelpCommand();return s&&!s._hidden&&r.push(s),this.sortSubcommands&&r.sort((n,i)=>n.name().localeCompare(i.name())),r}compareOptions(e,r){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(e).localeCompare(s(r))}visibleOptions(e){let r=e.options.filter(n=>!n.hidden),s=e._getHelpOption();if(s&&!s.hidden){let n=s.short&&e._findOption(s.short),i=s.long&&e._findOption(s.long);!n&&!i?r.push(s):s.long&&!i?r.push(e.createOption(s.long,s.description)):s.short&&!n&&r.push(e.createOption(s.short,s.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let s=e.parent;s;s=s.parent){let n=s.options.filter(i=>!i.hidden);r.push(...n)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(s=>vu(s)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((s,n)=>Math.max(s,r.subcommandTerm(n).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((s,n)=>Math.max(s,r.optionTerm(n).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((s,n)=>Math.max(s,r.argumentTerm(n).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let s="";for(let n=e.parent;n;n=n.parent)s=n.name()+" "+s;return s+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let s=`(${r.join(", ")})`;return e.description?`${e.description} ${s}`:s}return e.description}formatHelp(e,r){let s=r.padWidth(e,r),n=r.helpWidth||80,i=2,o=2;function a(f,m){if(m){let g=`${f.padEnd(s+o)}${m}`;return r.wrap(g,n-i,s+o)}return f}function l(f){return f.join(`
3
3
  `).replace(/^/gm," ".repeat(i))}let c=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(c=c.concat([r.wrap(u,n,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let p=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(p.length>0&&(c=c.concat(["Options:",l(p),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));f.length>0&&(c=c.concat(["Global Options:",l(f),""]))}let h=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return h.length>0&&(c=c.concat(["Commands:",l(h),""])),c.join(`
4
4
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,s,n=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-s;if(a<n)return e;let l=e.slice(0,s),c=e.slice(s).replace(`\r
5
5
  `,`
6
6
  `),u=" ".repeat(s),p="\\s\u200B",h=new RegExp(`
7
7
  |.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),f=c.match(h)||[];return l+f.map((m,g)=>m===`
8
8
  `?"":(g>0?u:"")+m.trimEnd()).join(`
9
- `)}};vi.Help=ls});var ps=P(ds=>{var{InvalidArgumentError:_u}=Pt(),us=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Tu(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new _u(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ku(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},fs=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,r){let s=r.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return r.negate===(i===e)}};function ku(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Tu(t){let e,r,s=t.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),r=s.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}ds.Option=us;ds.DualOptions=fs});var ki=P(_i=>{function Cu(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let s=0;s<=t.length;s++)r[s]=[s];for(let s=0;s<=e.length;s++)r[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=t.length;n++){let i=1;t[n-1]===e[s-1]?i=0:i=1,r[n][s]=Math.min(r[n-1][s]+1,r[n][s-1]+1,r[n-1][s-1]+i),n>1&&s>1&&t[n-1]===e[s-2]&&t[n-2]===e[s-1]&&(r[n][s]=Math.min(r[n][s],r[n-2][s-2]+1))}return r[t.length][e.length]}function $u(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Cu(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),r&&(s=s.map(o=>`--${o}`)),s.length>1?`
9
+ `)}};_i.Help=us});var ms=P(hs=>{var{InvalidArgumentError:_u}=Mt(),ds=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let s=Tu(e);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,s)=>{if(!this.argChoices.includes(r))throw new _u(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,s):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ku(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ps=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(e,r){let s=r.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,i=n!==void 0?n:!1;return r.negate===(i===e)}};function ku(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function Tu(t){let e,r,s=t.split(/[ |,]+/);return s.length>1&&!/^[[<]/.test(s[1])&&(e=s.shift()),r=s.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}hs.Option=ds;hs.DualOptions=ps});var Ti=P(ki=>{function Cu(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let s=0;s<=t.length;s++)r[s]=[s];for(let s=0;s<=e.length;s++)r[0][s]=s;for(let s=1;s<=e.length;s++)for(let n=1;n<=t.length;n++){let i=1;t[n-1]===e[s-1]?i=0:i=1,r[n][s]=Math.min(r[n-1][s]+1,r[n][s-1]+1,r[n-1][s-1]+i),n>1&&s>1&&t[n-1]===e[s-2]&&t[n-2]===e[s-1]&&(r[n][s]=Math.min(r[n][s],r[n-2][s-2]+1))}return r[t.length][e.length]}function $u(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let s=[],n=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=Cu(t,o),l=Math.max(t.length,o.length);(l-a)/l>i&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),r&&(s=s.map(o=>`--${o}`)),s.length>1?`
10
10
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
11
- (Did you mean ${s[0]}?)`:""}_i.suggestSimilar=$u});var Ai=P(Ei=>{var Eu=require("node:events").EventEmitter,hs=require("node:child_process"),Oe=require("node:path"),ms=require("node:fs"),W=require("node:process"),{Argument:Au,humanReadableArgName:Ou}=lr(),{CommanderError:gs}=Pt(),{Help:Ru}=cs(),{Option:Ti,DualOptions:Iu}=ps(),{suggestSimilar:Ci}=ki(),ys=class t extends Eu{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>W.stdout.write(r),writeErr:r=>W.stderr.write(r),getOutHelpWidth:()=>W.stdout.isTTY?W.stdout.columns:void 0,getErrHelpWidth:()=>W.stderr.isTTY?W.stderr.columns:void 0,outputError:(r,s)=>s(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,s){let n=r,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Ru,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
- - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Au(e,r)}argument(e,r,s,n){let i=this.createArgument(e,r);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,n]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
- Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,s){this._exitCallback&&this._exitCallback(new gs(e,r,s)),W.exit(e)}action(e){let r=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Ti(e,r)}_callParseArg(e,r,s,n){try{return e.parseArg(r,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
14
- - already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=n=>[n.name()].concat(n.aliases()),s=r(e).find(n=>this._findCommand(n));if(s){let n=r(this._findCommand(s)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,r,s,n,i){if(typeof r=="object"&&r instanceof Ti)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,s);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,r,s,n){return this._optionEx({},e,r,s,n)}requiredOption(e,r,s,n){return this._optionEx({mandatory:!0},e,r,s,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,s){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(r=s.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){W.versions?.electron&&(r.from="electron");let n=W.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(r.from="eval")}e===void 0&&(e=W.argv),this.rawArgs=e.slice();let s;switch(r.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":W.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,r){let s=this._prepareUserArgs(e,r);return this._parseCommand([],s),this}async parseAsync(e,r){let s=this._prepareUserArgs(e,r);return await this._parseCommand([],s),this}_executeSubCommand(e,r){r=r.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let p=Oe.resolve(u,d);if(ms.existsSync(p))return p;if(n.includes(Oe.extname(d)))return;let h=n.find(f=>ms.existsSync(`${p}${f}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=ms.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Oe.resolve(Oe.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Oe.basename(this._scriptPath,Oe.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}s=n.includes(Oe.extname(o));let l;W.platform!=="win32"?s?(r.unshift(o),r=$i(W.execArgv).concat(r),l=hs.spawn(W.argv[0],r,{stdio:"inherit"})):l=hs.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=$i(W.execArgv).concat(r),l=hs.spawn(W.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{W.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new gs(u,"commander.executeSubCommandAsync","(close)")):W.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${o}' does not exist
11
+ (Did you mean ${s[0]}?)`:""}ki.suggestSimilar=$u});var Oi=P(Ei=>{var Au=require("node:events").EventEmitter,gs=require("node:child_process"),Re=require("node:path"),ys=require("node:fs"),W=require("node:process"),{Argument:Eu,humanReadableArgName:Ou}=cr(),{CommanderError:ws}=Mt(),{Help:Ru}=fs(),{Option:Ci,DualOptions:Iu}=ms(),{suggestSimilar:$i}=Ti(),bs=class t extends Au{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>W.stdout.write(r),writeErr:r=>W.stderr.write(r),getOutHelpWidth:()=>W.stdout.isTTY?W.stdout.columns:void 0,getErrHelpWidth:()=>W.stderr.isTTY?W.stderr.columns:void 0,outputError:(r,s)=>s(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,s){let n=r,i=s;typeof n=="object"&&n!==null&&(i=n,n=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),i.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(i.noHelp||i.hidden),l._executableFile=i.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new t(e)}createHelp(){return Object.assign(new Ru,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,r){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
12
+ - specify the name in Command constructor or using .name()`);return r=r||{},r.isDefault&&(this._defaultCommandName=e._name),(r.noHelp||r.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,r){return new Eu(e,r)}argument(e,r,s,n){let i=this.createArgument(e,r);return typeof s=="function"?i.default(n).argParser(s):i.default(s),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,s,n]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let s=["preSubcommand","preAction","postAction"];if(!s.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
13
+ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,s){this._exitCallback&&this._exitCallback(new ws(e,r,s)),W.exit(e)}action(e){let r=s=>{let n=this.registeredArguments.length,i=s.slice(0,n);return this._storeOptionsAsProperties?i[n]=this:i[n]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new Ci(e,r)}_callParseArg(e,r,s,n){try{return e.parseArg(r,s)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${n} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let s=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
14
+ - already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=n=>[n.name()].concat(n.aliases()),s=r(e).find(n=>this._findCommand(n));if(s){let n=r(this._findCommand(s)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),s=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(s,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(s,e.defaultValue,"default");let n=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let l=this.getOptionValue(s);i!==null&&e.parseArg?i=this._callParseArg(e,i,l,o):i!==null&&e.variadic&&(i=e._concatValue(i,l)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(s,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;n(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;n(i,o,"env")}),this}_optionEx(e,r,s,n,i){if(typeof r=="object"&&r instanceof Ci)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,s);if(o.makeOptionMandatory(!!e.mandatory),typeof n=="function")o.default(i).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,c)=>{let u=a.exec(l);return u?u[0]:c},o.default(i).argParser(n)}else o.default(n);return this.addOption(o)}option(e,r,s,n){return this._optionEx({},e,r,s,n)}requiredOption(e,r,s,n){return this._optionEx({mandatory:!0},e,r,s,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,s){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=s,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(e)!==void 0&&(r=s.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){W.versions?.electron&&(r.from="electron");let n=W.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(r.from="eval")}e===void 0&&(e=W.argv),this.rawArgs=e.slice();let s;switch(r.from){case void 0:case"node":this._scriptPath=e[1],s=e.slice(2);break;case"electron":W.defaultApp?(this._scriptPath=e[1],s=e.slice(2)):s=e.slice(1);break;case"user":s=e.slice(0);break;case"eval":s=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(e,r){let s=this._prepareUserArgs(e,r);return this._parseCommand([],s),this}async parseAsync(e,r){let s=this._prepareUserArgs(e,r);return await this._parseCommand([],s),this}_executeSubCommand(e,r){r=r.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let p=Re.resolve(u,d);if(ys.existsSync(p))return p;if(n.includes(Re.extname(d)))return;let h=n.find(f=>ys.existsSync(`${p}${f}`));if(h)return`${p}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=ys.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Re.resolve(Re.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Re.basename(this._scriptPath,Re.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}s=n.includes(Re.extname(o));let l;W.platform!=="win32"?s?(r.unshift(o),r=Ai(W.execArgv).concat(r),l=gs.spawn(W.argv[0],r,{stdio:"inherit"})):l=gs.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Ai(W.execArgv).concat(r),l=gs.spawn(W.execPath,r,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{W.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",u=>{u=u??1,c?c(new ws(u,"commander.executeSubCommandAsync","(close)")):W.exit(u)}),l.on("error",u=>{if(u.code==="ENOENT"){let d=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${o}' does not exist
15
15
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
16
16
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
17
- - ${d}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)W.exit(1);else{let d=new gs(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,s){let n=this._findCommand(e);n||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,r.concat(s));else return n._parseCommand(r,s)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),r[n]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),r==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,r,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,r))}),n}_parseCommand(e,r){let s=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),r=s.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],s=[],n=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){n===s&&n.push(l),n.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}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("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&s.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){n.push(l),i.length>0&&n.push(...i);break}n.push(l)}return{operands:r,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let s=0;s<r;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
17
+ - ${d}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${o}' not executable`);if(!c)W.exit(1);else{let d=new ws(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,r,s){let n=this._findCommand(e);n||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,n,"preSubcommand"),i=this._chainOrCall(i,()=>{if(n._executableHandler)this._executeSubCommand(n,r.concat(s));else return n._parseCommand(r,s)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(s,n,i)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((s,n)=>{let i=s.defaultValue;s.variadic?n<this.args.length?(i=this.args.slice(n),s.parseArg&&(i=i.reduce((o,a)=>e(s,a,o),s.defaultValue))):i===void 0&&(i=[]):n<this.args.length&&(i=this.args[n],s.parseArg&&(i=e(s,i,s.defaultValue))),r[n]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let s=e,n=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{n.push({hookedCommand:i,callback:o})})}),r==="postAction"&&n.reverse(),n.forEach(i=>{s=this._chainOrCall(s,()=>i.callback(i.hookedCommand,this))}),s}_chainOrCallSubCommandHook(e,r,s){let n=e;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(i=>{n=this._chainOrCall(n,()=>i(this,r))}),n}_parseCommand(e,r){let s=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(s.operands),r=s.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))n(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=e.find(i=>s.conflictsWith.includes(i.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],s=[],n=r,i=e.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;i.length;){let l=i.shift();if(l==="--"){n===s&&n.push(l),n.push(...i);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let c=this._findOption(l);if(c){if(c.required){let u=i.shift();u===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,u)}else if(c.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${c.name()}`,u)}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("="),u=this._findOption(l.slice(0,c));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,l.slice(c+1));continue}}if(o(l)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&s.length===0){if(this._findCommand(l)){r.push(l),i.length>0&&s.push(...i);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){r.push(l),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){s.push(l),i.length>0&&s.push(...i);break}}if(this._passThroughOptions){n.push(l),i.length>0&&n.push(...i);break}n.push(l)}return{operands:r,unknown:s}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let s=0;s<r;s++){let n=this.options[s].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
18
18
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
19
19
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
20
- `),this.outputHelp({error:!0}));let s=r||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in W.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,W.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Iu(this.options),r=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&r(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!r(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},n=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=Ci(e,n)}let s=`error: unknown option '${e}'${r}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,s=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),r=Ci(e,n)}let s=`error: unknown command '${e}'${r}`;this.error(s,{code:"commander.unknownCommand"})}version(e,r,s){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",s=s||"output the version number";let n=this.createOption(r,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
- `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(s=>Ou(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Oe.basename(e,Oe.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},s;return r.error?s=n=>this._outputConfiguration.writeErr(n):s=n=>this._outputConfiguration.writeOut(n),r.write=e.write||s,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let n=this.helpInformation(s);if(r&&(n=r(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=W.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
20
+ `),this.outputHelp({error:!0}));let s=r||{},n=s.exitCode||1,i=s.code||"commander.error";this._exit(n,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in W.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,W.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Iu(this.options),r=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&r(s.attributeName())&&e.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!r(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),c=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:u||o},n=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${n(e)} cannot be used with ${n(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);n=n.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=$i(e,n)}let s=`error: unknown option '${e}'${r}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,s=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${s} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(i=>{n.push(i.name()),i.alias()&&n.push(i.alias())}),r=$i(e,n)}let s=`error: unknown command '${e}'${r}`;this.error(s,{code:"commander.unknownCommand"})}version(e,r,s){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",s=s||"output the version number";let n=this.createOption(r,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
21
+ `),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(e);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(s=>Ou(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Re.basename(e,Re.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},s;return r.error?s=n=>this._outputConfiguration.writeErr(n):s=n=>this._outputConfiguration.writeOut(n),r.write=e.write||s,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let s=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let n=this.helpInformation(s);if(r&&(n=r(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",s))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=W.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let s=["beforeAll","before","after","afterAll"];if(!s.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${s.join("', '")}'`);let n=`${e}Help`;return this.on(n,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(n=>r.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function $i(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],s=i[3],n=i[4]),r&&n!=="0"?`${r}=${s}:${parseInt(n)+1}`:e})}Ei.Command=ys});var ji=P(le=>{var{Argument:Oi}=lr(),{Command:ws}=Ai(),{CommanderError:ju,InvalidArgumentError:Ri}=Pt(),{Help:Pu}=cs(),{Option:Ii}=ps();le.program=new ws;le.createCommand=t=>new ws(t);le.createOption=(t,e)=>new Ii(t,e);le.createArgument=(t,e)=>new Oi(t,e);le.Command=ws;le.Option=Ii;le.Argument=Oi;le.Help=Pu;le.CommanderError=ju;le.InvalidArgumentError=Ri;le.InvalidOptionArgumentError=Ri});var Ss=P((_w,Ui)=>{"use strict";var Mt=t=>t&&typeof t.message=="string",xs=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return Mt(r)?r:void 0}else return Mt(e)?e:void 0},Di=(t,e)=>{if(!Mt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
- causes have become circular...`;let s=xs(t);return s?(e.add(t),r+`
25
- caused by: `+Di(s,e)):r},Mu=t=>Di(t,new Set),Ni=(t,e,r)=>{if(!Mt(t))return"";let s=r?"":t.message||"";if(e.has(t))return s+": ...";let n=xs(t);if(n){e.add(t);let i=typeof t.cause=="function";return s+(i?"":": ")+Ni(n,e,i)}else return s},Fu=t=>Ni(t,new Set);Ui.exports={isErrorLike:Mt,getErrorCause:xs,stackWithCauses:Mu,messageWithCauses:Fu}});var vs=P((kw,Bi)=>{"use strict";var Lu=Symbol("circular-ref-tag"),cr=Symbol("pino-raw-err-ref"),qi=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[cr]},set:function(t){this[cr]=t}}});Object.defineProperty(qi,cr,{writable:!0,value:{}});Bi.exports={pinoErrProto:qi,pinoErrorSymbols:{seen:Lu,rawSymbol:cr}}});var Vi=P((Tw,Wi)=>{"use strict";Wi.exports=ks;var{messageWithCauses:Du,stackWithCauses:Nu,isErrorLike:Hi}=Ss(),{pinoErrProto:Uu,pinoErrorSymbols:qu}=vs(),{seen:_s}=qu,{toString:Bu}=Object.prototype;function ks(t){if(!Hi(t))return t;t[_s]=void 0;let e=Object.create(Uu);e.type=Bu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Du(t),e.stack=Nu(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>ks(r)));for(let r in t)if(e[r]===void 0){let s=t[r];Hi(s)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(s,_s)&&(e[r]=ks(s)):e[r]=s}return delete t[_s],e.raw=t,e}});var Ki=P((Cw,zi)=>{"use strict";zi.exports=fr;var{isErrorLike:Ts}=Ss(),{pinoErrProto:Hu,pinoErrorSymbols:Wu}=vs(),{seen:ur}=Wu,{toString:Vu}=Object.prototype;function fr(t){if(!Ts(t))return t;t[ur]=void 0;let e=Object.create(Hu);e.type=Vu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>fr(r))),Ts(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,ur)&&(e.cause=fr(t.cause));for(let r in t)if(e[r]===void 0){let s=t[r];Ts(s)?Object.prototype.hasOwnProperty.call(s,ur)||(e[r]=fr(s)):e[r]=s}return delete t[ur],e.raw=t,e}});var Xi=P(($w,Yi)=>{"use strict";Yi.exports={mapHttpRequest:zu,reqSerializer:Ji};var Cs=Symbol("pino-raw-req-ref"),Gi=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[Cs]},set:function(t){this[Cs]=t}}});Object.defineProperty(Gi,Cs,{writable:!0,value:{}});function Ji(t){let e=t.info||t.socket,r=Object.create(Gi);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let s=t.path;r.url=typeof s=="string"?s:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function zu(t){return{req:Ji(t)}}});var to=P((Ew,eo)=>{"use strict";eo.exports={mapHttpResponse:Ku,resSerializer:Zi};var $s=Symbol("pino-raw-res-ref"),Qi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[$s]},set:function(t){this[$s]=t}}});Object.defineProperty(Qi,$s,{writable:!0,value:{}});function Zi(t){let e=Object.create(Qi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Ku(t){return{res:Zi(t)}}});var As=P((Aw,ro)=>{"use strict";var Es=Vi(),Gu=Ki(),dr=Xi(),pr=to();ro.exports={err:Es,errWithCause:Gu,mapHttpRequest:dr.mapHttpRequest,mapHttpResponse:pr.mapHttpResponse,req:dr.reqSerializer,res:pr.resSerializer,wrapErrorSerializer:function(e){return e===Es?e:function(s){return e(Es(s))}},wrapRequestSerializer:function(e){return e===dr.reqSerializer?e:function(s){return e(dr.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===pr.resSerializer?e:function(s){return e(pr.resSerializer(s))}}}});var Os=P((Ow,so)=>{"use strict";function Ju(t,e){return e}so.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Ju;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let s=r.slice(2),n=[];for(let i of s)i&&n.push(i.getFileName());return n}});var co=P((Rw,lo)=>{"use strict";function Rs(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=Rs(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=Rs(t[r]));return e}return t}function no(t){let e=[],r="",s=!1,n=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!s&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),s=!0):a==="]"&&s?(e.push(r),r="",s=!1,n=!1):(a==='"'||a==="'")&&s?n?a===i?(n=!1,i=""):r+=a:(n=!0,i=a):r+=a}return r&&e.push(r),e}function io(t,e,r){let s=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=r;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=r)}else typeof s=="object"&&s!==null&&n in s&&Object.prototype.hasOwnProperty.call(s,n)&&(s[n]=r);return!0}function oo(t,e){let r=t;for(let n=0;n<e.length-1;n++){let i=e[n];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let n=0;n<r.length;n++)r[n]=void 0;else if(typeof r=="object"&&r!==null)for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&delete r[n]}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&delete r[s];return!0}var hr=Symbol("PATH_NOT_FOUND");function Yu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null||!(s in r))return hr;r=r[s]}return r}function Xu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null)return;r=r[s]}return r}function Qu(t,e,r,s=!1){for(let n of e){let i=no(n);if(i.includes("*"))ao(t,i,r,n,s);else if(s)oo(t,i);else{let o=Yu(t,i);if(o===hr)continue;let a=typeof r=="function"?r(o,i):r;io(t,i,a)}}}function ao(t,e,r,s,n=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(n)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(n){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else Zu(t,e,r,i,s,n)}function Zu(t,e,r,s,n,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)l[d]=p.toString(),c(u[p],d+1);else if(typeof u=="object"&&u!==null)for(let p in u)l[d]=p,c(u[p],d+1)}else if(d<o.length){let p=o[d];u&&typeof u=="object"&&u!==null&&p in u&&(l[d]=p,c(u[p],d+1))}else if(a.includes("*"))ao(u,a,typeof r=="function"?(h,f)=>{let m=[...l.slice(0,d),...f];return r(h,m)}:r,n,i);else if(i)oo(u,a);else{let p=typeof r=="function"?r(Xu(u,a),[...l.slice(0,d),...a]):r;io(u,a,p)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let p=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[p],l[d]=p}u!=null&&c(u,o.length)}}function ef(t){if(t.length===0)return null;let e=new Map;for(let r of t){let s=no(r),n=e;for(let i=0;i<s.length;i++){let o=s[i];n.has(o)||n.set(o,new Map),n=n.get(o)}}return e}function tf(t,e){if(!e)return t;function r(s,n,i=0){if(!n||n.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let c=l.toString();n.has(c)||n.has("*")?a[l]=r(s[l],n.get(c)||n.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(n.has(a)||n.has("*")?o[a]=r(s[a],n.get(a)||n.get("*")):o[a]=s[a]);return o}return r(t,e)}function rf(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,s="";for(let n=0;n<t.length;n++){let i=t[n];if((i==='"'||i==="'")&&e>0)r?i===s&&(r=!1,s=""):(r=!0,s=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function sf(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)rf(e)}function nf(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:s=JSON.stringify,strict:n=!0,remove:i=!1}=t;sf(e);let o=ef(e);return function(l){if(n&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let c=tf(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Qu(c,e,d,i),s===!1?(c.restore=function(){return Rs(u)},c):typeof s=="function"?s(c):JSON.stringify(c)}}lo.exports=nf});var dt=P((Iw,uo)=>{"use strict";var of=Symbol("pino.setLevel"),af=Symbol("pino.getLevel"),lf=Symbol("pino.levelVal"),cf=Symbol("pino.levelComp"),uf=Symbol("pino.useLevelLabels"),ff=Symbol("pino.useOnlyCustomLevels"),df=Symbol("pino.mixin"),pf=Symbol("pino.lsCache"),hf=Symbol("pino.chindings"),mf=Symbol("pino.asJson"),gf=Symbol("pino.write"),yf=Symbol("pino.redactFmt"),wf=Symbol("pino.time"),bf=Symbol("pino.timeSliceIndex"),xf=Symbol("pino.stream"),Sf=Symbol("pino.stringify"),vf=Symbol("pino.stringifySafe"),_f=Symbol("pino.stringifiers"),kf=Symbol("pino.end"),Tf=Symbol("pino.formatOpts"),Cf=Symbol("pino.messageKey"),$f=Symbol("pino.errorKey"),Ef=Symbol("pino.nestedKey"),Af=Symbol("pino.nestedKeyStr"),Of=Symbol("pino.mixinMergeStrategy"),Rf=Symbol("pino.msgPrefix"),If=Symbol("pino.wildcardFirst"),jf=Symbol.for("pino.serializers"),Pf=Symbol.for("pino.formatters"),Mf=Symbol.for("pino.hooks"),Ff=Symbol.for("pino.metadata");uo.exports={setLevelSym:of,getLevelSym:af,levelValSym:lf,levelCompSym:cf,useLevelLabelsSym:uf,mixinSym:df,lsCacheSym:pf,chindingsSym:hf,asJsonSym:mf,writeSym:gf,serializersSym:jf,redactFmtSym:yf,timeSym:wf,timeSliceIndexSym:bf,streamSym:xf,stringifySym:Sf,stringifySafeSym:vf,stringifiersSym:_f,endSym:kf,formatOptsSym:Tf,messageKeySym:Cf,errorKeySym:$f,nestedKeySym:Ef,wildcardFirstSym:If,needsMetadataGsym:Ff,useOnlyCustomLevelsSym:ff,formattersSym:Pf,hooksSym:Mf,nestedKeyStrSym:Af,mixinMergeStrategySym:Of,msgPrefixSym:Rf}});var js=P((jw,mo)=>{"use strict";var fo=co(),{redactFmtSym:Lf,wildcardFirstSym:mr}=dt(),Is=/[^.[\]]+|\[([^[\]]*?)\]/g,po="[Redacted]",ho=!1;function Df(t,e){let{paths:r,censor:s,remove:n}=Nf(t),i=r.reduce((l,c)=>{Is.lastIndex=0;let u=Is.exec(c),d=Is.exec(c),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=mr),d===null)return l[p]=null,l;if(l[p]===null)return l;let{index:h}=d,f=`${c.substr(h,c.length-1)}`;return l[p]=l[p]||[],p!==mr&&l[p].length===0&&l[p].push(...l[mr]||[]),p===mr&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(f)}),l[p].push(f),l},{}),o={[Lf]:fo({paths:r,censor:s,serialize:e,strict:ho,remove:n})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=u=>a(u,[c]);else{let u=typeof s=="function"?(d,p)=>s(d,[c,...p]):s;l[c]=fo({paths:i[c],censor:u,serialize:e,strict:ho,remove:n})}return l},o)}function Nf(t){if(Array.isArray(t))return t={paths:t,censor:po},t;let{paths:e,censor:r=po,remove:s}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(r=void 0),{paths:e,censor:r,remove:s}}mo.exports=Df});var wo=P((Pw,yo)=>{"use strict";var Uf=()=>"",qf=()=>`,"time":${Date.now()}`,Bf=()=>`,"time":${Math.round(Date.now()/1e3)}`,Hf=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Wf=1000000n,go=1000000000n,Vf=BigInt(Date.now())*Wf,zf=process.hrtime.bigint(),Kf=()=>{let t=process.hrtime.bigint()-zf,e=Vf+t,r=e/go,s=e%go,n=Number(r*1000n+s/1000000n),i=new Date(n),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${s.toString().padStart(9,"0")}Z"`};yo.exports={nullTime:Uf,epochTime:qf,unixTime:Bf,isoTime:Hf,isoTimeNano:Kf}});var xo=P((Mw,bo)=>{"use strict";function Gf(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}bo.exports=Jf;function Jf(t,e,r){var s=r&&r.stringify||Gf,n=1;if(typeof t=="object"&&t!==null){var i=e.length+n;if(i===1)return t;var o=new Array(i);o[0]=s(t);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",u=1-n,d=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(d=d>-1?d:0,t.charCodeAt(h+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<h&&(c+=t.slice(d,h)),c+=Number(e[u]),d=h+2,h++;break;case 105:if(u>=l||e[u]==null)break;d<h&&(c+=t.slice(d,h)),c+=Math.floor(Number(e[u])),d=h+2,h++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<h&&(c+=t.slice(d,h));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=h+2,h++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=h+2,h++;break}c+=s(e[u]),d=h+2,h++;break;case 115:if(u>=l)break;d<h&&(c+=t.slice(d,h)),c+=String(e[u]),d=h+2,h++;break;case 37:d<h&&(c+=t.slice(d,h)),c+="%",d=h+2,h++,u--;break}++u}++h}return d===-1?t:(d<p&&(c+=t.slice(d)),c)}});var Ms=P((Fw,Ps)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Ps.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let s=Date.now()+Number(e);for(;s>Date.now(););};Ps.exports=t}});var Eo=P((Lw,$o)=>{"use strict";var q=require("fs"),Yf=require("events"),Xf=require("util").inherits,So=require("path"),Ls=Ms(),Qf=require("assert"),gr=100,yr=Buffer.allocUnsafe(0),Zf=16*1024,vo="buffer",_o="utf8",[ed,td]=(process.versions.node||"0.0").split(".").map(Number),rd=ed>=22&&td>=7;function ko(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",n=e.mode;if(e.sync)try{e.mkdir&&q.mkdirSync(So.dirname(t),{recursive:!0});let i=q.openSync(t,s,n);r(null,i)}catch(i){throw r(i),i}else e.mkdir?q.mkdir(So.dirname(t),{recursive:!0},i=>{if(i)return r(i);q.open(t,s,n,r)}):q.open(t,s,n,r)}function we(t){if(!(this instanceof we))return new we(t);let{fd:e,dest:r,minLength:s,maxLength:n,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:p,mode:h}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=n||0,this.maxWrite=i||Zf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,m;if(p===vo)this._writingBuf=yr,this.write=id,this.flush=ad,this.flushSync=cd,this._actualWrite=fd,f=()=>q.writeSync(this.fd,this._writingBuf),m=()=>q.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===_o)this._writingBuf="",this.write=nd,this.flush=od,this.flushSync=ld,this._actualWrite=ud,f=()=>Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?q.write(this.fd,this._writingBuf,this.release):q.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${_o}" and "${vo}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")ko(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,y)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Ls(gr),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,gr);else this._writing=!1,this.emit("error",g);return}this.emit("write",y);let b=Fs(this._writingBuf,this._len,y);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=f(),_=Fs(this._writingBuf,this._len,S);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&q.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,wr(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(sd,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Fs(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function sd(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Xf(we,Yf);function To(t,e){return t.length===0?yr:t.length===1?t[0]:Buffer.concat(t,e)}function nd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,s=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(t):s[s.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function id(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||s[s.length-1]+t.length>this.maxWrite?(r.push([t]),s.push(t.length)):(r[r.length-1].push(t),s[s.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Co(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{q.fsync(this.fd,s=>{this._flushPending=!1,t(s)})}catch(s){t(s)}this.off("error",r)},r=s=>{this._flushPending=!1,t(s),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function od(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Co.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function ad(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&Co.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}we.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&q.close(e,r=>{if(r)return this.emit("error",r)})}),ko(this.file,this)};we.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():wr(this)))};function ld(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?q.writeSync(this.fd,t):q.writeSync(this.fd,t,"utf8"),r=Fs(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Ls(gr)}}try{q.fsyncSync(this.fd)}catch{}}function cd(){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=yr);let t=yr;for(;this._bufs.length||t.length;){t.length<=0&&(t=To(this._bufs[0],this._lens[0]));try{let e=q.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Ls(gr)}}}we.prototype.destroy=function(){this.destroyed||wr(this)};function ud(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else q.write(this.fd,this._writingBuf,t)}function fd(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:To(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=q.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else rd&&(this._writingBuf=Buffer.from(this._writingBuf)),q.write(this.fd,this._writingBuf,t)}function wr(t){if(t.fd===-1){t.once("ready",wr.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Qf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{q.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?q.close(t.fd,r):r()}function r(s){if(s){t.emit("error",s);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}we.SonicBoom=we;we.default=we;$o.exports=we});var Ds=P((Dw,jo)=>{"use strict";var be={exit:[],beforeExit:[]},Ao={exit:hd,beforeExit:md},pt;function dd(){pt===void 0&&(pt=new FinalizationRegistry(gd))}function pd(t){be[t].length>0||process.on(t,Ao[t])}function Oo(t){be[t].length>0||(process.removeListener(t,Ao[t]),be.exit.length===0&&be.beforeExit.length===0&&(pt=void 0))}function hd(){Ro("exit")}function md(){Ro("beforeExit")}function Ro(t){for(let e of be[t]){let r=e.deref(),s=e.fn;r!==void 0&&s(r,t)}be[t]=[]}function gd(t){for(let e of["exit","beforeExit"]){let r=be[e].indexOf(t);be[e].splice(r,r+1),Oo(e)}}function Io(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");pd(t);let s=new WeakRef(e);s.fn=r,dd(),pt.register(e,s),be[t].push(s)}function yd(t,e){Io("exit",t,e)}function wd(t,e){Io("beforeExit",t,e)}function bd(t){if(pt!==void 0){pt.unregister(t);for(let e of["exit","beforeExit"])be[e]=be[e].filter(r=>{let s=r.deref();return s&&s!==t}),Oo(e)}}jo.exports={register:yd,registerBeforeExit:wd,unregister:bd}});var Po=P((Nw,xd)=>{xd.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 Fo=P((Uw,Mo)=>{"use strict";function Sd(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(t,e);if(a===r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function vd(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(t,e)!==r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(u=>{if(u==="ok"){n(null,"ok");return}o()}):setImmediate(o)};o()}Mo.exports={wait:Sd,waitDiff:vd}});var Do=P((qw,Lo)=>{"use strict";Lo.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Yo=P((Bw,Jo)=>{"use strict";var{version:_d}=Po(),{EventEmitter:kd}=require("events"),{Worker:Td}=require("worker_threads"),{join:Cd}=require("path"),{pathToFileURL:$d}=require("url"),{wait:Ed}=Fo(),{WRITE_INDEX:Re,READ_INDEX:Xe,SEQ_INDEX:Ns}=Do(),Ad=require("buffer"),Od=require("assert"),v=Symbol("kImpl"),Rd=Ad.constants.MAX_STRING_LENGTH;function No(){}function Hs(t,e){Atomics.add(t[v].state,Ns,1),e(),Atomics.add(t[v].state,Ns,1),Atomics.notify(t[v].state,Ns)}function Uo(t){Hs(t,()=>{Atomics.store(t[v].state,Xe,0),Atomics.store(t[v].state,Re,0)})}var Ft=class{constructor(e){this._value=e}deref(){return this._value}},br=class{register(){}unregister(){}},Id=process.env.NODE_V8_COVERAGE?br:global.FinalizationRegistry||br,jd=process.env.NODE_V8_COVERAGE?Ft:global.WeakRef||Ft,qo=new Id(t=>{t.exited||t.terminate()});function Pd(t,e){let{filename:r,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Cd(__dirname,"lib","worker.js"),o=new Td(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:$d(r).href,dataBuf:t[v].dataBuf,stateBuf:t[v].stateBuf,workerData:{$context:{threadStreamVersion:_d},...s}}});return o.stream=new Ft(t),o.on("message",Md),o.on("exit",Wo),qo.register(t,o),o}function Bo(t){Od(!t[v].sync),t[v].needDrain&&(t[v].needDrain=!1,t.emit("drain"))}function Ho(t){for(;;){let e=Atomics.load(t[v].state,Re),r=t[v].data.length-e;if(r>0){if(t[v].bufLen===0){t[v].flushing=!1,t[v].ending?Ws(t):t[v].needDrain&&process.nextTick(Bo,t);return}Ko(t,r,No);continue}if(r===0){if(e===0&&t[v].bufLen===0)return;xr(t,()=>{t.destroyed||(Uo(t),Ho(t))});return}ue(t,new Error("overwritten"));return}}function Md(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new jd(e),xr(e,()=>{e[v].ready=!0,e.emit("ready")});break;case"ERROR":ue(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){ue(e,new Error("this should not happen: "+t.code));break}let r=e[v].flushCallbacks.get(t.id);r&&(e[v].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ue(e,new Error("this should not happen: "+t.code))}}function Wo(t){let e=this.stream.deref();e!==void 0&&(qo.unregister(e),e.worker.exited=!0,e.worker.off("exit",Wo),ue(e,t!==0?new Error("the worker thread exited"):null))}var qs=class extends kd{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[v]={},this[v].stateBuf=new SharedArrayBuffer(128),this[v].state=new Int32Array(this[v].stateBuf),this[v].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[v].data=Buffer.from(this[v].dataBuf),this[v].sync=e.sync||!1,this[v].ending=!1,this[v].ended=!1,this[v].needDrain=!1,this[v].destroyed=!1,this[v].flushing=!1,this[v].ready=!1,this[v].finished=!1,this[v].errored=null,this[v].closed=!1,this[v].buf=[],this[v].bufHead=0,this[v].bufLen=0,this[v].flushCallbacks=new Map,this[v].nextFlushId=0,this.worker=Pd(this,e),this.on("message",(r,s)=>{this.worker.postMessage(r,s)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[v].destroyed)return Bs(this,new Error("the worker has exited")),!1;if(this[v].ending)return Bs(this,new Error("the worker is ending")),!1;if(this[v].flushing&&this[v].bufLen+r.length>=Rd)try{Us(this),this[v].flushing=!0}catch(s){return ue(this,s),!1}if(this[v].buf.push(r),this[v].bufLen+=r.length,this[v].sync)try{return Us(this),!0}catch(s){return ue(this,s),!1}return this[v].flushing||(this[v].flushing=!0,setImmediate(Ho,this)),this[v].needDrain=this[v].data.length-this[v].bufLen-Atomics.load(this[v].state,Re)<=0,!this[v].needDrain}end(){this[v].destroyed||(this[v].ending=!0,Ws(this))}flush(e){e=typeof e=="function"?e:No,Vo(this,r=>{if(r){process.nextTick(e,r);return}zo(this,e)})}flushSync(){this[v].destroyed||(Us(this),Go(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[v].ready}get destroyed(){return this[v].destroyed}get closed(){return this[v].closed}get writable(){return!this[v].destroyed&&!this[v].ending}get writableEnded(){return this[v].ending}get writableFinished(){return this[v].finished}get writableNeedDrain(){return this[v].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[v].errored}};function Vo(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].sync&&(t[v].flushing||t[v].bufLen>0)){setImmediate(Vo,t,e);return}xr(t,e)}function xr(t,e){let r=Atomics.load(t[v].state,Re);Ed(t[v].state,Xe,r,1/0,(s,n)=>{if(s){ue(t,s),e(s);return}if(n!=="ok"){xr(t,e);return}e()})}function zo(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].ready){let s=()=>{i(),zo(t,e)},n=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",s),t.off("close",n)};t.once("ready",s),t.once("close",n);return}let r=++t[v].nextFlushId;t[v].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(s){t[v].flushCallbacks.delete(r),ue(t,s),process.nextTick(e,s)}}function Fd(t,e){let r=t[v].flushCallbacks;if(r.size===0)return;let s=e||new Error("the worker has exited");for(let n of r.values())process.nextTick(n,s);r.clear()}function Bs(t,e){setImmediate(()=>{t.emit("error",e)})}function ue(t,e){t[v].destroyed||(t[v].destroyed=!0,Fd(t,e),e&&(t[v].errored=e,Bs(t,e)),t.worker.exited?setImmediate(()=>{t[v].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[v].closed=!0,t.emit("close")}))}function Ko(t,e,r){let n=Atomics.load(t[v].state,Re),i=e;for(;i>0&&t[v].bufLen!==0;){let o=t[v].bufHead,a=t[v].buf[o];if(a.length<=i){a.copy(t[v].data,n),n+=a.length,i-=a.length,t[v].bufLen-=a.length,t[v].bufHead=o+1,t[v].bufHead===t[v].buf.length?(t[v].buf.length=0,t[v].bufHead=0):t[v].bufHead>=1024&&t[v].bufHead*2>=t[v].buf.length&&(t[v].buf.splice(0,t[v].bufHead),t[v].bufHead=0);continue}a.copy(t[v].data,n,0,i),t[v].buf[o]=a.subarray(i),t[v].bufLen-=i,n+=i,i=0}return Hs(t,()=>{Atomics.store(t[v].state,Re,n)}),r(),!0}function Ws(t){if(!(t[v].ended||!t[v].ending||t[v].flushing)){t[v].ended=!0;try{t.flushSync();let e=Atomics.load(t[v].state,Xe);Hs(t,()=>{Atomics.store(t[v].state,Re,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[v].state,Xe,e,1e3),e=Atomics.load(t[v].state,Xe),e===-2){ue(t,new Error("end() failed"));return}if(++r===10){ue(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[v].finished=!0,t.emit("finish")})}catch(e){ue(t,e)}}}function Us(t){let e=()=>{t[v].ending?Ws(t):t[v].needDrain&&process.nextTick(Bo,t)};for(t[v].flushing=!1;t[v].bufLen!==0;){let r=Atomics.load(t[v].state,Re),s=t[v].data.length-r;if(s===0){Go(t),Uo(t);continue}else if(s<0)throw new Error("overwritten");Ko(t,s,e)}}function Go(t){if(t[v].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[v].state,Re),r=0;for(;;){let s=Atomics.load(t[v].state,Xe);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(t[v].state,Xe,s,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Jo.exports=qs});var Ks=P((Hw,Zo)=>{"use strict";var{createRequire:Ld}=require("module"),{existsSync:Dd}=require("node:fs"),Nd=Os(),{join:Vs,isAbsolute:Qo,sep:Ud}=require("node:path"),{fileURLToPath:qd}=require("node:url"),Bd=Ms(),zs=Ds(),Hd=Yo();function Wd(t){zs.register(t,Jd),zs.registerBeforeExit(t,Yd),t.on("close",function(){zs.unregister(t)})}function Vd(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function zd(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],s=!1;for(let n=0;n<e.length;n++){let i=e[n];if(i==="--require"||i==="-r"||i==="--import"){let o=e[n+1];if(o&&Xo(o)){s=!0,n++;continue}r.push(i),o&&(r.push(o),n++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Xo(o)){s=!0;continue}}r.push(i)}return s?r.join(" "):t}function Xo(t){let e=Kd(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=qd(r)}catch{return!1}return Qo(r)&&!Dd(r)}function Kd(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Gd(t,e,r,s,n){if(!r.execArgv&&Vd()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=zd(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:n};let i=new Hd({filename:t,workerData:e,workerOpts:r,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&Wd(i)}function a(){i.closed||(i.flushSync(),Bd(100),i.end())}return i}function Jd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Yd(t){t.flushSync()}function Xd(t){let{pipeline:e,targets:r,levels:s,dedupe:n,worker:i={},caller:o=Nd(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||Vs(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:h(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(m=>({...m,level:f.level,target:h(m.target)})))):e&&(d=u["pino-worker"]||Vs(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:h(f.target)}))]),s&&(l.levels=s),n&&(l.dedupe=n),l.pinoWillSendConfig=!0;let p=r||e?"pino.transport":d;return Gd(h(d),l,i,a,p);function h(f){if(f=u[f]||f,Qo(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return Vs(__dirname,"..","file.js");let m;for(let g of c)try{let y=g==="node:repl"?process.cwd()+Ud:g;m=Ld(y).resolve(f);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${f}"`);return m}}Zo.exports=Xd});var _r=P((Ww,da)=>{"use strict";var Qd=require("node:diagnostics_channel"),ea=xo(),{mapHttpRequest:Zd,mapHttpResponse:ep}=As(),Js=Eo(),ta=Ds(),{lsCacheSym:tp,chindingsSym:oa,writeSym:ra,serializersSym:aa,formatOptsSym:sa,endSym:rp,stringifiersSym:la,stringifySym:ca,stringifySafeSym:Ys,wildcardFirstSym:ua,nestedKeySym:sp,formattersSym:fa,messageKeySym:np,errorKeySym:ip,nestedKeyStrSym:op,msgPrefixSym:Sr}=dt(),{isMainThread:ap}=require("worker_threads"),lp=Ks(),[cp]=process.versions.node.split(".").map(t=>Number(t)),na=Qd.tracingChannel("pino_asJson"),Gs=cp>=25?t=>JSON.stringify(t):fp;function ht(){}function up(t,e){if(!e)return r;return function(...n){e.call(this,n,r,t)};function r(s,...n){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=Zd(s):typeof s.setHeader=="function"&&(s=ep(s)));let o;i===null&&n.length===0?o=[null]:(i=n.shift(),o=n),typeof this[Sr]=="string"&&i!==void 0&&i!==null&&(i=this[Sr]+i),this[ra](s,ea(i,o,this[sa]),t)}else{let i=s===void 0?n.shift():s;typeof this[Sr]=="string"&&i!==void 0&&i!==null&&(i=this[Sr]+i),this[ra](null,ea(i,n,this[sa]),t)}}}function fp(t){let e="",r=0,s=!1,n=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&n>=32;o++)n=t.charCodeAt(o),(n===34||n===92)&&(e+=t.slice(r,o)+"\\",r=o,s=!0);return s?e+=t.slice(r):e=t,n<32?JSON.stringify(t):'"'+e+'"'}function dp(t,e,r,s){if(na.hasSubscribers===!1)return ia.call(this,t,e,r,s);let n={instance:this,arguments};return na.traceSync(ia,n,this,t,e,r,s)}function ia(t,e,r,s){let n=this[ca],i=this[Ys],o=this[la],a=this[rp],l=this[oa],c=this[aa],u=this[fa],d=this[np],p=this[ip],h=this[tp][r]+s;h=h+l;let f;u.log&&(t=u.log(t));let m=o[ua],g="";for(let b in t)if(f=t[b],Object.prototype.hasOwnProperty.call(t,b)&&f!==void 0){c[b]?f=c[b](f):b===p&&c.err&&(f=c.err(f));let w=o[b]||m;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":w&&(f=w(f));break;case"string":f=(w||Gs)(f);break;default:f=(w||n)(f,i)}if(f===void 0)continue;let S=Gs(b);g+=","+S+":"+f}let y="";if(e!==void 0){f=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":b&&(f=b(f)),y=',"'+d+'":'+f;break;case"string":f=(b||Gs)(f),y=',"'+d+'":'+f;break;default:f=(b||n)(f,i),y=',"'+d+'":'+f}}return this[sp]&&g?h+this[op]+g.slice(1)+"}"+y+a:h+g+y+a}function pp(t,e){let r,s=t[oa],n=t[ca],i=t[Ys],o=t[la],a=o[ua],l=t[aa],c=t[fa].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||n)(r,i),r===void 0)continue;s+=',"'+u+'":'+r}return s}function hp(t){return t.write!==t.constructor.prototype.write}function vr(t){let e=new Js(t);return e.on("error",r),!t.sync&&ap&&(ta.register(e,mp),e.on("close",function(){ta.unregister(e)})),e;function r(s){if(s.code==="EPIPE"){e.write=ht,e.end=ht,e.flushSync=ht,e.destroy=ht;return}e.removeListener("error",r),e.emit("error",s)}}function mp(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function gp(t){return function(r,s,n={},i){if(typeof n=="string")i=vr({dest:n}),n={};else if(typeof i=="string"){if(n&&n.transport)throw Error("only one of option.transport or stream can be specified");i=vr({dest:i})}else if(n instanceof Js||n.writable||n._writableState)i=n,n={};else if(n.transport){if(n.transport instanceof Js||n.transport.writable||n.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(n.transport.targets&&n.transport.targets.length&&n.formatters&&typeof n.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;n.customLevels&&(l=n.useOnlyCustomLevels?n.customLevels:Object.assign({},n.levels,n.customLevels)),i=lp({caller:s,...n.transport,levels:l})}if(n=Object.assign({},t,n),n.serializers=Object.assign({},t.serializers,n.serializers),n.formatters=Object.assign({},t.formatters,n.formatters),n.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=n;return o===!1&&(n.level="silent"),a||(n.onChild=ht),i||(hp(process.stdout)?i=process.stdout:i=vr({fd:process.stdout.fd||1})),{opts:n,stream:i}}}function yp(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Ys])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function wp(t,e,r){return{level:t,bindings:e,log:r}}function bp(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}da.exports={noop:ht,buildSafeSonicBoom:vr,asChindings:pp,asJson:dp,genLog:up,createArgsNormalizer:gp,stringify:yp,buildFormatters:wp,normalizeDestFileDescriptor:bp}});var kr=P((Vw,pa)=>{var xp={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Sp={ASC:"ASC",DESC:"DESC"};pa.exports={DEFAULT_LEVELS:xp,SORTING_ORDER:Sp}});var Zs=P((zw,ya)=>{"use strict";var{lsCacheSym:vp,levelValSym:Xs,useOnlyCustomLevelsSym:_p,streamSym:kp,formattersSym:Tp,hooksSym:Cp,levelCompSym:ha}=dt(),{noop:$p,genLog:Qe}=_r(),{DEFAULT_LEVELS:ke,SORTING_ORDER:ma}=kr(),ga={fatal:t=>{let e=Qe(ke.fatal,t);return function(...r){let s=this[kp];if(e.call(this,...r),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:t=>Qe(ke.error,t),warn:t=>Qe(ke.warn,t),info:t=>Qe(ke.info,t),debug:t=>Qe(ke.debug,t),trace:t=>Qe(ke.trace,t)},Qs=Object.keys(ke).reduce((t,e)=>(t[ke[e]]=e,t),{}),Ep=Object.keys(Qs).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Ap(t){let e=t[Tp].level,{labels:r}=t.levels,s={};for(let n in r){let i=e(r[n],Number(n));s[n]=JSON.stringify(i).slice(0,-1)}return t[vp]=s,t}function Op(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Rp(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let s=this[Xs],n=this[Xs]=r[t],i=this[_p],o=this[ha],a=this[Cp].logMethod;for(let l in r){if(o(r[l],n)===!1){this[l]=$p;continue}this[l]=Op(l,i)?ga[l](a):Qe(r[l],a)}this.emit("level-change",t,n,e[s],s,this)}function Ip(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function jp(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[ha](r,this[Xs])}function Pp(t,e,r){return t===ma.DESC?e<=r:e>=r}function Mp(t){return typeof t=="string"?Pp.bind(null,t):t}function Fp(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:Qs,r),n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ke,t);return{labels:s,values:n}}function Lp(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(Qs).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:ke,e);if(!(t in s))throw Error(`default level:${t} must be included in custom levels`)}function Dp(t,e){let{labels:r,values:s}=t;for(let n in e){if(n in s)throw Error("levels cannot be overridden");if(e[n]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Np(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(ma).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ya.exports={initialLsCache:Ep,genLsCache:Ap,levelMethods:ga,getLevel:Ip,setLevel:Rp,isLevelEnabled:jp,mappings:Fp,assertNoLevelCollisions:Dp,assertDefaultLevelFound:Lp,genLevelComparison:Mp,assertLevelComparison:Np}});var en=P((Kw,wa)=>{"use strict";wa.exports={version:"10.3.1"}});var Ca=P((Jw,Ta)=>{"use strict";var{EventEmitter:Up}=require("node:events"),{lsCacheSym:qp,levelValSym:Bp,setLevelSym:rn,getLevelSym:ba,chindingsSym:Cr,mixinSym:Hp,asJsonSym:Sa,writeSym:Wp,mixinMergeStrategySym:Vp,timeSym:zp,timeSliceIndexSym:Kp,streamSym:va,serializersSym:Ze,formattersSym:Lt,errorKeySym:Gp,messageKeySym:Jp,useOnlyCustomLevelsSym:Yp,needsMetadataGsym:Xp,redactFmtSym:Qp,stringifySym:Zp,formatOptsSym:eh,stringifiersSym:th,msgPrefixSym:sn,hooksSym:rh}=dt(),{getLevel:sh,setLevel:nh,isLevelEnabled:ih,mappings:oh,initialLsCache:ah,genLsCache:lh,assertNoLevelCollisions:ch}=Zs(),{asChindings:nn,asJson:uh,buildFormatters:tn,stringify:xa,noop:_a}=_r(),{version:fh}=en(),dh=js(),ph=class{},ka={constructor:ph,child:hh,bindings:mh,setBindings:gh,flush:bh,isLevelEnabled:ih,version:fh,get level(){return this[ba]()},set level(t){this[rn](t)},get levelVal(){return this[Bp]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[sn]},get[Symbol.toStringTag](){return"Pino"},[qp]:ah,[Wp]:wh,[Sa]:uh,[ba]:sh,[rn]:nh};Object.setPrototypeOf(ka,Up.prototype);Ta.exports=function(){return Object.create(ka)};var Tr=t=>t;function hh(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[Ze],s=this[Lt],n=Object.create(this);if(e==null)return n[Lt].bindings!==Tr&&(n[Lt]=tn(s.level,Tr,s.log)),n[Cr]=nn(n,t),this.onChild!==_a&&this.onChild(n),n;if(e.hasOwnProperty("serializers")===!0){n[Ze]=Object.create(null);for(let c in r)n[Ze][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];n[Ze][c]=r[c]}for(let c in e.serializers)n[Ze][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];n[Ze][c]=e.serializers[c]}}else n[Ze]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;n[Lt]=tn(a||s.level,l||Tr,c||s.log)}else n[Lt]=tn(s.level,Tr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(ch(this.levels,e.customLevels),n.levels=oh(e.customLevels,n[Yp]),lh(n)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){n.redact=e.redact;let a=dh(n.redact,xa),l={stringify:a[Qp]};n[Zp]=xa,n[th]=a,n[eh]=l}if(typeof e.msgPrefix=="string"&&(n[sn]=(this[sn]||"")+e.msgPrefix),n[Cr]=nn(n,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;n[rn](a)}return this.onChild(n),n}function mh(){let e=`{${this[Cr].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function gh(t){let e=nn(this,t);this[Cr]=e}function yh(t,e){return Object.assign(e,t)}function wh(t,e,r){let s=this[zp](),n=this[Hp],i=this[Gp],o=this[Jp],a=this[Vp]||yh,l,c=this[rh].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),n&&(l=a(l,n(l,r,this)));let u=this[Sa](l,e,r,s),d=this[va];d[Xp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=s.slice(this[Kp]),d.lastLogger=this),d.write(c?c(u):u)}function bh(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[va];typeof e.flush=="function"?e.flush(t||_a):t&&t()}});var Oa=P((cn,Aa)=>{"use strict";var{hasOwnProperty:Dt}=Object.prototype,tt=ln();tt.configure=ln;tt.stringify=tt;tt.default=tt;cn.stringify=tt;cn.configure=ln;Aa.exports=tt;var xh=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ue(t){return t.length<5e3&&!xh.test(t)?`"${t}"`:JSON.stringify(t)}function on(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let s=t[r],n=r;for(;n!==0&&t[n-1]>s;)t[n]=t[n-1],n--;t[n]=s}return t}var Sh=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function an(t){return Sh.call(t)!==void 0&&t.length!==0}function $a(t,e,r){t.length<r&&(r=t.length);let s=e===","?"":" ",n=`"0":${s}${t[0]}`;for(let i=1;i<r;i++)n+=`${e}"${i}":${s}${t[i]}`;return n}function vh(t){if(Dt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function _h(t){let e;if(Dt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function kh(t,e){let r;if(Dt.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ea(t,e){let r;if(Dt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function et(t){return t===1?"1 item":`${t} items`}function Th(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Ch(t){if(Dt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let s=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(s+=` (${r.toString()})`),new Error(s)}}}function ln(t){t={...t};let e=Ch(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=vh(t),s=kh(t,"bigint"),n=_h(t),i=typeof n=="function"?n:void 0,o=Ea(t,"maximumDepth"),a=Ea(t,"maximumBreadth");function l(h,f,m,g,y,b){let w=f[h];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(h)),w=g.call(f,h,w),typeof w){case"string":return Ue(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return r;let S="",_=",",C=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(w),y!==""&&(b+=y,S+=`
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(n=>r.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Ai(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,s="127.0.0.1",n="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?n=i[3]:s=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],s=i[3],n=i[4]),r&&n!=="0"?`${r}=${s}:${parseInt(n)+1}`:e})}Ei.Command=bs});var Pi=P(le=>{var{Argument:Ri}=cr(),{Command:xs}=Oi(),{CommanderError:ju,InvalidArgumentError:Ii}=Mt(),{Help:Pu}=fs(),{Option:ji}=ms();le.program=new xs;le.createCommand=t=>new xs(t);le.createOption=(t,e)=>new ji(t,e);le.createArgument=(t,e)=>new Ri(t,e);le.Command=xs;le.Option=ji;le.Argument=Ri;le.Help=Pu;le.CommanderError=ju;le.InvalidArgumentError=Ii;le.InvalidOptionArgumentError=Ii});var _s=P((Tw,qi)=>{"use strict";var Ft=t=>t&&typeof t.message=="string",vs=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return Ft(r)?r:void 0}else return Ft(e)?e:void 0},Ni=(t,e)=>{if(!Ft(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let s=vs(t);return s?(e.add(t),r+`
25
+ caused by: `+Ni(s,e)):r},Mu=t=>Ni(t,new Set),Ui=(t,e,r)=>{if(!Ft(t))return"";let s=r?"":t.message||"";if(e.has(t))return s+": ...";let n=vs(t);if(n){e.add(t);let i=typeof t.cause=="function";return s+(i?"":": ")+Ui(n,e,i)}else return s},Fu=t=>Ui(t,new Set);qi.exports={isErrorLike:Ft,getErrorCause:vs,stackWithCauses:Mu,messageWithCauses:Fu}});var ks=P((Cw,Hi)=>{"use strict";var Lu=Symbol("circular-ref-tag"),ur=Symbol("pino-raw-err-ref"),Bi=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[ur]},set:function(t){this[ur]=t}}});Object.defineProperty(Bi,ur,{writable:!0,value:{}});Hi.exports={pinoErrProto:Bi,pinoErrorSymbols:{seen:Lu,rawSymbol:ur}}});var zi=P(($w,Vi)=>{"use strict";Vi.exports=Cs;var{messageWithCauses:Du,stackWithCauses:Nu,isErrorLike:Wi}=_s(),{pinoErrProto:Uu,pinoErrorSymbols:qu}=ks(),{seen:Ts}=qu,{toString:Bu}=Object.prototype;function Cs(t){if(!Wi(t))return t;t[Ts]=void 0;let e=Object.create(Uu);e.type=Bu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=Du(t),e.stack=Nu(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Cs(r)));for(let r in t)if(e[r]===void 0){let s=t[r];Wi(s)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(s,Ts)&&(e[r]=Cs(s)):e[r]=s}return delete t[Ts],e.raw=t,e}});var Gi=P((Aw,Ki)=>{"use strict";Ki.exports=dr;var{isErrorLike:$s}=_s(),{pinoErrProto:Hu,pinoErrorSymbols:Wu}=ks(),{seen:fr}=Wu,{toString:Vu}=Object.prototype;function dr(t){if(!$s(t))return t;t[fr]=void 0;let e=Object.create(Hu);e.type=Vu.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=t.message,e.stack=t.stack,Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>dr(r))),$s(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,fr)&&(e.cause=dr(t.cause));for(let r in t)if(e[r]===void 0){let s=t[r];$s(s)?Object.prototype.hasOwnProperty.call(s,fr)||(e[r]=dr(s)):e[r]=s}return delete t[fr],e.raw=t,e}});var Qi=P((Ew,Yi)=>{"use strict";Yi.exports={mapHttpRequest:zu,reqSerializer:Xi};var As=Symbol("pino-raw-req-ref"),Ji=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[As]},set:function(t){this[As]=t}}});Object.defineProperty(Ji,As,{writable:!0,value:{}});function Xi(t){let e=t.info||t.socket,r=Object.create(Ji);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let s=t.path;r.url=typeof s=="string"?s:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function zu(t){return{req:Xi(t)}}});var ro=P((Ow,to)=>{"use strict";to.exports={mapHttpResponse:Ku,resSerializer:eo};var Es=Symbol("pino-raw-res-ref"),Zi=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Es]},set:function(t){this[Es]=t}}});Object.defineProperty(Zi,Es,{writable:!0,value:{}});function eo(t){let e=Object.create(Zi);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Ku(t){return{res:eo(t)}}});var Rs=P((Rw,so)=>{"use strict";var Os=zi(),Gu=Gi(),pr=Qi(),hr=ro();so.exports={err:Os,errWithCause:Gu,mapHttpRequest:pr.mapHttpRequest,mapHttpResponse:hr.mapHttpResponse,req:pr.reqSerializer,res:hr.resSerializer,wrapErrorSerializer:function(e){return e===Os?e:function(s){return e(Os(s))}},wrapRequestSerializer:function(e){return e===pr.reqSerializer?e:function(s){return e(pr.reqSerializer(s))}},wrapResponseSerializer:function(e){return e===hr.resSerializer?e:function(s){return e(hr.resSerializer(s))}}}});var Is=P((Iw,no)=>{"use strict";function Ju(t,e){return e}no.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Ju;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let s=r.slice(2),n=[];for(let i of s)i&&n.push(i.getFileName());return n}});var uo=P((jw,co)=>{"use strict";function js(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array){let e=[];for(let r=0;r<t.length;r++)e[r]=js(t[r]);return e}if(typeof t=="object"){let e=Object.create(Object.getPrototypeOf(t));for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=js(t[r]));return e}return t}function io(t){let e=[],r="",s=!1,n=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!s&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),s=!0):a==="]"&&s?(e.push(r),r="",s=!1,n=!1):(a==='"'||a==="'")&&s?n?a===i?(n=!1,i=""):r+=a:(n=!0,i=a):r+=a}return r&&e.push(r),e}function oo(t,e,r){let s=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof s!="object"||s===null||!(o in s)||typeof s[o]!="object"||s[o]===null)return!1;s=s[o]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(s))for(let i=0;i<s.length;i++)s[i]=r;else if(typeof s=="object"&&s!==null)for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&(s[i]=r)}else typeof s=="object"&&s!==null&&n in s&&Object.prototype.hasOwnProperty.call(s,n)&&(s[n]=r);return!0}function ao(t,e){let r=t;for(let n=0;n<e.length-1;n++){let i=e[n];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(r))for(let n=0;n<r.length;n++)r[n]=void 0;else if(typeof r=="object"&&r!==null)for(let n in r)Object.prototype.hasOwnProperty.call(r,n)&&delete r[n]}else typeof r=="object"&&r!==null&&s in r&&Object.prototype.hasOwnProperty.call(r,s)&&delete r[s];return!0}var mr=Symbol("PATH_NOT_FOUND");function Xu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null||!(s in r))return mr;r=r[s]}return r}function Yu(t,e){let r=t;for(let s of e){if(r==null||typeof r!="object"||r===null)return;r=r[s]}return r}function Qu(t,e,r,s=!1){for(let n of e){let i=io(n);if(i.includes("*"))lo(t,i,r,n,s);else if(s)ao(t,i);else{let o=Xu(t,i);if(o===mr)continue;let a=typeof r=="function"?r(o,i):r;oo(t,i,a)}}}function lo(t,e,r,s,n=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(n)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let c=[...o,l.toString()],u=typeof r=="function"?r(a[l],c):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(n){let l=[];for(let c in a)Object.prototype.hasOwnProperty.call(a,c)&&l.push(c);for(let c of l)delete a[c]}else for(let l in a){let c=[...o,l],u=typeof r=="function"?r(a[l],c):r;a[l]=u}}else Zu(t,e,r,i,s,n)}function Zu(t,e,r,s,n,i=!1){let o=e.slice(0,s),a=e.slice(s+1),l=[];function c(u,d){if(d===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)l[d]=p.toString(),c(u[p],d+1);else if(typeof u=="object"&&u!==null)for(let p in u)l[d]=p,c(u[p],d+1)}else if(d<o.length){let p=o[d];u&&typeof u=="object"&&u!==null&&p in u&&(l[d]=p,c(u[p],d+1))}else if(a.includes("*"))lo(u,a,typeof r=="function"?(h,f)=>{let m=[...l.slice(0,d),...f];return r(h,m)}:r,n,i);else if(i)ao(u,a);else{let p=typeof r=="function"?r(Yu(u,a),[...l.slice(0,d),...a]):r;oo(u,a,p)}}if(o.length===0)c(t,0);else{let u=t;for(let d=0;d<o.length;d++){let p=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[p],l[d]=p}u!=null&&c(u,o.length)}}function ef(t){if(t.length===0)return null;let e=new Map;for(let r of t){let s=io(r),n=e;for(let i=0;i<s.length;i++){let o=s[i];n.has(o)||n.set(o,new Map),n=n.get(o)}}return e}function tf(t,e){if(!e)return t;function r(s,n,i=0){if(!n||n.size===0||s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(Array.isArray(s)){let a=[];for(let l=0;l<s.length;l++){let c=l.toString();n.has(c)||n.has("*")?a[l]=r(s[l],n.get(c)||n.get("*")):a[l]=s[l]}return a}let o=Object.create(Object.getPrototypeOf(s));for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&(n.has(a)||n.has("*")?o[a]=r(s[a],n.get(a)||n.get("*")):o[a]=s[a]);return o}return r(t,e)}function rf(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,s="";for(let n=0;n<t.length;n++){let i=t[n];if((i==='"'||i==="'")&&e>0)r?i===s&&(r=!1,s=""):(r=!0,s=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function sf(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)rf(e)}function nf(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:s=JSON.stringify,strict:n=!0,remove:i=!1}=t;sf(e);let o=ef(e);return function(l){if(n&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return s?s(l):l;let c=tf(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Qu(c,e,d,i),s===!1?(c.restore=function(){return js(u)},c):typeof s=="function"?s(c):JSON.stringify(c)}}co.exports=nf});var pt=P((Pw,fo)=>{"use strict";var of=Symbol("pino.setLevel"),af=Symbol("pino.getLevel"),lf=Symbol("pino.levelVal"),cf=Symbol("pino.levelComp"),uf=Symbol("pino.useLevelLabels"),ff=Symbol("pino.useOnlyCustomLevels"),df=Symbol("pino.mixin"),pf=Symbol("pino.lsCache"),hf=Symbol("pino.chindings"),mf=Symbol("pino.asJson"),gf=Symbol("pino.write"),yf=Symbol("pino.redactFmt"),wf=Symbol("pino.time"),bf=Symbol("pino.timeSliceIndex"),xf=Symbol("pino.stream"),Sf=Symbol("pino.stringify"),vf=Symbol("pino.stringifySafe"),_f=Symbol("pino.stringifiers"),kf=Symbol("pino.end"),Tf=Symbol("pino.formatOpts"),Cf=Symbol("pino.messageKey"),$f=Symbol("pino.errorKey"),Af=Symbol("pino.nestedKey"),Ef=Symbol("pino.nestedKeyStr"),Of=Symbol("pino.mixinMergeStrategy"),Rf=Symbol("pino.msgPrefix"),If=Symbol("pino.wildcardFirst"),jf=Symbol.for("pino.serializers"),Pf=Symbol.for("pino.formatters"),Mf=Symbol.for("pino.hooks"),Ff=Symbol.for("pino.metadata");fo.exports={setLevelSym:of,getLevelSym:af,levelValSym:lf,levelCompSym:cf,useLevelLabelsSym:uf,mixinSym:df,lsCacheSym:pf,chindingsSym:hf,asJsonSym:mf,writeSym:gf,serializersSym:jf,redactFmtSym:yf,timeSym:wf,timeSliceIndexSym:bf,streamSym:xf,stringifySym:Sf,stringifySafeSym:vf,stringifiersSym:_f,endSym:kf,formatOptsSym:Tf,messageKeySym:Cf,errorKeySym:$f,nestedKeySym:Af,wildcardFirstSym:If,needsMetadataGsym:Ff,useOnlyCustomLevelsSym:ff,formattersSym:Pf,hooksSym:Mf,nestedKeyStrSym:Ef,mixinMergeStrategySym:Of,msgPrefixSym:Rf}});var Ms=P((Mw,go)=>{"use strict";var po=uo(),{redactFmtSym:Lf,wildcardFirstSym:gr}=pt(),Ps=/[^.[\]]+|\[([^[\]]*?)\]/g,ho="[Redacted]",mo=!1;function Df(t,e){let{paths:r,censor:s,remove:n}=Nf(t),i=r.reduce((l,c)=>{Ps.lastIndex=0;let u=Ps.exec(c),d=Ps.exec(c),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=gr),d===null)return l[p]=null,l;if(l[p]===null)return l;let{index:h}=d,f=`${c.substr(h,c.length-1)}`;return l[p]=l[p]||[],p!==gr&&l[p].length===0&&l[p].push(...l[gr]||[]),p===gr&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(f)}),l[p].push(f),l},{}),o={[Lf]:po({paths:r,censor:s,serialize:e,strict:mo,remove:n})},a=(...l)=>e(typeof s=="function"?s(...l):s);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,c)=>{if(i[c]===null)l[c]=u=>a(u,[c]);else{let u=typeof s=="function"?(d,p)=>s(d,[c,...p]):s;l[c]=po({paths:i[c],censor:u,serialize:e,strict:mo,remove:n})}return l},o)}function Nf(t){if(Array.isArray(t))return t={paths:t,censor:ho},t;let{paths:e,censor:r=ho,remove:s}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return s===!0&&(r=void 0),{paths:e,censor:r,remove:s}}go.exports=Df});var bo=P((Fw,wo)=>{"use strict";var Uf=()=>"",qf=()=>`,"time":${Date.now()}`,Bf=()=>`,"time":${Math.round(Date.now()/1e3)}`,Hf=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,Wf=1000000n,yo=1000000000n,Vf=BigInt(Date.now())*Wf,zf=process.hrtime.bigint(),Kf=()=>{let t=process.hrtime.bigint()-zf,e=Vf+t,r=e/yo,s=e%yo,n=Number(r*1000n+s/1000000n),i=new Date(n),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${c}:${u}:${d}.${s.toString().padStart(9,"0")}Z"`};wo.exports={nullTime:Uf,epochTime:qf,unixTime:Bf,isoTime:Hf,isoTimeNano:Kf}});var So=P((Lw,xo)=>{"use strict";function Gf(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}xo.exports=Jf;function Jf(t,e,r){var s=r&&r.stringify||Gf,n=1;if(typeof t=="object"&&t!==null){var i=e.length+n;if(i===1)return t;var o=new Array(i);o[0]=s(t);for(var a=1;a<i;a++)o[a]=s(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var c="",u=1-n,d=-1,p=t&&t.length||0,h=0;h<p;){if(t.charCodeAt(h)===37&&h+1<p){switch(d=d>-1?d:0,t.charCodeAt(h+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<h&&(c+=t.slice(d,h)),c+=Number(e[u]),d=h+2,h++;break;case 105:if(u>=l||e[u]==null)break;d<h&&(c+=t.slice(d,h)),c+=Math.floor(Number(e[u])),d=h+2,h++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<h&&(c+=t.slice(d,h));var f=typeof e[u];if(f==="string"){c+="'"+e[u]+"'",d=h+2,h++;break}if(f==="function"){c+=e[u].name||"<anonymous>",d=h+2,h++;break}c+=s(e[u]),d=h+2,h++;break;case 115:if(u>=l)break;d<h&&(c+=t.slice(d,h)),c+=String(e[u]),d=h+2,h++;break;case 37:d<h&&(c+=t.slice(d,h)),c+="%",d=h+2,h++,u--;break}++u}++h}return d===-1?t:(d<p&&(c+=t.slice(d)),c)}});var Ls=P((Dw,Fs)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(t,0,0,Number(r))},t=new Int32Array(new SharedArrayBuffer(4));Fs.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let s=Date.now()+Number(e);for(;s>Date.now(););};Fs.exports=t}});var Eo=P((Nw,Ao)=>{"use strict";var q=require("fs"),Xf=require("events"),Yf=require("util").inherits,vo=require("path"),Ns=Ls(),Qf=require("assert"),yr=100,wr=Buffer.allocUnsafe(0),Zf=16*1024,_o="buffer",ko="utf8",[ed,td]=(process.versions.node||"0.0").split(".").map(Number),rd=ed>=22&&td>=7;function To(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let s=e.append?"a":"w",n=e.mode;if(e.sync)try{e.mkdir&&q.mkdirSync(vo.dirname(t),{recursive:!0});let i=q.openSync(t,s,n);r(null,i)}catch(i){throw r(i),i}else e.mkdir?q.mkdir(vo.dirname(t),{recursive:!0},i=>{if(i)return r(i);q.open(t,s,n,r)}):q.open(t,s,n,r)}function be(t){if(!(this instanceof be))return new be(t);let{fd:e,dest:r,minLength:s,maxLength:n,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:c,retryEAGAIN:u,fsync:d,contentMode:p,mode:h}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(s||0,16387),this.file=null,this.destroyed=!1,this.minLength=s||0,this.maxLength=n||0,this.maxWrite=i||Zf,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=c||!1;let f,m;if(p===_o)this._writingBuf=wr,this.write=id,this.flush=ad,this.flushSync=cd,this._actualWrite=fd,f=()=>q.writeSync(this.fd,this._writingBuf),m=()=>q.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===ko)this._writingBuf="",this.write=nd,this.flush=od,this.flushSync=ld,this._actualWrite=ud,f=()=>Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?q.write(this.fd,this._writingBuf,this.release):q.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${ko}" and "${_o}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")To(e,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,y)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Ns(yr),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,yr);else this._writing=!1,this.emit("error",g);return}this.emit("write",y);let b=Ds(this._writingBuf,this._len,y);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=f(),_=Ds(this._writingBuf,this._len,S);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&q.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,br(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(sd,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Ds(t,e,r){return typeof t=="string"&&(t=Buffer.from(t)),e=Math.max(e-r,0),t=t.subarray(r),{writingBuf:t,len:e}}function sd(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Yf(be,Xf);function Co(t,e){return t.length===0?wr:t.length===1?t[0]:Buffer.concat(t,e)}function nd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,s=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(s.length===0||Buffer.byteLength(s[s.length-1])+e>this.maxWrite?s.push(t):s[s.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function id(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,s=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||s[s.length-1]+t.length>this.maxWrite?(r.push([t]),s.push(t.length)):(r[r.length-1].push(t),s[s.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function $o(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{q.fsync(this.fd,s=>{this._flushPending=!1,t(s)})}catch(s){t(s)}this.off("error",r)},r=s=>{this._flushPending=!1,t(s),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function od(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&$o.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function ad(t){if(t!=null&&typeof t!="function")throw new Error("flush cb must be a function");if(this.destroyed){let e=new Error("SonicBoom destroyed");if(t){t(e);return}throw e}if(this.minLength<=0){t?.();return}t&&$o.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}be.prototype.reopen=function(t){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(t)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(t&&(this.file=t),this._reopening=!0,this._writing)return;let e=this.fd;this.once("ready",()=>{e!==this.fd&&q.close(e,r=>{if(r)return this.emit("error",r)})}),To(this.file,this)};be.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():br(this)))};function ld(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let t="";for(;this._bufs.length||t.length;){t.length<=0&&(t=this._bufs[0]);try{let e=Buffer.isBuffer(t)?q.writeSync(this.fd,t):q.writeSync(this.fd,t,"utf8"),r=Ds(t,this._len,e);t=r.writingBuf,this._len=r.len,t.length<=0&&this._bufs.shift()}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Ns(yr)}}try{q.fsyncSync(this.fd)}catch{}}function cd(){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=wr);let t=wr;for(;this._bufs.length||t.length;){t.length<=0&&(t=Co(this._bufs[0],this._lens[0]));try{let e=q.writeSync(this.fd,t);t=t.subarray(e),this._len=Math.max(this._len-e,0),t.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(e){if((e.code==="EAGAIN"||e.code==="EBUSY")&&!this.retryEAGAIN(e,t.length,this._len-t.length))throw e;Ns(yr)}}}be.prototype.destroy=function(){this.destroyed||br(this)};function ud(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||"",this.sync)try{let e=Buffer.isBuffer(this._writingBuf)?q.writeSync(this.fd,this._writingBuf):q.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else q.write(this.fd,this._writingBuf,t)}function fd(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Co(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=q.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else rd&&(this._writingBuf=Buffer.from(this._writingBuf)),q.write(this.fd,this._writingBuf,t)}function br(t){if(t.fd===-1){t.once("ready",br.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Qf(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{q.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?q.close(t.fd,r):r()}function r(s){if(s){t.emit("error",s);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}be.SonicBoom=be;be.default=be;Ao.exports=be});var Us=P((Uw,Po)=>{"use strict";var xe={exit:[],beforeExit:[]},Oo={exit:hd,beforeExit:md},ht;function dd(){ht===void 0&&(ht=new FinalizationRegistry(gd))}function pd(t){xe[t].length>0||process.on(t,Oo[t])}function Ro(t){xe[t].length>0||(process.removeListener(t,Oo[t]),xe.exit.length===0&&xe.beforeExit.length===0&&(ht=void 0))}function hd(){Io("exit")}function md(){Io("beforeExit")}function Io(t){for(let e of xe[t]){let r=e.deref(),s=e.fn;r!==void 0&&s(r,t)}xe[t]=[]}function gd(t){for(let e of["exit","beforeExit"]){let r=xe[e].indexOf(t);xe[e].splice(r,r+1),Ro(e)}}function jo(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");pd(t);let s=new WeakRef(e);s.fn=r,dd(),ht.register(e,s),xe[t].push(s)}function yd(t,e){jo("exit",t,e)}function wd(t,e){jo("beforeExit",t,e)}function bd(t){if(ht!==void 0){ht.unregister(t);for(let e of["exit","beforeExit"])xe[e]=xe[e].filter(r=>{let s=r.deref();return s&&s!==t}),Ro(e)}}Po.exports={register:yd,registerBeforeExit:wd,unregister:bd}});var Mo=P((qw,xd)=>{xd.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 Lo=P((Bw,Fo)=>{"use strict";function Sd(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{let a=Atomics.load(t,e);if(a===r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,a,l);c.async?c.value.then(o):setImmediate(o)};o()}function vd(t,e,r,s,n){let i=s===1/0?1/0:Date.now()+s,o=()=>{if(Atomics.load(t,e)!==r){n(null,"ok");return}if(i!==1/0&&Date.now()>i){n(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),c=Atomics.waitAsync(t,e,r,l);c.async?c.value.then(u=>{if(u==="ok"){n(null,"ok");return}o()}):setImmediate(o)};o()}Fo.exports={wait:Sd,waitDiff:vd}});var No=P((Hw,Do)=>{"use strict";Do.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var Yo=P((Ww,Xo)=>{"use strict";var{version:_d}=Mo(),{EventEmitter:kd}=require("events"),{Worker:Td}=require("worker_threads"),{join:Cd}=require("path"),{pathToFileURL:$d}=require("url"),{wait:Ad}=Lo(),{WRITE_INDEX:Ie,READ_INDEX:Qe,SEQ_INDEX:qs}=No(),Ed=require("buffer"),Od=require("assert"),v=Symbol("kImpl"),Rd=Ed.constants.MAX_STRING_LENGTH;function Uo(){}function Vs(t,e){Atomics.add(t[v].state,qs,1),e(),Atomics.add(t[v].state,qs,1),Atomics.notify(t[v].state,qs)}function qo(t){Vs(t,()=>{Atomics.store(t[v].state,Qe,0),Atomics.store(t[v].state,Ie,0)})}var Lt=class{constructor(e){this._value=e}deref(){return this._value}},xr=class{register(){}unregister(){}},Id=process.env.NODE_V8_COVERAGE?xr:global.FinalizationRegistry||xr,jd=process.env.NODE_V8_COVERAGE?Lt:global.WeakRef||Lt,Bo=new Id(t=>{t.exited||t.terminate()});function Pd(t,e){let{filename:r,workerData:s}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Cd(__dirname,"lib","worker.js"),o=new Td(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:$d(r).href,dataBuf:t[v].dataBuf,stateBuf:t[v].stateBuf,workerData:{$context:{threadStreamVersion:_d},...s}}});return o.stream=new Lt(t),o.on("message",Md),o.on("exit",Vo),Bo.register(t,o),o}function Ho(t){Od(!t[v].sync),t[v].needDrain&&(t[v].needDrain=!1,t.emit("drain"))}function Wo(t){for(;;){let e=Atomics.load(t[v].state,Ie),r=t[v].data.length-e;if(r>0){if(t[v].bufLen===0){t[v].flushing=!1,t[v].ending?zs(t):t[v].needDrain&&process.nextTick(Ho,t);return}Go(t,r,Uo);continue}if(r===0){if(e===0&&t[v].bufLen===0)return;Sr(t,()=>{t.destroyed||(qo(t),Wo(t))});return}ue(t,new Error("overwritten"));return}}function Md(t){let e=this.stream.deref();if(e===void 0){this.exited=!0,this.terminate();return}if(t?.code!=null)switch(t.code){case"READY":this.stream=new jd(e),Sr(e,()=>{e[v].ready=!0,e.emit("ready")});break;case"ERROR":ue(e,t.err);break;case"EVENT":Array.isArray(t.args)?e.emit(t.name,...t.args):e.emit(t.name,t.args);break;case"FLUSHED":{if(t.context!=="thread-stream"){ue(e,new Error("this should not happen: "+t.code));break}let r=e[v].flushCallbacks.get(t.id);r&&(e[v].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:ue(e,new Error("this should not happen: "+t.code))}}function Vo(t){let e=this.stream.deref();e!==void 0&&(Bo.unregister(e),e.worker.exited=!0,e.worker.off("exit",Vo),ue(e,t!==0?new Error("the worker thread exited"):null))}var Hs=class extends kd{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[v]={},this[v].stateBuf=new SharedArrayBuffer(128),this[v].state=new Int32Array(this[v].stateBuf),this[v].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[v].data=Buffer.from(this[v].dataBuf),this[v].sync=e.sync||!1,this[v].ending=!1,this[v].ended=!1,this[v].needDrain=!1,this[v].destroyed=!1,this[v].flushing=!1,this[v].ready=!1,this[v].finished=!1,this[v].errored=null,this[v].closed=!1,this[v].buf=[],this[v].bufHead=0,this[v].bufLen=0,this[v].flushCallbacks=new Map,this[v].nextFlushId=0,this.worker=Pd(this,e),this.on("message",(r,s)=>{this.worker.postMessage(r,s)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[v].destroyed)return Ws(this,new Error("the worker has exited")),!1;if(this[v].ending)return Ws(this,new Error("the worker is ending")),!1;if(this[v].flushing&&this[v].bufLen+r.length>=Rd)try{Bs(this),this[v].flushing=!0}catch(s){return ue(this,s),!1}if(this[v].buf.push(r),this[v].bufLen+=r.length,this[v].sync)try{return Bs(this),!0}catch(s){return ue(this,s),!1}return this[v].flushing||(this[v].flushing=!0,setImmediate(Wo,this)),this[v].needDrain=this[v].data.length-this[v].bufLen-Atomics.load(this[v].state,Ie)<=0,!this[v].needDrain}end(){this[v].destroyed||(this[v].ending=!0,zs(this))}flush(e){e=typeof e=="function"?e:Uo,zo(this,r=>{if(r){process.nextTick(e,r);return}Ko(this,e)})}flushSync(){this[v].destroyed||(Bs(this),Jo(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[v].ready}get destroyed(){return this[v].destroyed}get closed(){return this[v].closed}get writable(){return!this[v].destroyed&&!this[v].ending}get writableEnded(){return this[v].ending}get writableFinished(){return this[v].finished}get writableNeedDrain(){return this[v].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[v].errored}};function zo(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].sync&&(t[v].flushing||t[v].bufLen>0)){setImmediate(zo,t,e);return}Sr(t,e)}function Sr(t,e){let r=Atomics.load(t[v].state,Ie);Ad(t[v].state,Qe,r,1/0,(s,n)=>{if(s){ue(t,s),e(s);return}if(n!=="ok"){Sr(t,e);return}e()})}function Ko(t,e){if(t[v].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[v].ready){let s=()=>{i(),Ko(t,e)},n=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",s),t.off("close",n)};t.once("ready",s),t.once("close",n);return}let r=++t[v].nextFlushId;t[v].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(s){t[v].flushCallbacks.delete(r),ue(t,s),process.nextTick(e,s)}}function Fd(t,e){let r=t[v].flushCallbacks;if(r.size===0)return;let s=e||new Error("the worker has exited");for(let n of r.values())process.nextTick(n,s);r.clear()}function Ws(t,e){setImmediate(()=>{t.emit("error",e)})}function ue(t,e){t[v].destroyed||(t[v].destroyed=!0,Fd(t,e),e&&(t[v].errored=e,Ws(t,e)),t.worker.exited?setImmediate(()=>{t[v].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[v].closed=!0,t.emit("close")}))}function Go(t,e,r){let n=Atomics.load(t[v].state,Ie),i=e;for(;i>0&&t[v].bufLen!==0;){let o=t[v].bufHead,a=t[v].buf[o];if(a.length<=i){a.copy(t[v].data,n),n+=a.length,i-=a.length,t[v].bufLen-=a.length,t[v].bufHead=o+1,t[v].bufHead===t[v].buf.length?(t[v].buf.length=0,t[v].bufHead=0):t[v].bufHead>=1024&&t[v].bufHead*2>=t[v].buf.length&&(t[v].buf.splice(0,t[v].bufHead),t[v].bufHead=0);continue}a.copy(t[v].data,n,0,i),t[v].buf[o]=a.subarray(i),t[v].bufLen-=i,n+=i,i=0}return Vs(t,()=>{Atomics.store(t[v].state,Ie,n)}),r(),!0}function zs(t){if(!(t[v].ended||!t[v].ending||t[v].flushing)){t[v].ended=!0;try{t.flushSync();let e=Atomics.load(t[v].state,Qe);Vs(t,()=>{Atomics.store(t[v].state,Ie,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[v].state,Qe,e,1e3),e=Atomics.load(t[v].state,Qe),e===-2){ue(t,new Error("end() failed"));return}if(++r===10){ue(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[v].finished=!0,t.emit("finish")})}catch(e){ue(t,e)}}}function Bs(t){let e=()=>{t[v].ending?zs(t):t[v].needDrain&&process.nextTick(Ho,t)};for(t[v].flushing=!1;t[v].bufLen!==0;){let r=Atomics.load(t[v].state,Ie),s=t[v].data.length-r;if(s===0){Jo(t),qo(t);continue}else if(s<0)throw new Error("overwritten");Go(t,s,e)}}function Jo(t){if(t[v].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[v].state,Ie),r=0;for(;;){let s=Atomics.load(t[v].state,Qe);if(s===-2)throw Error("_flushSync failed");if(s!==e)Atomics.wait(t[v].state,Qe,s,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Xo.exports=Hs});var Js=P((Vw,ea)=>{"use strict";var{createRequire:Ld}=require("module"),{existsSync:Dd}=require("node:fs"),Nd=Is(),{join:Ks,isAbsolute:Zo,sep:Ud}=require("node:path"),{fileURLToPath:qd}=require("node:url"),Bd=Ls(),Gs=Us(),Hd=Yo();function Wd(t){Gs.register(t,Jd),Gs.registerBeforeExit(t,Xd),t.on("close",function(){Gs.unregister(t)})}function Vd(){let t=process.execArgv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--import"||r==="--require"||r==="-r"||r.startsWith("--import=")||r.startsWith("--require=")||r.startsWith("-r="))return!0}return!1}function zd(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],s=!1;for(let n=0;n<e.length;n++){let i=e[n];if(i==="--require"||i==="-r"||i==="--import"){let o=e[n+1];if(o&&Qo(o)){s=!0,n++;continue}r.push(i),o&&(r.push(o),n++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(Qo(o)){s=!0;continue}}r.push(i)}return s?r.join(" "):t}function Qo(t){let e=Kd(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=qd(r)}catch{return!1}return Zo(r)&&!Dd(r)}function Kd(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Gd(t,e,r,s,n){if(!r.execArgv&&Vd()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=zd(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:n};let i=new Hd({filename:t,workerData:e,workerOpts:r,sync:s});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&Wd(i)}function a(){i.closed||(i.flushSync(),Bd(100),i.end())}return i}function Jd(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Xd(t){t.flushSync()}function Yd(t){let{pipeline:e,targets:r,levels:s,dedupe:n,worker:i={},caller:o=Nd(),sync:a=!1}=t,l={...t.options},c=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||Ks(__dirname,"worker.js"),l.targets=r.filter(f=>f.target).map(f=>({...f,target:h(f.target)})),l.pipelines=r.filter(f=>f.pipeline).map(f=>f.pipeline.map(m=>({...m,level:f.level,target:h(m.target)})))):e&&(d=u["pino-worker"]||Ks(__dirname,"worker.js"),l.pipelines=[e.map(f=>({...f,target:h(f.target)}))]),s&&(l.levels=s),n&&(l.dedupe=n),l.pinoWillSendConfig=!0;let p=r||e?"pino.transport":d;return Gd(h(d),l,i,a,p);function h(f){if(f=u[f]||f,Zo(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return Ks(__dirname,"..","file.js");let m;for(let g of c)try{let y=g==="node:repl"?process.cwd()+Ud:g;m=Ld(y).resolve(f);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${f}"`);return m}}ea.exports=Yd});var kr=P((zw,pa)=>{"use strict";var Qd=require("node:diagnostics_channel"),ta=So(),{mapHttpRequest:Zd,mapHttpResponse:ep}=Rs(),Ys=Eo(),ra=Us(),{lsCacheSym:tp,chindingsSym:aa,writeSym:sa,serializersSym:la,formatOptsSym:na,endSym:rp,stringifiersSym:ca,stringifySym:ua,stringifySafeSym:Qs,wildcardFirstSym:fa,nestedKeySym:sp,formattersSym:da,messageKeySym:np,errorKeySym:ip,nestedKeyStrSym:op,msgPrefixSym:vr}=pt(),{isMainThread:ap}=require("worker_threads"),lp=Js(),[cp]=process.versions.node.split(".").map(t=>Number(t)),ia=Qd.tracingChannel("pino_asJson"),Xs=cp>=25?t=>JSON.stringify(t):fp;function mt(){}function up(t,e){if(!e)return r;return function(...n){e.call(this,n,r,t)};function r(s,...n){if(typeof s=="object"){let i=s;s!==null&&(s.method&&s.headers&&s.socket?s=Zd(s):typeof s.setHeader=="function"&&(s=ep(s)));let o;i===null&&n.length===0?o=[null]:(i=n.shift(),o=n),typeof this[vr]=="string"&&i!==void 0&&i!==null&&(i=this[vr]+i),this[sa](s,ta(i,o,this[na]),t)}else{let i=s===void 0?n.shift():s;typeof this[vr]=="string"&&i!==void 0&&i!==null&&(i=this[vr]+i),this[sa](null,ta(i,n,this[na]),t)}}}function fp(t){let e="",r=0,s=!1,n=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&n>=32;o++)n=t.charCodeAt(o),(n===34||n===92)&&(e+=t.slice(r,o)+"\\",r=o,s=!0);return s?e+=t.slice(r):e=t,n<32?JSON.stringify(t):'"'+e+'"'}function dp(t,e,r,s){if(ia.hasSubscribers===!1)return oa.call(this,t,e,r,s);let n={instance:this,arguments};return ia.traceSync(oa,n,this,t,e,r,s)}function oa(t,e,r,s){let n=this[ua],i=this[Qs],o=this[ca],a=this[rp],l=this[aa],c=this[la],u=this[da],d=this[np],p=this[ip],h=this[tp][r]+s;h=h+l;let f;u.log&&(t=u.log(t));let m=o[fa],g="";for(let b in t)if(f=t[b],Object.prototype.hasOwnProperty.call(t,b)&&f!==void 0){c[b]?f=c[b](f):b===p&&c.err&&(f=c.err(f));let w=o[b]||m;switch(typeof f){case"undefined":case"function":continue;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":w&&(f=w(f));break;case"string":f=(w||Xs)(f);break;default:f=(w||n)(f,i)}if(f===void 0)continue;let S=Xs(b);g+=","+S+":"+f}let y="";if(e!==void 0){f=c[d]?c[d](e):e;let b=o[d]||m;switch(typeof f){case"function":break;case"number":Number.isFinite(f)===!1&&(f=null);case"boolean":b&&(f=b(f)),y=',"'+d+'":'+f;break;case"string":f=(b||Xs)(f),y=',"'+d+'":'+f;break;default:f=(b||n)(f,i),y=',"'+d+'":'+f}}return this[sp]&&g?h+this[op]+g.slice(1)+"}"+y+a:h+g+y+a}function pp(t,e){let r,s=t[aa],n=t[ua],i=t[Qs],o=t[ca],a=o[fa],l=t[la],c=t[da].bindings;e=c(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||n)(r,i),r===void 0)continue;s+=',"'+u+'":'+r}return s}function hp(t){return t.write!==t.constructor.prototype.write}function _r(t){let e=new Ys(t);return e.on("error",r),!t.sync&&ap&&(ra.register(e,mp),e.on("close",function(){ra.unregister(e)})),e;function r(s){if(s.code==="EPIPE"){e.write=mt,e.end=mt,e.flushSync=mt,e.destroy=mt;return}e.removeListener("error",r),e.emit("error",s)}}function mp(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function gp(t){return function(r,s,n={},i){if(typeof n=="string")i=_r({dest:n}),n={};else if(typeof i=="string"){if(n&&n.transport)throw Error("only one of option.transport or stream can be specified");i=_r({dest:i})}else if(n instanceof Ys||n.writable||n._writableState)i=n,n={};else if(n.transport){if(n.transport instanceof Ys||n.transport.writable||n.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(n.transport.targets&&n.transport.targets.length&&n.formatters&&typeof n.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;n.customLevels&&(l=n.useOnlyCustomLevels?n.customLevels:Object.assign({},n.levels,n.customLevels)),i=lp({caller:s,...n.transport,levels:l})}if(n=Object.assign({},t,n),n.serializers=Object.assign({},t.serializers,n.serializers),n.formatters=Object.assign({},t.formatters,n.formatters),n.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=n;return o===!1&&(n.level="silent"),a||(n.onChild=mt),i||(hp(process.stdout)?i=process.stdout:i=_r({fd:process.stdout.fd||1})),{opts:n,stream:i}}}function yp(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[Qs])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function wp(t,e,r){return{level:t,bindings:e,log:r}}function bp(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}pa.exports={noop:mt,buildSafeSonicBoom:_r,asChindings:pp,asJson:dp,genLog:up,createArgsNormalizer:gp,stringify:yp,buildFormatters:wp,normalizeDestFileDescriptor:bp}});var Tr=P((Kw,ha)=>{var xp={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Sp={ASC:"ASC",DESC:"DESC"};ha.exports={DEFAULT_LEVELS:xp,SORTING_ORDER:Sp}});var tn=P((Gw,wa)=>{"use strict";var{lsCacheSym:vp,levelValSym:Zs,useOnlyCustomLevelsSym:_p,streamSym:kp,formattersSym:Tp,hooksSym:Cp,levelCompSym:ma}=pt(),{noop:$p,genLog:Ze}=kr(),{DEFAULT_LEVELS:Te,SORTING_ORDER:ga}=Tr(),ya={fatal:t=>{let e=Ze(Te.fatal,t);return function(...r){let s=this[kp];if(e.call(this,...r),typeof s.flushSync=="function")try{s.flushSync()}catch{}}},error:t=>Ze(Te.error,t),warn:t=>Ze(Te.warn,t),info:t=>Ze(Te.info,t),debug:t=>Ze(Te.debug,t),trace:t=>Ze(Te.trace,t)},en=Object.keys(Te).reduce((t,e)=>(t[Te[e]]=e,t),{}),Ap=Object.keys(en).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function Ep(t){let e=t[Tp].level,{labels:r}=t.levels,s={};for(let n in r){let i=e(r[n],Number(n));s[n]=JSON.stringify(i).slice(0,-1)}return t[vp]=s,t}function Op(t,e){if(e)return!1;switch(t){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Rp(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let s=this[Zs],n=this[Zs]=r[t],i=this[_p],o=this[ma],a=this[Cp].logMethod;for(let l in r){if(o(r[l],n)===!1){this[l]=$p;continue}this[l]=Op(l,i)?ya[l](a):Ze(r[l],a)}this.emit("level-change",t,n,e[s],s,this)}function Ip(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function jp(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[ma](r,this[Zs])}function Pp(t,e,r){return t===ga.DESC?e<=r:e>=r}function Mp(t){return typeof t=="string"?Pp.bind(null,t):t}function Fp(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,s=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:en,r),n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:Te,t);return{labels:s,values:n}}function Lp(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(en).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:Te,e);if(!(t in s))throw Error(`default level:${t} must be included in custom levels`)}function Dp(t,e){let{labels:r,values:s}=t;for(let n in e){if(n in s)throw Error("levels cannot be overridden");if(e[n]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Np(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(ga).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}wa.exports={initialLsCache:Ap,genLsCache:Ep,levelMethods:ya,getLevel:Ip,setLevel:Rp,isLevelEnabled:jp,mappings:Fp,assertNoLevelCollisions:Dp,assertDefaultLevelFound:Lp,genLevelComparison:Mp,assertLevelComparison:Np}});var rn=P((Jw,ba)=>{"use strict";ba.exports={version:"10.3.1"}});var $a=P((Yw,Ca)=>{"use strict";var{EventEmitter:Up}=require("node:events"),{lsCacheSym:qp,levelValSym:Bp,setLevelSym:nn,getLevelSym:xa,chindingsSym:$r,mixinSym:Hp,asJsonSym:va,writeSym:Wp,mixinMergeStrategySym:Vp,timeSym:zp,timeSliceIndexSym:Kp,streamSym:_a,serializersSym:et,formattersSym:Dt,errorKeySym:Gp,messageKeySym:Jp,useOnlyCustomLevelsSym:Xp,needsMetadataGsym:Yp,redactFmtSym:Qp,stringifySym:Zp,formatOptsSym:eh,stringifiersSym:th,msgPrefixSym:on,hooksSym:rh}=pt(),{getLevel:sh,setLevel:nh,isLevelEnabled:ih,mappings:oh,initialLsCache:ah,genLsCache:lh,assertNoLevelCollisions:ch}=tn(),{asChindings:an,asJson:uh,buildFormatters:sn,stringify:Sa,noop:ka}=kr(),{version:fh}=rn(),dh=Ms(),ph=class{},Ta={constructor:ph,child:hh,bindings:mh,setBindings:gh,flush:bh,isLevelEnabled:ih,version:fh,get level(){return this[xa]()},set level(t){this[nn](t)},get levelVal(){return this[Bp]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[on]},get[Symbol.toStringTag](){return"Pino"},[qp]:ah,[Wp]:wh,[va]:uh,[xa]:sh,[nn]:nh};Object.setPrototypeOf(Ta,Up.prototype);Ca.exports=function(){return Object.create(Ta)};var Cr=t=>t;function hh(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[et],s=this[Dt],n=Object.create(this);if(e==null)return n[Dt].bindings!==Cr&&(n[Dt]=sn(s.level,Cr,s.log)),n[$r]=an(n,t),this.onChild!==ka&&this.onChild(n),n;if(e.hasOwnProperty("serializers")===!0){n[et]=Object.create(null);for(let c in r)n[et][c]=r[c];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let c=a[i];n[et][c]=r[c]}for(let c in e.serializers)n[et][c]=e.serializers[c];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let c=l[o];n[et][c]=e.serializers[c]}}else n[et]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:c}=e.formatters;n[Dt]=sn(a||s.level,l||Cr,c||s.log)}else n[Dt]=sn(s.level,Cr,s.log);if(e.hasOwnProperty("customLevels")===!0&&(ch(this.levels,e.customLevels),n.levels=oh(e.customLevels,n[Xp]),lh(n)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){n.redact=e.redact;let a=dh(n.redact,Sa),l={stringify:a[Qp]};n[Zp]=Sa,n[th]=a,n[eh]=l}if(typeof e.msgPrefix=="string"&&(n[on]=(this[on]||"")+e.msgPrefix),n[$r]=an(n,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;n[nn](a)}return this.onChild(n),n}function mh(){let e=`{${this[$r].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function gh(t){let e=an(this,t);this[$r]=e}function yh(t,e){return Object.assign(e,t)}function wh(t,e,r){let s=this[zp](),n=this[Hp],i=this[Gp],o=this[Jp],a=this[Vp]||yh,l,c=this[rh].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),n&&(l=a(l,n(l,r,this)));let u=this[va](l,e,r,s),d=this[_a];d[Yp]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=s.slice(this[Kp]),d.lastLogger=this),d.write(c?c(u):u)}function bh(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[_a];typeof e.flush=="function"?e.flush(t||ka):t&&t()}});var Ra=P((fn,Oa)=>{"use strict";var{hasOwnProperty:Nt}=Object.prototype,rt=un();rt.configure=un;rt.stringify=rt;rt.default=rt;fn.stringify=rt;fn.configure=un;Oa.exports=rt;var xh=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function Ue(t){return t.length<5e3&&!xh.test(t)?`"${t}"`:JSON.stringify(t)}function ln(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let s=t[r],n=r;for(;n!==0&&t[n-1]>s;)t[n]=t[n-1],n--;t[n]=s}return t}var Sh=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function cn(t){return Sh.call(t)!==void 0&&t.length!==0}function Aa(t,e,r){t.length<r&&(r=t.length);let s=e===","?"":" ",n=`"0":${s}${t[0]}`;for(let i=1;i<r;i++)n+=`${e}"${i}":${s}${t[i]}`;return n}function vh(t){if(Nt.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function _h(t){let e;if(Nt.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function kh(t,e){let r;if(Nt.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ea(t,e){let r;if(Nt.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function tt(t){return t===1?"1 item":`${t} items`}function Th(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function Ch(t){if(Nt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let s=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(s+=` (${r.toString()})`),new Error(s)}}}function un(t){t={...t};let e=Ch(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=vh(t),s=kh(t,"bigint"),n=_h(t),i=typeof n=="function"?n:void 0,o=Ea(t,"maximumDepth"),a=Ea(t,"maximumBreadth");function l(h,f,m,g,y,b){let w=f[h];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(h)),w=g.call(f,h,w),typeof w){case"string":return Ue(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return r;let S="",_=",",C=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(w),y!==""&&(b+=y,S+=`
26
26
  ${b}`,_=`,
27
- ${b}`);let N=Math.min(w.length,a),H=0;for(;H<N-1;H++){let K=l(String(H),w,m,g,y,b);S+=K!==void 0?K:"null",S+=_}let Q=l(String(H),w,m,g,y,b);if(S+=Q!==void 0?Q:"null",w.length-1>a){let K=w.length-a-1;S+=`${_}"... ${et(K)} not stringified"`}return y!==""&&(S+=`
28
- ${C}`),m.pop(),`[${S}]`}let A=Object.keys(w),E=A.length;if(E===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",M="";y!==""&&(b+=y,_=`,
29
- ${b}`,$=" ");let U=Math.min(E,a);n&&!an(w)&&(A=on(A,i)),m.push(w);for(let N=0;N<U;N++){let H=A[N],Q=l(H,w,m,g,y,b);Q!==void 0&&(S+=`${M}${Ue(H)}:${$}${Q}`,M=_)}if(E>a){let N=E-a;S+=`${M}"...":${$}"${et(N)} not stringified"`,M=_}return y!==""&&M.length>1&&(S=`
27
+ ${b}`);let N=Math.min(w.length,a),H=0;for(;H<N-1;H++){let K=l(String(H),w,m,g,y,b);S+=K!==void 0?K:"null",S+=_}let Q=l(String(H),w,m,g,y,b);if(S+=Q!==void 0?Q:"null",w.length-1>a){let K=w.length-a-1;S+=`${_}"... ${tt(K)} not stringified"`}return y!==""&&(S+=`
28
+ ${C}`),m.pop(),`[${S}]`}let E=Object.keys(w),A=E.length;if(A===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",M="";y!==""&&(b+=y,_=`,
29
+ ${b}`,$=" ");let U=Math.min(A,a);n&&!cn(w)&&(E=ln(E,i)),m.push(w);for(let N=0;N<U;N++){let H=E[N],Q=l(H,w,m,g,y,b);Q!==void 0&&(S+=`${M}${Ue(H)}:${$}${Q}`,M=_)}if(A>a){let N=A-a;S+=`${M}"...":${$}"${tt(N)} not stringified"`,M=_}return y!==""&&M.length>1&&(S=`
30
30
  ${b}${S}
31
31
  ${C}`),m.pop(),`{${S}}`}case"number":return isFinite(w)?String(w):e?e(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(w);default:return e?e(w):void 0}}function c(h,f,m,g,y,b){switch(typeof f=="object"&&f!==null&&typeof f.toJSON=="function"&&(f=f.toJSON(h)),typeof f){case"string":return Ue(f);case"object":{if(f===null)return"null";if(m.indexOf(f)!==-1)return r;let w=b,S="",_=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(f),y!==""&&(b+=y,S+=`
32
32
  ${b}`,_=`,
33
- ${b}`);let E=Math.min(f.length,a),$=0;for(;$<E-1;$++){let U=c(String($),f[$],m,g,y,b);S+=U!==void 0?U:"null",S+=_}let M=c(String($),f[$],m,g,y,b);if(S+=M!==void 0?M:"null",f.length-1>a){let U=f.length-a-1;S+=`${_}"... ${et(U)} not stringified"`}return y!==""&&(S+=`
33
+ ${b}`);let A=Math.min(f.length,a),$=0;for(;$<A-1;$++){let U=c(String($),f[$],m,g,y,b);S+=U!==void 0?U:"null",S+=_}let M=c(String($),f[$],m,g,y,b);if(S+=M!==void 0?M:"null",f.length-1>a){let U=f.length-a-1;S+=`${_}"... ${tt(U)} not stringified"`}return y!==""&&(S+=`
34
34
  ${w}`),m.pop(),`[${S}]`}m.push(f);let C="";y!==""&&(b+=y,_=`,
35
- ${b}`,C=" ");let A="";for(let E of g){let $=c(E,f[E],m,g,y,b);$!==void 0&&(S+=`${A}${Ue(E)}:${C}${$}`,A=_)}return y!==""&&A.length>1&&(S=`
35
+ ${b}`,C=" ");let E="";for(let A of g){let $=c(A,f[A],m,g,y,b);$!==void 0&&(S+=`${E}${Ue(A)}:${C}${$}`,E=_)}return y!==""&&E.length>1&&(S=`
36
36
  ${b}${S}
37
37
  ${w}`),m.pop(),`{${S}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(f);default:return e?e(f):void 0}}function u(h,f,m,g,y){switch(typeof f){case"string":return Ue(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(h),typeof f!="object")return u(h,f,m,g,y);if(f===null)return"null"}if(m.indexOf(f)!==-1)return r;let b=y;if(Array.isArray(f)){if(f.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(f),y+=g;let $=`
38
38
  ${y}`,M=`,
39
- ${y}`,U=Math.min(f.length,a),N=0;for(;N<U-1;N++){let Q=u(String(N),f[N],m,g,y);$+=Q!==void 0?Q:"null",$+=M}let H=u(String(N),f[N],m,g,y);if($+=H!==void 0?H:"null",f.length-1>a){let Q=f.length-a-1;$+=`${M}"... ${et(Q)} not stringified"`}return $+=`
39
+ ${y}`,U=Math.min(f.length,a),N=0;for(;N<U-1;N++){let Q=u(String(N),f[N],m,g,y);$+=Q!==void 0?Q:"null",$+=M}let H=u(String(N),f[N],m,g,y);if($+=H!==void 0?H:"null",f.length-1>a){let Q=f.length-a-1;$+=`${M}"... ${tt(Q)} not stringified"`}return $+=`
40
40
  ${b}`,m.pop(),`[${$}]`}let w=Object.keys(f),S=w.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';y+=g;let _=`,
41
- ${y}`,C="",A="",E=Math.min(S,a);an(f)&&(C+=$a(f,_,a),w=w.slice(f.length),E-=f.length,A=_),n&&(w=on(w,i)),m.push(f);for(let $=0;$<E;$++){let M=w[$],U=u(M,f[M],m,g,y);U!==void 0&&(C+=`${A}${Ue(M)}: ${U}`,A=_)}if(S>a){let $=S-a;C+=`${A}"...": "${et($)} not stringified"`,A=_}return A!==""&&(C=`
41
+ ${y}`,C="",E="",A=Math.min(S,a);cn(f)&&(C+=Aa(f,_,a),w=w.slice(f.length),A-=f.length,E=_),n&&(w=ln(w,i)),m.push(f);for(let $=0;$<A;$++){let M=w[$],U=u(M,f[M],m,g,y);U!==void 0&&(C+=`${E}${Ue(M)}: ${U}`,E=_)}if(S>a){let $=S-a;C+=`${E}"...": "${tt($)} not stringified"`,E=_}return E!==""&&(C=`
42
42
  ${y}${C}
43
- ${b}`),m.pop(),`{${C}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(f);default:return e?e(f):void 0}}function d(h,f,m){switch(typeof f){case"string":return Ue(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(h),typeof f!="object")return d(h,f,m);if(f===null)return"null"}if(m.indexOf(f)!==-1)return r;let g="",y=f.length!==void 0;if(y&&Array.isArray(f)){if(f.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(f);let C=Math.min(f.length,a),A=0;for(;A<C-1;A++){let $=d(String(A),f[A],m);g+=$!==void 0?$:"null",g+=","}let E=d(String(A),f[A],m);if(g+=E!==void 0?E:"null",f.length-1>a){let $=f.length-a-1;g+=`,"... ${et($)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(f),w=b.length;if(w===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",_=Math.min(w,a);y&&an(f)&&(g+=$a(f,",",a),b=b.slice(f.length),_-=f.length,S=","),n&&(b=on(b,i)),m.push(f);for(let C=0;C<_;C++){let A=b[C],E=d(A,f[A],m);E!==void 0&&(g+=`${S}${Ue(A)}:${E}`,S=",")}if(w>a){let C=w-a;g+=`${S}"...":"${et(C)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(f);default:return e?e(f):void 0}}function p(h,f,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),f!=null){if(typeof f=="function")return l("",{"":h},[],f,g,"");if(Array.isArray(f))return c("",h,[],Th(f),g,"")}if(g.length!==0)return u("",h,[],g,"")}return d("",h,[])}return p}});var Pa=P((Yw,ja)=>{"use strict";var un=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Ia}=kr(),$h=Ia.info;function Eh(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Ia);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let s={write:n,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:u,[un]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,s):a.call(s,t),t=null,s;function n(d){let p,h=this.lastLevel,{streams:f}=this,m=0,g;for(let y=Ah(f.length,e.dedupe);Rh(y,f.length,e.dedupe);y=Oh(y,e.dedupe))if(p=f[y],p.level<=h){if(m!==0&&m!==p.level)break;if(g=p.stream,g[un]){let{lastTime:b,lastMsg:w,lastObj:S,lastLogger:_}=this;g.lastLevel=h,g.lastTime=b,g.lastMsg=w,g.lastObj=S,g.lastLogger=_}g.write(d),e.dedupe&&(m=p.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return s;let p=typeof d.write=="function"||d.stream,h=d.write?d:d.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:m}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=m[d.level]:typeof d.level=="number"?g=d.level:g=$h;let y={stream:h,level:g,levelVal:void 0,id:++s.lastId};return f.unshift(y),f.sort(Ra),this.minLevel=f[0].level,s}function l(d){let{streams:p}=this,h=p.findIndex(f=>f.id===d);return h>=0&&(p.splice(h,1),p.sort(Ra),this.minLevel=p.length>0?p[0].level:-1),s}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:d,stream:this.streams[h].stream};return{write:n,add:a,remove:l,minLevel:d,streams:p,clone:u,emit:i,flushSync:o,[un]:!0}}}function Ra(t,e){return t.level-e.level}function Ah(t,e){return e?t-1:0}function Oh(t,e){return e?t-1:t+1}function Rh(t,e,r){return r?t>=0:t<e}ja.exports=Eh});var Ga=P((Xw,fe)=>{"use strict";var Ih=require("node:os"),Ba=As(),jh=Os(),Ph=js(),Ha=wo(),Mh=Ca(),Wa=dt(),{configure:Fh}=Oa(),{assertDefaultLevelFound:Lh,mappings:Va,genLsCache:Dh,genLevelComparison:Nh,assertLevelComparison:Uh}=Zs(),{DEFAULT_LEVELS:za,SORTING_ORDER:qh}=kr(),{createArgsNormalizer:Bh,asChindings:Hh,buildSafeSonicBoom:Ma,buildFormatters:Wh,stringify:fn,normalizeDestFileDescriptor:Fa,noop:Vh}=_r(),{version:zh}=en(),{chindingsSym:La,redactFmtSym:Kh,serializersSym:Da,timeSym:Gh,timeSliceIndexSym:Jh,streamSym:Yh,stringifySym:Na,stringifySafeSym:dn,stringifiersSym:Ua,setLevelSym:Xh,endSym:Qh,formatOptsSym:Zh,messageKeySym:em,errorKeySym:tm,nestedKeySym:rm,mixinSym:sm,levelCompSym:nm,useOnlyCustomLevelsSym:im,formattersSym:qa,hooksSym:om,nestedKeyStrSym:am,mixinMergeStrategySym:lm,msgPrefixSym:cm}=Wa,{epochTime:Ka,nullTime:um}=Ha,{pid:fm}=process,dm=Ih.hostname(),pm=Ba.err,hm={level:"info",levelComparison:qh.ASC,levels:za,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:fm,hostname:dm},serializers:Object.assign(Object.create(null),{err:pm}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ka,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},mm=Bh(hm),gm=Object.assign(Object.create(null),Ba);function pn(...t){let e={},{opts:r,stream:s}=mm(e,jh(),...t);r.level&&typeof r.level=="string"&&za[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:n,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:u,base:d,name:p,level:h,customLevels:f,levelComparison:m,mixin:g,mixinMergeStrategy:y,useOnlyCustomLevels:b,formatters:w,hooks:S,depthLimit:_,edgeLimit:C,onChild:A,msgPrefix:E}=r,$=Fh({maximumDepth:_,maximumBreadth:C}),M=Wh(w.level,w.bindings,w.log),U=fn.bind({[dn]:$}),N=n?Ph(n,U):{},H=n?{stringify:N[Kh]}:{stringify:U},Q="}"+(i?`\r
43
+ ${b}`),m.pop(),`{${C}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(f);default:return e?e(f):void 0}}function d(h,f,m){switch(typeof f){case"string":return Ue(f);case"object":{if(f===null)return"null";if(typeof f.toJSON=="function"){if(f=f.toJSON(h),typeof f!="object")return d(h,f,m);if(f===null)return"null"}if(m.indexOf(f)!==-1)return r;let g="",y=f.length!==void 0;if(y&&Array.isArray(f)){if(f.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(f);let C=Math.min(f.length,a),E=0;for(;E<C-1;E++){let $=d(String(E),f[E],m);g+=$!==void 0?$:"null",g+=","}let A=d(String(E),f[E],m);if(g+=A!==void 0?A:"null",f.length-1>a){let $=f.length-a-1;g+=`,"... ${tt($)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(f),w=b.length;if(w===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",_=Math.min(w,a);y&&cn(f)&&(g+=Aa(f,",",a),b=b.slice(f.length),_-=f.length,S=","),n&&(b=ln(b,i)),m.push(f);for(let C=0;C<_;C++){let E=b[C],A=d(E,f[E],m);A!==void 0&&(g+=`${S}${Ue(E)}:${A}`,S=",")}if(w>a){let C=w-a;g+=`${S}"...":"${tt(C)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(s)return String(f);default:return e?e(f):void 0}}function p(h,f,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),f!=null){if(typeof f=="function")return l("",{"":h},[],f,g,"");if(Array.isArray(f))return c("",h,[],Th(f),g,"")}if(g.length!==0)return u("",h,[],g,"")}return d("",h,[])}return p}});var Ma=P((Qw,Pa)=>{"use strict";var dn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:ja}=Tr(),$h=ja.info;function Ah(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(ja);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let s={write:n,add:a,remove:l,emit:i,flushSync:o,end:c,minLevel:0,lastId:0,streams:[],clone:u,[dn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,s):a.call(s,t),t=null,s;function n(d){let p,h=this.lastLevel,{streams:f}=this,m=0,g;for(let y=Eh(f.length,e.dedupe);Rh(y,f.length,e.dedupe);y=Oh(y,e.dedupe))if(p=f[y],p.level<=h){if(m!==0&&m!==p.level)break;if(g=p.stream,g[dn]){let{lastTime:b,lastMsg:w,lastObj:S,lastLogger:_}=this;g.lastLevel=h,g.lastTime=b,g.lastMsg=w,g.lastObj=S,g.lastLogger=_}g.write(d),e.dedupe&&(m=p.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return s;let p=typeof d.write=="function"||d.stream,h=d.write?d:d.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:f,streamLevels:m}=this,g;typeof d.levelVal=="number"?g=d.levelVal:typeof d.level=="string"?g=m[d.level]:typeof d.level=="number"?g=d.level:g=$h;let y={stream:h,level:g,levelVal:void 0,id:++s.lastId};return f.unshift(y),f.sort(Ia),this.minLevel=f[0].level,s}function l(d){let{streams:p}=this,h=p.findIndex(f=>f.id===d);return h>=0&&(p.splice(h,1),p.sort(Ia),this.minLevel=p.length>0?p[0].level:-1),s}function c(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let p=new Array(this.streams.length);for(let h=0;h<p.length;h++)p[h]={level:d,stream:this.streams[h].stream};return{write:n,add:a,remove:l,minLevel:d,streams:p,clone:u,emit:i,flushSync:o,[dn]:!0}}}function Ia(t,e){return t.level-e.level}function Eh(t,e){return e?t-1:0}function Oh(t,e){return e?t-1:t+1}function Rh(t,e,r){return r?t>=0:t<e}Pa.exports=Ah});var Ja=P((Zw,fe)=>{"use strict";var Ih=require("node:os"),Ha=Rs(),jh=Is(),Ph=Ms(),Wa=bo(),Mh=$a(),Va=pt(),{configure:Fh}=Ra(),{assertDefaultLevelFound:Lh,mappings:za,genLsCache:Dh,genLevelComparison:Nh,assertLevelComparison:Uh}=tn(),{DEFAULT_LEVELS:Ka,SORTING_ORDER:qh}=Tr(),{createArgsNormalizer:Bh,asChindings:Hh,buildSafeSonicBoom:Fa,buildFormatters:Wh,stringify:pn,normalizeDestFileDescriptor:La,noop:Vh}=kr(),{version:zh}=rn(),{chindingsSym:Da,redactFmtSym:Kh,serializersSym:Na,timeSym:Gh,timeSliceIndexSym:Jh,streamSym:Xh,stringifySym:Ua,stringifySafeSym:hn,stringifiersSym:qa,setLevelSym:Yh,endSym:Qh,formatOptsSym:Zh,messageKeySym:em,errorKeySym:tm,nestedKeySym:rm,mixinSym:sm,levelCompSym:nm,useOnlyCustomLevelsSym:im,formattersSym:Ba,hooksSym:om,nestedKeyStrSym:am,mixinMergeStrategySym:lm,msgPrefixSym:cm}=Va,{epochTime:Ga,nullTime:um}=Wa,{pid:fm}=process,dm=Ih.hostname(),pm=Ha.err,hm={level:"info",levelComparison:qh.ASC,levels:Ka,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:fm,hostname:dm},serializers:Object.assign(Object.create(null),{err:pm}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Ga,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},mm=Bh(hm),gm=Object.assign(Object.create(null),Ha);function mn(...t){let e={},{opts:r,stream:s}=mm(e,jh(),...t);r.level&&typeof r.level=="string"&&Ka[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:n,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:c,nestedKey:u,base:d,name:p,level:h,customLevels:f,levelComparison:m,mixin:g,mixinMergeStrategy:y,useOnlyCustomLevels:b,formatters:w,hooks:S,depthLimit:_,edgeLimit:C,onChild:E,msgPrefix:A}=r,$=Fh({maximumDepth:_,maximumBreadth:C}),M=Wh(w.level,w.bindings,w.log),U=pn.bind({[hn]:$}),N=n?Ph(n,U):{},H=n?{stringify:N[Kh]}:{stringify:U},Q="}"+(i?`\r
44
44
  `:`
45
- `),K=Hh.bind(null,{[La]:"",[Da]:o,[Ua]:N,[Na]:fn,[dn]:$,[qa]:M}),re="";d!==null&&(p===void 0?re=K(d):re=K(Object.assign({},d,{name:p})));let I=a instanceof Function?a:a?Ka:um,F=I().indexOf(":")+1;if(b&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(E&&typeof E!="string")throw Error(`Unknown msgPrefix type "${typeof E}" - expected "string"`);Lh(h,f,b);let Le=Va(f,b);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:Le,messageKey:l,errorKey:c}}),Uh(m);let ri=Nh(m);return Object.assign(e,{levels:Le,[nm]:ri,[im]:b,[Yh]:s,[Gh]:I,[Jh]:F,[Na]:fn,[dn]:$,[Ua]:N,[Qh]:Q,[Zh]:H,[em]:l,[tm]:c,[rm]:u,[am]:u?`,${JSON.stringify(u)}:{`:"",[Da]:o,[sm]:g,[lm]:y,[La]:re,[qa]:M,[om]:S,silent:Vh,onChild:A,[cm]:E}),Object.setPrototypeOf(e,Mh()),Dh(e),e[Xh](h),e}fe.exports=pn;fe.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Fa(t.dest||process.stdout.fd),Ma(t)):Ma({dest:Fa(t),minLength:0});fe.exports.transport=Ks();fe.exports.multistream=Pa();fe.exports.levels=Va();fe.exports.stdSerializers=gm;fe.exports.stdTimeFunctions=Object.assign({},Ha);fe.exports.symbols=Wa;fe.exports.version=zh;fe.exports.default=pn;fe.exports.pino=pn});var ts=k(require("os")),nr=k(require("fs")),It=k(require("path"));function fu(){let t=[It.resolve(__dirname,"..","package.json"),It.resolve(__dirname,"..","..","package.json"),It.resolve(process.cwd(),"package.json")];for(let e of t)try{if(nr.existsSync(e)){let r=JSON.parse(nr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var rs=fu(),jt=process.stdout.isTTY===!0,ai=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",li=process.stdout.columns||100;jt&&process.stdout.on("resize",()=>{li=process.stdout.columns||100});var Ne=()=>Math.min(Math.max(li-4,56),100);function G(t,e){return!jt||ai?t:`\x1B[${e}m${t}\x1B[0m`}var x={strong:t=>G(t,"1;38;5;255"),muted:t=>G(t,"38;5;241"),dim:t=>G(t,"2;38;5;245"),border:t=>G(t,"38;5;237"),accent:t=>G(t,"38;5;147"),primary:t=>G(t,"38;5;253"),secondary:t=>G(t,"38;5;247"),info:t=>G(t,"38;5;110"),success:t=>G(t,"38;5;114"),warning:t=>G(t,"38;5;179"),error:t=>G(t,"38;5;167"),plan:t=>G(t,"38;5;144"),code:t=>G(t,"38;5;189"),codeLang:t=>G(t,"38;5;110"),linenum:t=>G(t,"38;5;239"),diffAdd:t=>G(t,"38;5;71"),diffDel:t=>G(t,"38;5;131"),link:t=>G(t,"4;38;5;110")};function ve(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function du(t,e){let r=ve(t);return t+" ".repeat(Math.max(0,e-r.length))}function es(t,e=2,r){let s=(r??Ne())-e,n=t.split(/(?<=\s)|(?=\s)/).filter(Boolean),i=[],o="";for(let a of n){let l=ve(o),c=ve(a.trimStart());l.trimEnd().length+1+c.length>s&&l.trim()?(i.push(" ".repeat(e)+o.trimStart()),o=a.trimStart()):o+=a}return o.trim()&&i.push(" ".repeat(e)+o.trimStart()),i.length?i:[""]}function pu(t,e="\u2500"){return x.border(e.repeat(Math.max(0,t)))}function ni(t,e,r){let s=ve(t),n=Math.max(0,Math.floor((r-2-s.length)/2)),i=Math.max(0,r-2-s.length-n);return x.border("\u2502")+" ".repeat(n)+e+" ".repeat(i)+x.border("\u2502")}function sr(t,e,r){let s=ve(t),n=ve(e),i=Math.max(1,r-4-s.length-n.length);return`${x.border("\u2502")} ${t}${" ".repeat(i)}${e} ${x.border("\u2502")}`}function ii(t){return`${x.border("\u2502")}${" ".repeat(t-2)}${x.border("\u2502")}`}function ci(t,e){let r=Math.min(Ne(),76),s=e.replace(ts.homedir(),"~"),n=t.length>42?t.slice(0,40)+"\u2026":t,i=s.length>42?"\u2026"+s.slice(-40):s,o=x.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),a=x.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),l=x.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),c=x.border("\u255E"+"\u2550".repeat(r-2)+"\u2561");return["",o,ii(r),ni(" HABLAS "," "+x.accent("\u25C6")+" "+x.strong("HABLAS")+" ",r),ni("engineering runtime",x.dim("engineering runtime"),r),ii(r),c,sr(x.secondary("model "),x.accent(n),r),sr(x.secondary("workspace"),x.muted(i),r),sr(x.secondary("version "),x.muted("v"+rs),r),l,sr(x.dim("Type naturally \xB7 /help for commands \xB7 Ctrl+C to cancel"),"",r),a,""].join(`
46
- `)}function ui(t){let e=Ne(),r=" "+x.accent("\u25C6")+" "+x.strong("Turn")+" "+x.muted(String(t))+" ",s=" \u25C6 Turn "+t+" ",n=Math.max(0,e-s.length-2);return`
47
- `+x.border("\u2500\u2500")+r+x.border("\u2500".repeat(n))}function ir(){return`
48
- `+x.accent("\u25C6")+" "+x.strong("Hablas")}var hu={Thinking:"\u25CC",Planning:"\u25C8",Inspecting:"\u25CE",Researching:"\u25C9",Editing:"\u25C6",Running:"\u25B6",Fetching:"\u21E9",Downloading:"\u21E9",Memory:"\u25C7",Git:"\u2387",Verifying:"\u25D0",Working:"\u25CF"};function fi(t){let e=hu[t]??"\u25CF";return`
49
- `+x.muted("\u2504")+" "+x.accent(e)+" "+x.secondary(t)+" "+x.muted("\u2504")}var mu={read_file:"\u{1F4C4}",list_dir:"\u{1F4C2}",write_file:"\u270F\uFE0F",edit_file:"\u270F\uFE0F",patch_file:"\u270F\uFE0F",search_and_replace:"\u{1F504}",append_to_file:"\u2795",move_file:"\u{1F69A}",delete_file:"\u{1F5D1}\uFE0F",create_dir:"\u{1F4C1}",search_codebase:"\u{1F50D}",run_command:"\u26A1",execute_code:"\u25B6\uFE0F",web_search:"\u{1F310}",scrape_url:"\u{1F578}\uFE0F",extract_links:"\u{1F517}",download_asset:"\u2B07\uFE0F",detect_bugs:"\u{1F41B}",read_pdf:"\u{1F4CB}",pdf_metadata:"\u{1F4CB}",search_image_candidates:"\u{1F5BC}\uFE0F",inspect_image:"\u{1F50E}",remember:"\u{1F4BE}",recall:"\u{1F9E0}",search_memory:"\u{1F50D}",forget:"\u{1F5D1}\uFE0F",git_status:"\u{1F33F}",git_diff:"\u{1F4DD}",git_log:"\u{1F4DC}",git_branch:"\u{1F33F}"};function di(t,e){let r=mu[t]??"\xB7",s=t.replace(/_/g," "),n=Math.min(Ne()-4,76),i=r+" "+x.secondary(s),o=e?x.dim(e.slice(0,40)):"",a=ve(i)+(o?" "+e.slice(0,40):""),l=Math.max(0,n-2-a.length),c=" "+x.border("\u256D"+"\u2500".repeat(n)+"\u256E"),u=" "+x.border("\u2502")+" "+i+(o?" "+o:"")+" ".repeat(l)+" "+x.border("\u2502");return`
45
+ `),K=Hh.bind(null,{[Da]:"",[Na]:o,[qa]:N,[Ua]:pn,[hn]:$,[Ba]:M}),te="";d!==null&&(p===void 0?te=K(d):te=K(Object.assign({},d,{name:p})));let I=a instanceof Function?a:a?Ga:um,F=I().indexOf(":")+1;if(b&&!f)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if(A&&typeof A!="string")throw Error(`Unknown msgPrefix type "${typeof A}" - expected "string"`);Lh(h,f,b);let ye=za(f,b);typeof s.emit=="function"&&s.emit("message",{code:"PINO_CONFIG",config:{levels:ye,messageKey:l,errorKey:c}}),Uh(m);let It=Nh(m);return Object.assign(e,{levels:ye,[nm]:It,[im]:b,[Xh]:s,[Gh]:I,[Jh]:F,[Ua]:pn,[hn]:$,[qa]:N,[Qh]:Q,[Zh]:H,[em]:l,[tm]:c,[rm]:u,[am]:u?`,${JSON.stringify(u)}:{`:"",[Na]:o,[sm]:g,[lm]:y,[Da]:te,[Ba]:M,[om]:S,silent:Vh,onChild:E,[cm]:A}),Object.setPrototypeOf(e,Mh()),Dh(e),e[Yh](h),e}fe.exports=mn;fe.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=La(t.dest||process.stdout.fd),Fa(t)):Fa({dest:La(t),minLength:0});fe.exports.transport=Js();fe.exports.multistream=Ma();fe.exports.levels=za();fe.exports.stdSerializers=gm;fe.exports.stdTimeFunctions=Object.assign({},Wa);fe.exports.symbols=Va;fe.exports.version=zh;fe.exports.default=mn;fe.exports.pino=mn});var ss=k(require("os")),ir=k(require("fs")),jt=k(require("path"));function fu(){let t=[jt.resolve(__dirname,"..","package.json"),jt.resolve(__dirname,"..","..","package.json"),jt.resolve(process.cwd(),"package.json")];for(let e of t)try{if(ir.existsSync(e)){let r=JSON.parse(ir.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var ns=fu(),Pt=process.stdout.isTTY===!0,li=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",ci=process.stdout.columns||100;Pt&&process.stdout.on("resize",()=>{ci=process.stdout.columns||100});var Ne=()=>Math.min(Math.max(ci-4,56),100);function G(t,e){return!Pt||li?t:`\x1B[${e}m${t}\x1B[0m`}var x={strong:t=>G(t,"1;38;5;255"),muted:t=>G(t,"38;5;241"),dim:t=>G(t,"2;38;5;245"),border:t=>G(t,"38;5;237"),accent:t=>G(t,"38;5;147"),primary:t=>G(t,"38;5;253"),secondary:t=>G(t,"38;5;247"),info:t=>G(t,"38;5;110"),success:t=>G(t,"38;5;114"),warning:t=>G(t,"38;5;179"),error:t=>G(t,"38;5;167"),plan:t=>G(t,"38;5;144"),code:t=>G(t,"38;5;189"),codeLang:t=>G(t,"38;5;110"),linenum:t=>G(t,"38;5;239"),diffAdd:t=>G(t,"38;5;71"),diffDel:t=>G(t,"38;5;131"),link:t=>G(t,"4;38;5;110")};function _e(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function du(t,e){let r=_e(t);return t+" ".repeat(Math.max(0,e-r.length))}function rs(t,e=2,r){let s=(r??Ne())-e,n=t.split(/(?<=\s)|(?=\s)/).filter(Boolean),i=[],o="";for(let a of n){let l=_e(o),c=_e(a.trimStart());l.trimEnd().length+1+c.length>s&&l.trim()?(i.push(" ".repeat(e)+o.trimStart()),o=a.trimStart()):o+=a}return o.trim()&&i.push(" ".repeat(e)+o.trimStart()),i.length?i:[""]}function pu(t,e="\u2500"){return x.border(e.repeat(Math.max(0,t)))}function ii(t,e,r){let s=_e(t),n=Math.max(0,Math.floor((r-2-s.length)/2)),i=Math.max(0,r-2-s.length-n);return x.border("\u2502")+" ".repeat(n)+e+" ".repeat(i)+x.border("\u2502")}function nr(t,e,r){let s=_e(t),n=_e(e),i=Math.max(1,r-4-s.length-n.length);return`${x.border("\u2502")} ${t}${" ".repeat(i)}${e} ${x.border("\u2502")}`}function oi(t){return`${x.border("\u2502")}${" ".repeat(t-2)}${x.border("\u2502")}`}function ui(t,e){let r=Math.min(Ne(),76),s=e.replace(ss.homedir(),"~"),n=t.length>42?t.slice(0,40)+"\u2026":t,i=s.length>42?"\u2026"+s.slice(-40):s,o=x.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),a=x.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),l=x.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),c=x.border("\u255E"+"\u2550".repeat(r-2)+"\u2561");return["",o,oi(r),ii(" HABLAS "," "+x.accent("\u25C6")+" "+x.strong("HABLAS")+" ",r),ii("engineering runtime",x.dim("engineering runtime"),r),oi(r),c,nr(x.secondary("model "),x.accent(n),r),nr(x.secondary("workspace"),x.muted(i),r),nr(x.secondary("version "),x.muted("v"+ns),r),l,nr(x.dim("Type naturally \xB7 /help for commands \xB7 Ctrl+C to cancel"),"",r),a,""].join(`
46
+ `)}function fi(t){let e=Ne(),r=" "+x.accent("\u25C6")+" "+x.strong("Turn")+" "+x.muted(String(t))+" ",s=" \u25C6 Turn "+t+" ",n=Math.max(0,e-s.length-2);return`
47
+ `+x.border("\u2500\u2500")+r+x.border("\u2500".repeat(n))}function or(){return`
48
+ `+x.accent("\u25C6")+" "+x.strong("Hablas")}var hu={Thinking:"\u25CC",Planning:"\u25C8",Inspecting:"\u25CE",Researching:"\u25C9",Editing:"\u25C6",Running:"\u25B6",Fetching:"\u21E9",Downloading:"\u21E9",Memory:"\u25C7",Git:"\u2387",Verifying:"\u25D0",Working:"\u25CF"};function di(t){let e=hu[t]??"\u25CF";return`
49
+ `+x.muted("\u2504")+" "+x.accent(e)+" "+x.secondary(t)+" "+x.muted("\u2504")}var mu={read_file:"\u{1F4C4}",list_dir:"\u{1F4C2}",write_file:"\u270F\uFE0F",edit_file:"\u270F\uFE0F",patch_file:"\u270F\uFE0F",search_and_replace:"\u{1F504}",append_to_file:"\u2795",move_file:"\u{1F69A}",delete_file:"\u{1F5D1}\uFE0F",create_dir:"\u{1F4C1}",search_codebase:"\u{1F50D}",run_command:"\u26A1",execute_code:"\u25B6\uFE0F",web_search:"\u{1F310}",scrape_url:"\u{1F578}\uFE0F",extract_links:"\u{1F517}",download_asset:"\u2B07\uFE0F",detect_bugs:"\u{1F41B}",read_pdf:"\u{1F4CB}",pdf_metadata:"\u{1F4CB}",search_image_candidates:"\u{1F5BC}\uFE0F",inspect_image:"\u{1F50E}",remember:"\u{1F4BE}",recall:"\u{1F9E0}",search_memory:"\u{1F50D}",forget:"\u{1F5D1}\uFE0F",git_status:"\u{1F33F}",git_diff:"\u{1F4DD}",git_log:"\u{1F4DC}",git_branch:"\u{1F33F}"};function pi(t,e){let r=mu[t]??"\xB7",s=t.replace(/_/g," "),n=Math.min(Ne()-4,76),i=r+" "+x.secondary(s),o=e?x.dim(e.slice(0,40)):"",a=_e(i)+(o?" "+e.slice(0,40):""),l=Math.max(0,n-2-a.length),c=" "+x.border("\u256D"+"\u2500".repeat(n)+"\u256E"),u=" "+x.border("\u2502")+" "+i+(o?" "+o:"")+" ".repeat(l)+" "+x.border("\u2502");return`
50
50
  `+c+`
51
- `+u}function pi(t,e,r){let s=Math.min(Ne()-4,76),n=r>=1e3?(r/1e3).toFixed(1)+"s":r+"ms",i=t?x.success("\u2713"):x.error("\u2717"),o=gu(e),a=i+" "+x.dim(n)+(o?" "+o:""),l=ve(a),c=Math.max(0,s-2-l.length),u=" "+x.border("\u2502")+" "+a+" ".repeat(c)+" "+x.border("\u2502"),d=" "+x.border("\u2570"+"\u2500".repeat(s)+"\u256F");return u+`
51
+ `+u}function hi(t,e,r){let s=Math.min(Ne()-4,76),n=r>=1e3?(r/1e3).toFixed(1)+"s":r+"ms",i=t?x.success("\u2713"):x.error("\u2717"),o=gu(e),a=i+" "+x.dim(n)+(o?" "+o:""),l=_e(a),c=Math.max(0,s-2-l.length),u=" "+x.border("\u2502")+" "+a+" ".repeat(c)+" "+x.border("\u2502"),d=" "+x.border("\u2570"+"\u2500".repeat(s)+"\u256F");return u+`
52
52
  `+d}function gu(t){if(!t?.trim())return"";let e=t.split(`
53
- `).filter(s=>s.trim());if(e.length>6)return x.dim(e.length+" lines");let r=e.join(" ").replace(/\s+/g," ").trim();return r.length<=55?x.dim(r):x.dim(r.slice(0,52)+"\u2026")}function De(t){return t.replace(/\*\*([^*\n]+)\*\*/g,(e,r)=>x.strong(r)).replace(/__([^_\n]+)__/g,(e,r)=>x.strong(r)).replace(/\*([^*\n]+)\*/g,(e,r)=>x.accent(r)).replace(/_([^_\n]+)_/g,(e,r)=>x.accent(r)).replace(/`([^`\n]+)`/g,(e,r)=>x.code(r)).replace(/~~([^~\n]+)~~/g,(e,r)=>x.muted(r)).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,(e,r,s)=>x.link(r)+x.muted(" ("+s+")"))}function yu(t){let e=t.filter(o=>!/^\s*\|?\s*[-:]+[-:\s|]*\s*\|?\s*$/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split("|").map(a=>a.trim()));if(!e.length)return[];let r=Math.max(...e.map(o=>o.length)),s=Array(r).fill(4);for(let o of e)for(let a=0;a<o.length;a++)s[a]=Math.max(s[a],ve(o[a]).length+2);let n=x.border(" \u251C"+s.map(o=>"\u2500".repeat(o+2)).join("\u253C")+"\u2524"),i=[];return e.forEach((o,a)=>{let l=Array(r).fill("").map((u,d)=>{let p=De(o[d]??"");return" "+du(p,s[d])+" "}),c=x.border(" \u2502")+l.join(x.border("\u2502"))+x.border("\u2502");i.push(c),a===0&&i.push(n)}),i}function wu(t,e){let r=Math.max(28,Ne()-8),s=String(t.length).length,n=[],i=e?" "+x.codeLang(e):"";n.push(" "+x.border("\u256D"+"\u2500".repeat(r))+i);for(let o=0;o<t.length;o++){let a=x.linenum(String(o+1).padStart(s)),l=bu(t[o],e);n.push(" "+x.border("\u2502")+" "+a+" "+x.border("\u2502")+" "+l)}return n.push(" "+x.border("\u2570"+"\u2500".repeat(r))),n}function bu(t,e){if(!jt||ai)return t;let r=e.toLowerCase();return["sh","bash","zsh","shell"].includes(r)?/^\s*#/.test(t)?x.muted(t):t.replace(/^(\s*)(export|cd|echo|npm|npx|git|node|python|pip|mkdir|rm|cp|mv|ls|cat|grep|sed|awk)(\s)/,(s,n,i,o)=>n+x.accent(i)+o).replace(/(['"`])([^'"` ]*)\1/g,(s,n,i)=>x.warning(n+i+n)):["ts","tsx","js","jsx","typescript","javascript"].includes(r)?/^\s*\/\//.test(t)||/^\s*\/\*/.test(t)?x.muted(t):t.replace(/\b(const|let|var|function|async|await|return|import|export|from|class|extends|interface|type|if|else|for|while|try|catch|throw|new|void|null|undefined|true|false)\b/g,s=>x.accent(s)).replace(/(['"`])([^'"` ]*)\1/g,(s,n,i)=>x.warning(n+i+n)):["py","python"].includes(r)?/^\s*#/.test(t)?x.muted(t):t.replace(/\b(def|class|import|from|return|if|elif|else|for|while|try|except|with|as|pass|in|not|and|or|True|False|None|lambda|yield|async|await)\b/g,s=>x.accent(s)).replace(/(['"`]{1,3})([^'"` ]*?)\1/g,s=>x.warning(s)):["json","jsonc"].includes(r)?t.replace(/"([^"]+)"(\s*:)/g,(s,n,i)=>x.info('"'+n+'"')+x.border(i)).replace(/:\s*"([^"]+)"/g,(s,n)=>": "+x.warning('"'+n+'"')).replace(/:\s*(true|false|null)/g,(s,n)=>": "+x.accent(n)).replace(/:\s*(-?\d+(\.\d+)?)/g,(s,n)=>": "+x.success(n)):x.code(t)}function or(t){if(!t?.trim()||(t=t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<\/?think(?:ing)?>/gi,"").trim(),!t))return"";let e=t.split(`
54
- `),r=[],s=!1,n="",i=[],o=[],a=()=>{i.length&&(r.push(...wu(i,n)),i=[],n="")},l=()=>{o.length&&(r.push(...yu(o)),o=[])},c=u=>/^\s*\|.+\|/.test(u)||/^\s*[-:]+[-:\s|]+$/.test(u);for(let u of e){let d=u.trimStart();if(d.startsWith("```")){l(),s?(a(),s=!1,n=""):(s=!0,n=d.slice(3).trim());continue}if(s){i.push(u);continue}if(c(u)){o.push(u);continue}if(l(),!u.trim()){r.push("");continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(d)){r.push(" "+pu(Math.min(Ne()-4,56)));continue}let p=/^#\s+(.+)/.exec(d);if(p){r.push(""),r.push(" "+x.strong(De(p[1]))),r.push(" "+x.border("\u2500".repeat(Math.min(ve(p[1]).length+2,Ne()-4))));continue}let h=/^##\s+(.+)/.exec(d);if(h){r.push(""),r.push(" "+x.accent("\u25C6")+" "+x.strong(De(h[1])));continue}let f=/^###\s+(.+)/.exec(d);if(f){r.push(""),r.push(" "+x.secondary("\u25C7")+" "+x.primary(De(f[1])));continue}let m=/^(\s*)([-*•+])\s+(.+)/.exec(u);if(m){let b=m[1].length,w=De(m[3]),S=b>0?x.muted("\u25E6"):x.accent("\xB7"),_=es(w,b+4);r.push(" ".repeat(b+2)+S+" "+(_[0]?.trimStart()??""));for(let C=1;C<_.length;C++)r.push(" ".repeat(b+4)+_[C].trimStart());continue}let g=/^(\s*)(\d+)\.\s+(.+)/.exec(u);if(g){let b=g[1].length,w=x.accent(g[2]+"."),S=De(g[3]),_=es(S,b+5);r.push(" ".repeat(b+2)+w+" "+(_[0]?.trimStart()??""));for(let C=1;C<_.length;C++)r.push(" ".repeat(b+5)+_[C].trimStart());continue}let y=/^>\s*(.*)/.exec(d);if(y){r.push(" "+x.border("\u258C")+" "+x.secondary(De(y[1])));continue}if(/^\+(?!\+\+)/.test(d)){r.push(" "+x.diffAdd(u));continue}if(/^-(?!--)/.test(d)){r.push(" "+x.diffDel(u));continue}r.push(...es(De(u),2))}return l(),s&&a(),`
53
+ `).filter(s=>s.trim());if(e.length>6)return x.dim(e.length+" lines");let r=e.join(" ").replace(/\s+/g," ").trim();return r.length<=55?x.dim(r):x.dim(r.slice(0,52)+"\u2026")}function De(t){return t.replace(/\*\*([^*\n]+)\*\*/g,(e,r)=>x.strong(r)).replace(/__([^_\n]+)__/g,(e,r)=>x.strong(r)).replace(/\*([^*\n]+)\*/g,(e,r)=>x.accent(r)).replace(/_([^_\n]+)_/g,(e,r)=>x.accent(r)).replace(/`([^`\n]+)`/g,(e,r)=>x.code(r)).replace(/~~([^~\n]+)~~/g,(e,r)=>x.muted(r)).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,(e,r,s)=>x.link(r)+x.muted(" ("+s+")"))}function yu(t){let e=t.filter(o=>!/^\s*\|?\s*[-:]+[-:\s|]*\s*\|?\s*$/.test(o)).map(o=>o.replace(/^\||\|$/g,"").split("|").map(a=>a.trim()));if(!e.length)return[];let r=Math.max(...e.map(o=>o.length)),s=Array(r).fill(4);for(let o of e)for(let a=0;a<o.length;a++)s[a]=Math.max(s[a],_e(o[a]).length+2);let n=x.border(" \u251C"+s.map(o=>"\u2500".repeat(o+2)).join("\u253C")+"\u2524"),i=[];return e.forEach((o,a)=>{let l=Array(r).fill("").map((u,d)=>{let p=De(o[d]??"");return" "+du(p,s[d])+" "}),c=x.border(" \u2502")+l.join(x.border("\u2502"))+x.border("\u2502");i.push(c),a===0&&i.push(n)}),i}function wu(t,e){let r=Math.max(28,Ne()-8),s=String(t.length).length,n=[],i=e?" "+x.codeLang(e):"";n.push(" "+x.border("\u256D"+"\u2500".repeat(r))+i);for(let o=0;o<t.length;o++){let a=x.linenum(String(o+1).padStart(s)),l=bu(t[o],e);n.push(" "+x.border("\u2502")+" "+a+" "+x.border("\u2502")+" "+l)}return n.push(" "+x.border("\u2570"+"\u2500".repeat(r))),n}function bu(t,e){if(!Pt||li)return t;let r=e.toLowerCase();return["sh","bash","zsh","shell"].includes(r)?/^\s*#/.test(t)?x.muted(t):t.replace(/^(\s*)(export|cd|echo|npm|npx|git|node|python|pip|mkdir|rm|cp|mv|ls|cat|grep|sed|awk)(\s)/,(s,n,i,o)=>n+x.accent(i)+o).replace(/(['"`])([^'"` ]*)\1/g,(s,n,i)=>x.warning(n+i+n)):["ts","tsx","js","jsx","typescript","javascript"].includes(r)?/^\s*\/\//.test(t)||/^\s*\/\*/.test(t)?x.muted(t):t.replace(/\b(const|let|var|function|async|await|return|import|export|from|class|extends|interface|type|if|else|for|while|try|catch|throw|new|void|null|undefined|true|false)\b/g,s=>x.accent(s)).replace(/(['"`])([^'"` ]*)\1/g,(s,n,i)=>x.warning(n+i+n)):["py","python"].includes(r)?/^\s*#/.test(t)?x.muted(t):t.replace(/\b(def|class|import|from|return|if|elif|else|for|while|try|except|with|as|pass|in|not|and|or|True|False|None|lambda|yield|async|await)\b/g,s=>x.accent(s)).replace(/(['"`]{1,3})([^'"` ]*?)\1/g,s=>x.warning(s)):["json","jsonc"].includes(r)?t.replace(/"([^"]+)"(\s*:)/g,(s,n,i)=>x.info('"'+n+'"')+x.border(i)).replace(/:\s*"([^"]+)"/g,(s,n)=>": "+x.warning('"'+n+'"')).replace(/:\s*(true|false|null)/g,(s,n)=>": "+x.accent(n)).replace(/:\s*(-?\d+(\.\d+)?)/g,(s,n)=>": "+x.success(n)):x.code(t)}function ar(t){if(!t?.trim()||(t=t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").replace(/<think>[\s\S]*?<\/think>/gi,"").replace(/<\/?think(?:ing)?>/gi,"").trim(),!t))return"";let e=t.split(`
54
+ `),r=[],s=!1,n="",i=[],o=[],a=()=>{i.length&&(r.push(...wu(i,n)),i=[],n="")},l=()=>{o.length&&(r.push(...yu(o)),o=[])},c=u=>/^\s*\|.+\|/.test(u)||/^\s*[-:]+[-:\s|]+$/.test(u);for(let u of e){let d=u.trimStart();if(d.startsWith("```")){l(),s?(a(),s=!1,n=""):(s=!0,n=d.slice(3).trim());continue}if(s){i.push(u);continue}if(c(u)){o.push(u);continue}if(l(),!u.trim()){r.push("");continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(d)){r.push(" "+pu(Math.min(Ne()-4,56)));continue}let p=/^#\s+(.+)/.exec(d);if(p){r.push(""),r.push(" "+x.strong(De(p[1]))),r.push(" "+x.border("\u2500".repeat(Math.min(_e(p[1]).length+2,Ne()-4))));continue}let h=/^##\s+(.+)/.exec(d);if(h){r.push(""),r.push(" "+x.accent("\u25C6")+" "+x.strong(De(h[1])));continue}let f=/^###\s+(.+)/.exec(d);if(f){r.push(""),r.push(" "+x.secondary("\u25C7")+" "+x.primary(De(f[1])));continue}let m=/^(\s*)([-*•+])\s+(.+)/.exec(u);if(m){let b=m[1].length,w=De(m[3]),S=b>0?x.muted("\u25E6"):x.accent("\xB7"),_=rs(w,b+4);r.push(" ".repeat(b+2)+S+" "+(_[0]?.trimStart()??""));for(let C=1;C<_.length;C++)r.push(" ".repeat(b+4)+_[C].trimStart());continue}let g=/^(\s*)(\d+)\.\s+(.+)/.exec(u);if(g){let b=g[1].length,w=x.accent(g[2]+"."),S=De(g[3]),_=rs(S,b+5);r.push(" ".repeat(b+2)+w+" "+(_[0]?.trimStart()??""));for(let C=1;C<_.length;C++)r.push(" ".repeat(b+5)+_[C].trimStart());continue}let y=/^>\s*(.*)/.exec(d);if(y){r.push(" "+x.border("\u258C")+" "+x.secondary(De(y[1])));continue}if(/^\+(?!\+\+)/.test(d)){r.push(" "+x.diffAdd(u));continue}if(/^-(?!--)/.test(d)){r.push(" "+x.diffDel(u));continue}r.push(...rs(De(u),2))}return l(),s&&a(),`
55
55
  `+r.join(`
56
56
  `)+`
57
- `}function hi(){let t=(e,r)=>" "+x.accent(e.padEnd(20))+" "+x.muted(r);return[""," "+x.strong("Commands"),"",t("/help","show this reference"),t("/status","runtime status snapshot"),t("/model [name]","show or switch active model"),t("/models [q] [n]","browse & search available models"),t("/provider","inspect or switch LLM provider"),t("/history [n]","show recent turns"),t("/clear","reset session"),t("/workspace","inspect project structure"),t("/memory","show project memory"),t("/diff [file]","show git diff"),t("/git [status|log]","git status or log"),t("/doctor","run diagnostics"),t("/version","show version"),t("/about","product identity"),t("/exit","quit"),""," "+x.secondary("Tips")," "+x.muted("Ctrl+C cancels current work. Ctrl+C twice exits.")," "+x.muted("Hablas reads Arabic, English, and mixed input."),""].join(`
58
- `)}function mi(t){let e=t.workingDir.replace(ts.homedir(),"~"),r=t.connected?x.success("online"):x.warning("offline"),s=[["model",x.accent(t.model)],["provider",x.primary(t.provider)],["connection",r],["workspace",x.muted(e)],["messages",x.muted(String(t.messageCount))],["tokens (est)",x.muted(t.totalTokens.toLocaleString())]];return[""," "+x.strong("Runtime Status"),"",...s.map(([n,i])=>" "+x.secondary(n.padEnd(14))+" "+i),""].join(`
59
- `)}function gi(){return[""," "+x.strong("Hablas")+" "+x.dim("v"+rs)," "+x.muted("Single-agent engineering runtime for the terminal."),""," "+x.secondary("Built by")+" "+x.primary("Abdulmoin Hablas")," "+x.link("https://portfolio-monopoly63s-projects.vercel.app/"),""," "+x.secondary("Philosophy")," "+x.muted("One agent. One conversation. Real execution."),""].join(`
60
- `)}function yi(){return`
61
- `+x.strong("hablas")+" "+x.accent("v"+rs)+`
62
- `}function Ae(t){return`
57
+ `}function mi(){let t=(e,r)=>" "+x.accent(e.padEnd(20))+" "+x.muted(r);return[""," "+x.strong("Commands"),"",t("/help","show this reference"),t("/status","runtime status snapshot"),t("/model [name]","show or switch active model"),t("/models [q] [n]","browse & search available models"),t("/provider","inspect or switch LLM provider"),t("/history [n]","show recent turns"),t("/clear","reset session"),t("/workspace","inspect project structure"),t("/memory","show project memory"),t("/diff [file]","show git diff"),t("/git [status|log]","git status or log"),t("/doctor","run diagnostics"),t("/version","show version"),t("/about","product identity"),t("/exit","quit"),""," "+x.secondary("Tips")," "+x.muted("Ctrl+C cancels current work. Ctrl+C twice exits.")," "+x.muted("Hablas reads Arabic, English, and mixed input."),""].join(`
58
+ `)}function gi(t){let e=t.workingDir.replace(ss.homedir(),"~"),r=t.connected?x.success("online"):x.warning("offline"),s=[["model",x.accent(t.model)],["provider",x.primary(t.provider)],["connection",r],["workspace",x.muted(e)],["messages",x.muted(String(t.messageCount))],["tokens (est)",x.muted(t.totalTokens.toLocaleString())]];return[""," "+x.strong("Runtime Status"),"",...s.map(([n,i])=>" "+x.secondary(n.padEnd(14))+" "+i),""].join(`
59
+ `)}function yi(){return[""," "+x.strong("Hablas")+" "+x.dim("v"+ns)," "+x.muted("Single-agent engineering runtime for the terminal."),""," "+x.secondary("Built by")+" "+x.primary("Abdulmoin Hablas")," "+x.link("https://portfolio-monopoly63s-projects.vercel.app/"),""," "+x.secondary("Philosophy")," "+x.muted("One agent. One conversation. Real execution."),""].join(`
60
+ `)}function wi(){return`
61
+ `+x.strong("hablas")+" "+x.accent("v"+ns)+`
62
+ `}function Oe(t){return`
63
63
  `+x.error("\u2717")+" "+x.primary(t)+`
64
- `}function se(t){return" "+x.warning("\u26A0")+" "+x.secondary(t)}function _e(t){return" "+x.success("\u2713")+" "+x.primary(t)}function D(t){return" "+x.muted("\xB7")+" "+x.secondary(t)}var oi=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ke=class{frame=0;timer;active=!1;label;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!jt||this.active||(this.active=!0,this.frame=0,this.timer=setInterval(()=>{let e=G(oi[this.frame++%oi.length],"38;5;147");process.stdout.write("\r "+e+" "+x.muted(this.label)+"\x1B[K")},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=void 0),jt&&process.stdout.write("\r\x1B[K"))}};var ss=null;function bi(t){ss=t}function xi(){try{ss?.stop()}catch{}ss=null}function wi(t,e){xi(),process.stdout.write(`
65
- `);let r=e instanceof Error?e.message:String(e);console.error(Ae(`[${t}] ${r}`)),process.env.HABLAS_DEBUG&&e instanceof Error&&e.stack&&console.error(`
64
+ `}function se(t){return" "+x.warning("\u26A0")+" "+x.secondary(t)}function ke(t){return" "+x.success("\u2713")+" "+x.primary(t)}function D(t){return" "+x.muted("\xB7")+" "+x.secondary(t)}var ai=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ge=class{frame=0;timer;active=!1;label;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!Pt||this.active||(this.active=!0,this.frame=0,this.timer=setInterval(()=>{let e=G(ai[this.frame++%ai.length],"38;5;147");process.stdout.write("\r "+e+" "+x.muted(this.label)+"\x1B[K")},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=void 0),Pt&&process.stdout.write("\r\x1B[K"))}};var is=null;function xi(t){is=t}function Si(){try{is?.stop()}catch{}is=null}function bi(t,e){Si(),process.stdout.write(`
65
+ `);let r=e instanceof Error?e.message:String(e);console.error(Oe(`[${t}] ${r}`)),process.env.HABLAS_DEBUG&&e instanceof Error&&e.stack&&console.error(`
66
66
  `+e.stack.split(`
67
67
  `).slice(1,5).join(`
68
- `))}function Si(){process.on("uncaughtException",t=>{wi("Uncaught Error",t),process.exit(1)}),process.on("unhandledRejection",t=>{wi("Unhandled Promise",t),process.exit(1)}),process.on("SIGTERM",()=>{xi(),process.stdout.write(`
69
- `),console.log(se("Received SIGTERM \u2014 shutting down gracefully.")),process.exit(0)})}var Pi=k(ji(),1),{program:aw,createCommand:lw,createArgument:cw,createOption:uw,CommanderError:fw,InvalidArgumentError:dw,InvalidOptionArgumentError:pw,Command:Mi,Argument:hw,Option:mw,Help:gw}=Pi.default;var ye=k(require("fs")),Je=k(require("path")),Fi=k(require("os"));var ct={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0},vision:{enabled:!0,primaryModel:"moonshotai/kimi-k2.6",fallbackModel:"meta/llama-3.2-90b-vision-instruct",maxImageBytes:1048576}},ce={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]},Ge={name:"Mistral AI",apiUrl:"https://api.mistral.ai/v1",defaultModel:"mistral-large-latest",models:["mistral-large-latest","mistral-medium-latest","mistral-small-latest","codestral-latest","open-mistral-nemo","open-codestral-mamba"]};var ut=Je.join(Fi.homedir(),".hablas"),bs=Je.join(ut,"config.json");function ft(t={}){let e={};if(ye.existsSync(bs))try{e=JSON.parse(ye.readFileSync(bs,"utf-8"))}catch{}let r={...ct,...e,tools:{...ct.tools,...e.tools||{},runCommand:{...ct.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...ct.workspace,...e.workspace||{}},vision:{...ct.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(r.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(r.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(r.vision.enabled=!1),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=Je.resolve(t.project)),t.provider){let s=t.provider;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function Ye(t){ye.existsSync(ut)||ye.mkdirSync(ut,{recursive:!0}),ye.writeFileSync(bs,JSON.stringify(t,null,2),"utf-8")}function Li(){let t=[ut,Je.join(ut,"logs"),Je.join(ut,"backup")];for(let e of t)ye.existsSync(e)||ye.mkdirSync(e,{recursive:!0})}var hn=k(Ga()),mn=k(require("path")),Ja=k(require("os")),$r=k(require("fs"));function gn(t){let e=mn.join(Ja.homedir(),".hablas","logs");$r.existsSync(e)||$r.mkdirSync(e,{recursive:!0});let r=mn.join(e,`session-${Date.now()}.log`);return(0,hn.default)({level:"info"},hn.default.destination({dest:r,sync:!1}))}var Er=k(require("fs")),Nt=k(require("path"));function Ya(){let t=[Nt.resolve(__dirname,"..","package.json"),Nt.resolve(__dirname,"..","..","package.json"),Nt.resolve(process.cwd(),"package.json"),Nt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Er.existsSync(e)){let r=JSON.parse(Er.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Wc=k(require("fs")),Vc=k(require("path"));var Ar=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,r,s){let n={model:this.model,messages:e,stream:!1};r.length>0&&(n.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let n=s.body?.getReader();if(!n)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await n.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
70
- `);o=c.pop()||"";for(let u of c)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var ym={400:{message:"Bad request \u2014 the model may not support this feature.",retryable:!1,fatal:!1},401:{message:"Authentication failed \u2014 check your API key with /provider.",retryable:!1,fatal:!0},402:{message:"Payment required \u2014 your API account needs credits.",retryable:!1,fatal:!0},403:{message:"Access forbidden \u2014 your API key lacks permission for this model.",retryable:!1,fatal:!0},404:{message:"Model not found \u2014 run /models to see available models.",retryable:!1,fatal:!1},413:{message:"Request too large \u2014 the conversation is too long. Starting fresh context.",retryable:!1,fatal:!1},422:{message:"Invalid request format \u2014 the provider rejected this message structure.",retryable:!1,fatal:!1},429:{message:"Rate limit reached \u2014 waiting before retry.",retryable:!0,fatal:!1},500:{message:"Provider server error \u2014 retrying...",retryable:!0,fatal:!1},502:{message:"Provider gateway error \u2014 retrying...",retryable:!0,fatal:!1},503:{message:"Provider temporarily unavailable \u2014 retrying...",retryable:!0,fatal:!1},529:{message:"Provider overloaded \u2014 retrying with backoff...",retryable:!0,fatal:!1}},yn=[{test:t=>/insufficient_quota|credit|billing|payment|out of credits/i.test(t),message:"API credits exhausted \u2014 top up your account or switch provider with /provider.",retryable:!1,fatal:!0},{test:t=>/rate.?limit|too many requests|rpm|tpm/i.test(t),message:"Rate limit reached \u2014 retrying after cooldown.",retryable:!0,fatal:!1},{test:t=>/context.?length|context_length|token.*limit|maximum.*token/i.test(t),message:"Context window full \u2014 the conversation is too long. Some history will be trimmed.",retryable:!1,fatal:!1},{test:t=>/model.*not.*found|does not exist|invalid model/i.test(t),message:"Model not found \u2014 run /models to list available models.",retryable:!1,fatal:!1},{test:t=>/invalid.?api.?key|unauthorized|authentication/i.test(t),message:"Invalid API key \u2014 reconfigure with /provider.",retryable:!1,fatal:!0},{test:t=>/overload|capacity|busy/i.test(t),message:"Provider is overloaded \u2014 retrying...",retryable:!0,fatal:!1}],wm=[{test:t=>/ECONNREFUSED/i.test(t),message:"Connection refused \u2014 is the API server running?",retryable:!0},{test:t=>/ECONNRESET/i.test(t),message:"Connection reset \u2014 network instability detected, retrying...",retryable:!0},{test:t=>/ENOTFOUND/i.test(t),message:"DNS lookup failed \u2014 check your internet connection.",retryable:!1},{test:t=>/ETIMEDOUT/i.test(t),message:"Connection timed out \u2014 network is slow or blocked.",retryable:!0},{test:t=>/fetch failed/i.test(t),message:"Network request failed \u2014 check your connection.",retryable:!0},{test:t=>/AbortError|aborted/i.test(t),message:"Request timed out \u2014 provider took too long to respond.",retryable:!0}];function de(t,e){let r=t instanceof Error?t.message:String(t),s=/API error: (\d{3})/.exec(r);if(s){let i=parseInt(s[1],10),o=ym[i];if(e){for(let a of yn)if(a.test(e))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i}}for(let a of yn)if(a.test(r))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i};return o?{...o,status:i}:{message:`Server error (${i}) \u2014 retrying...`,retryable:i>=500,fatal:!1,status:i}}for(let i of wm)if(i.test(r))return{message:i.message,retryable:i.retryable,fatal:!1};let n=r+(e||"");for(let i of yn)if(i.test(n))return{message:i.message,retryable:i.retryable,fatal:i.fatal};return{message:r.length>120?r.slice(0,120)+"...":r,retryable:!1,fatal:!1}}var wn=12e4,bm=6e4,Or=3,Xa=1e3,xm=20;function bn(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(s=>s?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((s,n)=>({id:`call_${n}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Qa(t){return t.map(e=>({type:"function",function:e.function}))}function Za(t){return t.filter(e=>e?.function?.name).map(e=>{let r={};try{r=JSON.parse(e.function?.arguments||"{}")}catch{r={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:r}}})}function el(t){return new Promise(e=>setTimeout(e,t))}function tl(t,e){return t?.name==="AbortError"?!1:e?de(new Error(`API error: ${e}`)).retryable:de(t).retryable}function rl(t,e){return de(t,e).message}function Sm(t,e){return de(t,e).fatal}var mt=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,s,n=0;for(;r&&n<xm;){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(bm)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let u=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),c.has_more&&u.length>0?(s=u[u.length-1],n++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async*streamChatWithTools(e,r,s,n){let i=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",o={model:this.model,messages:bn(e),stream:!0};r.length>0&&(o.tools=Qa(r),o.tool_choice="auto");let a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(o),signal:n||AbortSignal.timeout(wn)})}catch{return await this.chatWithTools(e,r,n)}if(!a.ok){let f=await a.text().catch(()=>"");throw new Error(`API error: ${a.status} ${a.statusText} \u2014 ${f}`)}let l=a.body?.getReader();if(!l)return await this.chatWithTools(e,r,n);let c=new TextDecoder,u="",d="",p=[];for(;;){let{done:f,value:m}=await l.read();if(f)break;u+=c.decode(m,{stream:!0});let g=u.split(`
71
- `);u=g.pop()||"";for(let y of g){let b=y.trim();if(!(!b||b==="data: [DONE]")&&b.startsWith("data: "))try{let S=JSON.parse(b.slice(6)).choices?.[0]?.delta;if(!S)continue;if(S.content&&(d+=S.content,s?.(S.content)),S.tool_calls)for(let _ of S.tool_calls){let C=_.index??0;p[C]||(p[C]={id:_.id||"",type:"function",index:C,function:{name:_.function?.name||"",arguments:""}}),_.function?.name&&(p[C].function.name=_.function.name),_.function?.arguments&&(p[C].function.arguments+=_.function.arguments)}}catch{}}}let h=p.length>0?Za(p):void 0;return{message:{role:"assistant",content:d,tool_calls:h},done:!0,done_reason:h?"tool_calls":"stop"}}async chatWithTools(e,r,s){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:bn(e)};r.length>0&&(i.tools=Qa(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Or;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),wn),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let d=await fetch(n,u);if(clearTimeout(c),!d.ok){let m=await d.text().catch(()=>"");if(Sm(null,m)||!tl(null,d.status))throw new Error(rl(new Error(`API error: ${d.status}`),m));if(o=new Error(rl(new Error(`API error: ${d.status}`),m)),a<Or){let g=Xa*Math.pow(2,a);await el(g);continue}throw o}let h=(await d.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let f=h.message.tool_calls?Za(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:f},done:!0,done_reason:h.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&s?.aborted)throw d;if(tl(d)&&(o=d,a<Or)){let p=Xa*Math.pow(2,a);await el(p);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Or)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:bn(e),stream:!0}),signal:r||AbortSignal.timeout(wn)});if(!n.ok)throw new Error(`API error: ${n.status} ${n.statusText}`);let i=n.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let u=a.split(`
72
- `);a=u.pop()||"";for(let d of u){let p=d.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let f=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;f&&(yield f)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function gt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ce.apiUrl};return new mt(e)}if(t.provider==="mistral"){let e={...t,provider:"custom",apiUrl:Ge.apiUrl};return new mt(e)}return t.provider==="custom"&&t.apiUrl?new mt(t):new Ar(t)}function rt(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="mistral")return"Mistral AI";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var B=k(require("fs/promises")),$n=k(require("fs")),qe=k(require("path"));function Ie(){}Ie.prototype={diff:function(e,r){var s,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.callback;typeof n=="function"&&(i=n,n={}),this.options=n;var o=this;function a(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,u=1,d=l+c;n.maxEditLength&&(d=Math.min(d,n.maxEditLength));var p=(s=n.timeout)!==null&&s!==void 0?s:1/0,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(f[0],r,e,0);if(f[0].oldPos+1>=c&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var g=-1/0,y=1/0;function b(){for(var S=Math.max(g,-u);S<=Math.min(y,u);S+=2){var _=void 0,C=f[S-1],A=f[S+1];C&&(f[S-1]=void 0);var E=!1;if(A){var $=A.oldPos-S;E=A&&0<=$&&$<l}var M=C&&C.oldPos+1<c;if(!E&&!M){f[S]=void 0;continue}if(!M||E&&C.oldPos+1<A.oldPos?_=o.addToPath(A,!0,void 0,0):_=o.addToPath(C,void 0,!0,1),m=o.extractCommon(_,r,e,S),_.oldPos+1>=c&&m+1>=l)return a(vm(o,_.lastComponent,r,e,o.useLongestToken));f[S]=_,_.oldPos+1>=c&&(y=Math.min(y,S-1)),m+1>=l&&(g=Math.max(g,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>h)return i();b()||S()},0)})();else for(;u<=d&&Date.now()<=h;){var w=b();if(w)return w}},addToPath:function(e,r,s,n){var i=e.lastComponent;return i&&i.added===r&&i.removed===s?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:s,previousComponent:i}}},extractCommon:function(e,r,s,n){for(var i=r.length,o=s.length,a=e.oldPos,l=a-n,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],s[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],s=0;s<e.length;s++)e[s]&&r.push(e[s]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function vm(t,e,r,s,n){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(s.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!d.added&&n){var p=r.slice(c,c+d.count);p=p.map(function(m,g){var y=s[u+g];return y.length>m.length?y:m}),d.value=t.join(p)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var f=i[l-1];return l>1&&typeof f.value=="string"&&(f.added||f.removed)&&t.equals("",f.value)&&(i[l-2].value+=f.value,i.pop()),i}var hb=new Ie;var sl=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,nl=/\S/,il=new Ie;il.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!nl.test(t)&&!nl.test(e)};il.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&sl.test(e[r])&&sl.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var kn=new Ie;kn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
73
- `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var s=0;s<r.length;s++){var n=r[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=n:(this.options.ignoreWhitespace&&(n=n.trim()),e.push(n))}return e};function _m(t,e,r){return kn.diff(t,e,r)}var km=new Ie;km.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Tm=new Ie;Tm.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Rr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Rr=function(e){return typeof e}:Rr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Rr(t)}function xn(t){return Cm(t)||$m(t)||Em(t)||Am()}function Cm(t){if(Array.isArray(t))return Sn(t)}function $m(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Em(t,e){if(t){if(typeof t=="string")return Sn(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Sn(t,e)}}function Sn(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,s=new Array(e);r<e;r++)s[r]=t[r];return s}function Am(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
74
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Om=Object.prototype.toString,Ut=new Ie;Ut.useLongestToken=!0;Ut.tokenize=kn.tokenize;Ut.castInput=function(t){var e=this.options,r=e.undefinedReplacement,s=e.stringifyReplacer,n=s===void 0?function(i,o){return typeof o>"u"?r:o}:s;return typeof t=="string"?t:JSON.stringify(vn(t,null,null,n),n," ")};Ut.equals=function(t,e){return Ie.prototype.equals.call(Ut,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function vn(t,e,r,s,n){e=e||[],r=r||[],s&&(t=s(n,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(Om.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),i=0;i<t.length;i+=1)o[i]=vn(t[i],e,r,s,n);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Rr(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=vn(t[l],e,r,s,l);e.pop(),r.pop()}else o=t;return o}var _n=new Ie;_n.tokenize=function(t){return t.slice()};_n.join=_n.removeEmpty=function(t){return t};function Rm(t,e,r,s,n,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=_m(r,s,o);if(!a)return;a.push({value:"",lines:[]});function l(y){return y.map(function(b){return" "+b})}for(var c=[],u=0,d=0,p=[],h=1,f=1,m=function(b){var w=a[b],S=w.lines||w.value.replace(/\n$/,"").split(`
75
- `);if(w.lines=S,w.added||w.removed){var _;if(!u){var C=a[b-1];u=h,d=f,C&&(p=o.context>0?l(C.lines.slice(-o.context)):[],u-=p.length,d-=p.length)}(_=p).push.apply(_,xn(S.map(function(Q){return(w.added?"+":"-")+Q}))),w.added?f+=S.length:h+=S.length}else{if(u)if(S.length<=o.context*2&&b<a.length-2){var A;(A=p).push.apply(A,xn(l(S)))}else{var E,$=Math.min(S.length,o.context);(E=p).push.apply(E,xn(l(S.slice(0,$))));var M={oldStart:u,oldLines:h-u+$,newStart:d,newLines:f-d+$,lines:p};if(b>=a.length-2&&S.length<=o.context){var U=/\n$/.test(r),N=/\n$/.test(s),H=S.length==0&&p.length>M.oldLines;!U&&H&&r.length>0&&p.splice(M.oldLines,0,"\"),(!U&&!H||!N)&&p.push("\")}c.push(M),u=0,d=0,p=[]}h+=S.length,f+=S.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:n,newHeader:i,hunks:c}}function ol(t){if(Array.isArray(t))return t.map(ol).join(`
68
+ `))}function vi(){process.on("uncaughtException",t=>{bi("Uncaught Error",t),process.exit(1)}),process.on("unhandledRejection",t=>{bi("Unhandled Promise",t),process.exit(1)}),process.on("SIGTERM",()=>{Si(),process.stdout.write(`
69
+ `),console.log(se("Received SIGTERM \u2014 shutting down gracefully.")),process.exit(0)})}var Mi=k(Pi(),1),{program:cw,createCommand:uw,createArgument:fw,createOption:dw,CommanderError:pw,InvalidArgumentError:hw,InvalidOptionArgumentError:mw,Command:Fi,Argument:gw,Option:yw,Help:ww}=Mi.default;var we=k(require("fs")),Xe=k(require("path")),Li=k(require("os"));var ut={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:5e3,timeout:12e4,autoMode:!1,contextBudget:2e6,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0},vision:{enabled:!0,primaryModel:"moonshotai/kimi-k2.6",fallbackModel:"meta/llama-3.2-90b-vision-instruct",maxImageBytes:1048576}},ce={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]},Je={name:"Mistral AI",apiUrl:"https://api.mistral.ai/v1",defaultModel:"mistral-large-latest",models:["mistral-large-latest","mistral-medium-latest","mistral-small-latest","codestral-latest","open-mistral-nemo","open-codestral-mamba"]};var ft=Xe.join(Li.homedir(),".hablas"),Ss=Xe.join(ft,"config.json");function dt(t={}){let e={};if(we.existsSync(Ss))try{e=JSON.parse(we.readFileSync(Ss,"utf-8"))}catch{}let r={...ut,...e,tools:{...ut.tools,...e.tools||{},runCommand:{...ut.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...ut.workspace,...e.workspace||{}},vision:{...ut.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(r.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(r.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(r.vision.enabled=!1),process.env.HABLAS_PROVIDER){let s=process.env.HABLAS_PROVIDER;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=Xe.resolve(t.project)),t.provider){let s=t.provider;(s==="ollama"||s==="custom"||s==="nvidia")&&(r.provider=s)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function Ye(t){we.existsSync(ft)||we.mkdirSync(ft,{recursive:!0}),we.writeFileSync(Ss,JSON.stringify(t,null,2),"utf-8")}function Di(){let t=[ft,Xe.join(ft,"logs"),Xe.join(ft,"backup")];for(let e of t)we.existsSync(e)||we.mkdirSync(e,{recursive:!0})}var gn=k(Ja()),yn=k(require("path")),Xa=k(require("os")),Ar=k(require("fs"));function wn(t){let e=yn.join(Xa.homedir(),".hablas","logs");Ar.existsSync(e)||Ar.mkdirSync(e,{recursive:!0});let r=yn.join(e,`session-${Date.now()}.log`);return(0,gn.default)({level:"info"},gn.default.destination({dest:r,sync:!1}))}var Er=k(require("fs")),Ut=k(require("path"));function Ya(){let t=[Ut.resolve(__dirname,"..","package.json"),Ut.resolve(__dirname,"..","..","package.json"),Ut.resolve(process.cwd(),"package.json"),Ut.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Er.existsSync(e)){let r=JSON.parse(Er.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Vc=k(require("fs")),zc=k(require("path"));var Or=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(s=>s.name):[]}catch{return[]}}async chatWithTools(e,r,s){let n={model:this.model,messages:e,stream:!1};r.length>0&&(n.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)};s&&(i.signal=s);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let s=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!s.ok)throw new Error(`Ollama error: ${s.status} ${s.statusText}`);let n=s.body?.getReader();if(!n)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await n.read();if(a)break;o+=i.decode(l,{stream:!0});let c=o.split(`
70
+ `);o=c.pop()||"";for(let u of c)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var ym={400:{message:"Bad request \u2014 the model may not support this feature.",retryable:!1,fatal:!1},401:{message:"Authentication failed \u2014 check your API key with /provider.",retryable:!1,fatal:!0},402:{message:"Payment required \u2014 your API account needs credits.",retryable:!1,fatal:!0},403:{message:"Access forbidden \u2014 your API key lacks permission for this model.",retryable:!1,fatal:!0},404:{message:"Model not found \u2014 run /models to see available models.",retryable:!1,fatal:!1},413:{message:"Request too large \u2014 the conversation is too long. Starting fresh context.",retryable:!1,fatal:!1},422:{message:"Invalid request format \u2014 the provider rejected this message structure.",retryable:!1,fatal:!1},429:{message:"Rate limit reached by API provider \u2014 waiting before retry.",retryable:!0,fatal:!1},500:{message:"Provider server error \u2014 retrying...",retryable:!0,fatal:!1},502:{message:"Provider gateway error \u2014 retrying...",retryable:!0,fatal:!1},503:{message:"Provider temporarily unavailable \u2014 retrying...",retryable:!0,fatal:!1},529:{message:"Provider overloaded \u2014 retrying with backoff...",retryable:!0,fatal:!1}},bn=[{test:t=>/insufficient_quota|credit|billing|payment|out of credits/i.test(t),message:"API credits exhausted \u2014 top up your account or switch provider with /provider.",retryable:!1,fatal:!0},{test:t=>/rate.?limit|too many requests|rpm|tpm/i.test(t),message:"API provider rate limit \u2014 retrying after cooldown.",retryable:!0,fatal:!1},{test:t=>/context.?length|context_length|token.*limit|maximum.*token/i.test(t),message:"Context window full \u2014 the conversation is too long. Some history will be trimmed.",retryable:!1,fatal:!1},{test:t=>/model.*not.*found|does not exist|invalid model/i.test(t),message:"Model not found \u2014 run /models to list available models.",retryable:!1,fatal:!1},{test:t=>/invalid.?api.?key|unauthorized|authentication/i.test(t),message:"Invalid API key \u2014 reconfigure with /provider.",retryable:!1,fatal:!0},{test:t=>/overload|capacity|busy/i.test(t),message:"Provider is overloaded \u2014 retrying...",retryable:!0,fatal:!1}],wm=[{test:t=>/ECONNREFUSED/i.test(t),message:"Connection refused \u2014 is the API server running?",retryable:!0},{test:t=>/ECONNRESET/i.test(t),message:"Connection reset \u2014 network instability detected, retrying...",retryable:!0},{test:t=>/ENOTFOUND/i.test(t),message:"DNS lookup failed \u2014 check your internet connection.",retryable:!1},{test:t=>/ETIMEDOUT/i.test(t),message:"Connection timed out \u2014 network is slow or blocked.",retryable:!0},{test:t=>/fetch failed/i.test(t),message:"Network request failed \u2014 check your connection.",retryable:!0},{test:t=>/AbortError|aborted/i.test(t),message:"Request timed out \u2014 provider took too long to respond.",retryable:!0}];function de(t,e){let r=t instanceof Error?t.message:String(t),s=/API error: (\d{3})/.exec(r);if(s){let i=parseInt(s[1],10),o=ym[i];if(e){for(let a of bn)if(a.test(e))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i}}for(let a of bn)if(a.test(r))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i};return o?{...o,status:i}:{message:`Server error (${i}) \u2014 retrying...`,retryable:i>=500,fatal:!1,status:i}}for(let i of wm)if(i.test(r))return{message:i.message,retryable:i.retryable,fatal:!1};let n=r+(e||"");for(let i of bn)if(i.test(n))return{message:i.message,retryable:i.retryable,fatal:i.fatal};return{message:r.length>120?r.slice(0,120)+"...":r,retryable:!1,fatal:!1}}var xn=12e4,bm=6e4,Rr=3,Qa=1e3,xm=15e3,Sm=6e4,vm=20;function Sn(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(s=>s?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((s,n)=>({id:`call_${n}`,type:"function",function:{name:s.function?.name||"",arguments:JSON.stringify(s.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function Za(t){return t.map(e=>({type:"function",function:e.function}))}function el(t){return t.filter(e=>e?.function?.name).map(e=>{let r={};try{r=JSON.parse(e.function?.arguments||"{}")}catch{r={_raw:e.function?.arguments}}return{function:{name:e.function?.name||"",arguments:r}}})}function tl(t){return new Promise(e=>setTimeout(e,t))}function rl(t,e){return t?.name==="AbortError"?!1:e?de(new Error(`API error: ${e}`)).retryable:de(t).retryable}function sl(t,e){return de(t,e).message}function _m(t,e){return de(t,e).fatal}var gt=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,s,n=0;for(;r&&n<vm;){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(bm)});if(!l.ok)break;let c=await l.json();if(Array.isArray(c))e.push(...c.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(c.data&&Array.isArray(c.data)){let u=c.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),c.has_more&&u.length>0?(s=u[u.length-1],n++):r=!1}else c.models&&Array.isArray(c.models)&&e.push(...c.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async*streamChatWithTools(e,r,s,n){let i=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",o={model:this.model,messages:Sn(e),stream:!0};r.length>0&&(o.tools=Za(r),o.tool_choice="auto");let a;try{a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(o),signal:n||AbortSignal.timeout(xn)})}catch{return await this.chatWithTools(e,r,n)}if(!a.ok){let f=await a.text().catch(()=>"");throw new Error(`API error: ${a.status} ${a.statusText} \u2014 ${f}`)}let l=a.body?.getReader();if(!l)return await this.chatWithTools(e,r,n);let c=new TextDecoder,u="",d="",p=[];for(;;){let{done:f,value:m}=await l.read();if(f)break;u+=c.decode(m,{stream:!0});let g=u.split(`
71
+ `);u=g.pop()||"";for(let y of g){let b=y.trim();if(!(!b||b==="data: [DONE]")&&b.startsWith("data: "))try{let S=JSON.parse(b.slice(6)).choices?.[0]?.delta;if(!S)continue;if(S.content&&(d+=S.content,s?.(S.content)),S.tool_calls)for(let _ of S.tool_calls){let C=_.index??0;p[C]||(p[C]={id:_.id||"",type:"function",index:C,function:{name:_.function?.name||"",arguments:""}}),_.function?.name&&(p[C].function.name=_.function.name),_.function?.arguments&&(p[C].function.arguments+=_.function.arguments)}}catch{}}}let h=p.length>0?el(p):void 0;return{message:{role:"assistant",content:d,tool_calls:h},done:!0,done_reason:h?"tool_calls":"stop"}}async chatWithTools(e,r,s){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:Sn(e)};r.length>0&&(i.tools=Za(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Rr;a++)try{let l=new AbortController,c=setTimeout(()=>l.abort(),xn),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:s||l.signal};try{let d=await fetch(n,u);if(clearTimeout(c),!d.ok){let m=await d.text().catch(()=>"");if(_m(null,m)||!rl(null,d.status))throw new Error(sl(new Error(`API error: ${d.status}`),m));if(o=new Error(sl(new Error(`API error: ${d.status}`),m)),a<Rr){let g=d.headers.get("retry-after")||d.headers.get("x-ratelimit-reset-requests"),y;if(d.status===429)if(g){let b=Number(g);if(!isNaN(b))y=b>1e9?Math.max(0,b*1e3-Date.now()):b*1e3;else{let w=new Date(g);y=Math.max(0,w.getTime()-Date.now())}}else y=Math.min(xm*Math.pow(2,a),Sm);else y=Qa*Math.pow(2,a);await tl(y);continue}throw o}let h=(await d.json()).choices?.[0];if(!h)throw new Error("API returned empty response");let f=h.message.tool_calls?el(h.message.tool_calls):void 0;return{message:{role:h.message.role||"assistant",content:h.message.content||"",tool_calls:f},done:!0,done_reason:h.finish_reason}}catch(d){if(clearTimeout(c),d.name==="AbortError"&&s?.aborted)throw d;if(rl(d)&&(o=d,a<Rr)){let p=Qa*Math.pow(2,a);await tl(p);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Rr)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:Sn(e),stream:!0}),signal:r||AbortSignal.timeout(xn)});if(!n.ok)throw new Error(`API error: ${n.status} ${n.statusText}`);let i=n.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:c}=await i.read();if(l)break;a+=o.decode(c,{stream:!0});let u=a.split(`
72
+ `);a=u.pop()||"";for(let d of u){let p=d.trim();if(!(!p||p==="data: [DONE]")&&p.startsWith("data: "))try{let f=JSON.parse(p.slice(6)).choices?.[0]?.delta?.content;f&&(yield f)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function yt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:ce.apiUrl};return new gt(e)}if(t.provider==="mistral"){let e={...t,provider:"custom",apiUrl:Je.apiUrl};return new gt(e)}return t.provider==="custom"&&t.apiUrl?new gt(t):new Or(t)}function st(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="mistral")return"Mistral AI";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var B=k(require("fs/promises")),En=k(require("fs")),qe=k(require("path"));function je(){}je.prototype={diff:function(e,r){var s,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.callback;typeof n=="function"&&(i=n,n={}),this.options=n;var o=this;function a(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,c=e.length,u=1,d=l+c;n.maxEditLength&&(d=Math.min(d,n.maxEditLength));var p=(s=n.timeout)!==null&&s!==void 0?s:1/0,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(f[0],r,e,0);if(f[0].oldPos+1>=c&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var g=-1/0,y=1/0;function b(){for(var S=Math.max(g,-u);S<=Math.min(y,u);S+=2){var _=void 0,C=f[S-1],E=f[S+1];C&&(f[S-1]=void 0);var A=!1;if(E){var $=E.oldPos-S;A=E&&0<=$&&$<l}var M=C&&C.oldPos+1<c;if(!A&&!M){f[S]=void 0;continue}if(!M||A&&C.oldPos+1<E.oldPos?_=o.addToPath(E,!0,void 0,0):_=o.addToPath(C,void 0,!0,1),m=o.extractCommon(_,r,e,S),_.oldPos+1>=c&&m+1>=l)return a(km(o,_.lastComponent,r,e,o.useLongestToken));f[S]=_,_.oldPos+1>=c&&(y=Math.min(y,S-1)),m+1>=l&&(g=Math.max(g,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>h)return i();b()||S()},0)})();else for(;u<=d&&Date.now()<=h;){var w=b();if(w)return w}},addToPath:function(e,r,s,n){var i=e.lastComponent;return i&&i.added===r&&i.removed===s?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:s,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:s,previousComponent:i}}},extractCommon:function(e,r,s,n){for(var i=r.length,o=s.length,a=e.oldPos,l=a-n,c=0;l+1<i&&a+1<o&&this.equals(r[l+1],s[a+1]);)l++,a++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],s=0;s<e.length;s++)e[s]&&r.push(e[s]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function km(t,e,r,s,n){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,c=0,u=0;a<l;a++){var d=i[a];if(d.removed){if(d.value=t.join(s.slice(u,u+d.count)),u+=d.count,a&&i[a-1].added){var h=i[a-1];i[a-1]=i[a],i[a]=h}}else{if(!d.added&&n){var p=r.slice(c,c+d.count);p=p.map(function(m,g){var y=s[u+g];return y.length>m.length?y:m}),d.value=t.join(p)}else d.value=t.join(r.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}var f=i[l-1];return l>1&&typeof f.value=="string"&&(f.added||f.removed)&&t.equals("",f.value)&&(i[l-2].value+=f.value,i.pop()),i}var gb=new je;var nl=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,il=/\S/,ol=new je;ol.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!il.test(t)&&!il.test(e)};ol.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&nl.test(e[r])&&nl.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Cn=new je;Cn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
73
+ `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var s=0;s<r.length;s++){var n=r[s];s%2&&!this.options.newlineIsToken?e[e.length-1]+=n:(this.options.ignoreWhitespace&&(n=n.trim()),e.push(n))}return e};function Tm(t,e,r){return Cn.diff(t,e,r)}var Cm=new je;Cm.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var $m=new je;$m.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Ir(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ir=function(e){return typeof e}:Ir=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ir(t)}function vn(t){return Am(t)||Em(t)||Om(t)||Rm()}function Am(t){if(Array.isArray(t))return _n(t)}function Em(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Om(t,e){if(t){if(typeof t=="string")return _n(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _n(t,e)}}function _n(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,s=new Array(e);r<e;r++)s[r]=t[r];return s}function Rm(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
74
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Im=Object.prototype.toString,qt=new je;qt.useLongestToken=!0;qt.tokenize=Cn.tokenize;qt.castInput=function(t){var e=this.options,r=e.undefinedReplacement,s=e.stringifyReplacer,n=s===void 0?function(i,o){return typeof o>"u"?r:o}:s;return typeof t=="string"?t:JSON.stringify(kn(t,null,null,n),n," ")};qt.equals=function(t,e){return je.prototype.equals.call(qt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function kn(t,e,r,s,n){e=e||[],r=r||[],s&&(t=s(n,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(Im.call(t)==="[object Array]"){for(e.push(t),o=new Array(t.length),r.push(o),i=0;i<t.length;i+=1)o[i]=kn(t[i],e,r,s,n);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Ir(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=kn(t[l],e,r,s,l);e.pop(),r.pop()}else o=t;return o}var Tn=new je;Tn.tokenize=function(t){return t.slice()};Tn.join=Tn.removeEmpty=function(t){return t};function jm(t,e,r,s,n,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=Tm(r,s,o);if(!a)return;a.push({value:"",lines:[]});function l(y){return y.map(function(b){return" "+b})}for(var c=[],u=0,d=0,p=[],h=1,f=1,m=function(b){var w=a[b],S=w.lines||w.value.replace(/\n$/,"").split(`
75
+ `);if(w.lines=S,w.added||w.removed){var _;if(!u){var C=a[b-1];u=h,d=f,C&&(p=o.context>0?l(C.lines.slice(-o.context)):[],u-=p.length,d-=p.length)}(_=p).push.apply(_,vn(S.map(function(Q){return(w.added?"+":"-")+Q}))),w.added?f+=S.length:h+=S.length}else{if(u)if(S.length<=o.context*2&&b<a.length-2){var E;(E=p).push.apply(E,vn(l(S)))}else{var A,$=Math.min(S.length,o.context);(A=p).push.apply(A,vn(l(S.slice(0,$))));var M={oldStart:u,oldLines:h-u+$,newStart:d,newLines:f-d+$,lines:p};if(b>=a.length-2&&S.length<=o.context){var U=/\n$/.test(r),N=/\n$/.test(s),H=S.length==0&&p.length>M.oldLines;!U&&H&&r.length>0&&p.splice(M.oldLines,0,"\"),(!U&&!H||!N)&&p.push("\")}c.push(M),u=0,d=0,p=[]}h+=S.length,f+=S.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:n,newHeader:i,hunks:c}}function al(t){if(Array.isArray(t))return t.map(al).join(`
76
76
  `);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var s=t.hunks[r];s.oldLines===0&&(s.oldStart-=1),s.newLines===0&&(s.newStart-=1),e.push("@@ -"+s.oldStart+","+s.oldLines+" +"+s.newStart+","+s.newLines+" @@"),e.push.apply(e,s.lines)}return e.join(`
77
77
  `)+`
78
- `}function Im(t,e,r,s,n,i,o){return ol(Rm(t,e,r,s,n,i,o))}function al(t,e,r,s,n,i){return Im(t,t,e,r,s,n,i)}function qt(t,e,r){return al(t,e,r,"original","modified")}var Te=k(require("fs/promises")),Tn=k(require("fs")),yt=k(require("path")),cl=k(require("os")),Bt=yt.join(cl.homedir(),".hablas","backup"),ll=10;async function st(t){try{if(!Tn.existsSync(t))return;Tn.existsSync(Bt)||await Te.mkdir(Bt,{recursive:!0});let e=await Te.readFile(t,"utf-8"),r=yt.basename(t),s=Date.now(),n=`${r}.${s}.bak`,i=yt.join(Bt,n);await Te.writeFile(i,e,"utf-8");let a=(await Te.readdir(Bt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>ll)for(let l of a.slice(ll))await Te.unlink(yt.join(Bt,l))}catch{}}function ul(t){let e=h=>qe.resolve(t,h);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let f=e(h.path),g=(await B.readFile(f,"utf-8")).split(`
79
- `),y=g.length,b=h.start_line?Math.max(1,h.start_line):1,w=h.end_line?Math.min(y,h.end_line):y,S=g.slice(b-1,w),_=String(w).length,C=S.map(($,M)=>`${String(b+M).padStart(_," ")} | ${$}`),A=`[${h.path} \u2014 lines ${b}-${w} of ${y}]`,E=w<y?`
80
- ... [Partial read. Total lines: ${y}.]`:"";return{success:!0,output:`${A}
78
+ `}function Pm(t,e,r,s,n,i,o){return al(jm(t,e,r,s,n,i,o))}function ll(t,e,r,s,n,i){return Pm(t,t,e,r,s,n,i)}function Bt(t,e,r){return ll(t,e,r,"original","modified")}var Ce=k(require("fs/promises")),$n=k(require("fs")),wt=k(require("path")),ul=k(require("os")),Ht=wt.join(ul.homedir(),".hablas","backup"),cl=10;async function nt(t){try{if(!$n.existsSync(t))return;$n.existsSync(Ht)||await Ce.mkdir(Ht,{recursive:!0});let e=await Ce.readFile(t,"utf-8"),r=wt.basename(t),s=Date.now(),n=`${r}.${s}.bak`,i=wt.join(Ht,n);await Ce.writeFile(i,e,"utf-8");let a=(await Ce.readdir(Ht)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>cl)for(let l of a.slice(cl))await Ce.unlink(wt.join(Ht,l))}catch{}}function fl(t){let e=h=>qe.resolve(t,h);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[read_file]: path is required"};let f=e(h.path),g=(await B.readFile(f,"utf-8")).split(`
79
+ `),y=g.length,b=h.start_line?Math.max(1,h.start_line):1,w=h.end_line?Math.min(y,h.end_line):y,S=g.slice(b-1,w),_=String(w).length,C=S.map(($,M)=>`${String(b+M).padStart(_," ")} | ${$}`),E=`[${h.path} \u2014 lines ${b}-${w} of ${y}]`,A=w<y?`
80
+ ... [Partial read. Total lines: ${y}.]`:"";return{success:!0,output:`${E}
81
81
  ${C.join(`
82
- `)}${E}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${f.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let f=e(h.path);return $n.existsSync(f)&&await st(f),await B.mkdir(qe.dirname(f),{recursive:!0}),await B.writeFile(f,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${f.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!h.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=h.old_content,y=h.new_content,b=Cn(m,g),w=g;if(b===0){let E=N=>N.replace(/\r\n/g,`
82
+ `)}${A}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${f.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let f=e(h.path);return En.existsSync(f)&&await nt(f),await B.mkdir(qe.dirname(f),{recursive:!0}),await B.writeFile(f,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${f.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!h.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=h.old_content,y=h.new_content,b=An(m,g),w=g;if(b===0){let A=N=>N.replace(/\r\n/g,`
83
83
  `).split(`
84
84
  `).map(H=>H.trimEnd()).join(`
85
- `),$=E(m),M=E(g),U=Cn($,M);U===1&&(w=M,b=U)}if(b===0)return{success:!1,output:"",error:`[edit_file]: old_content not found in file. Check for whitespace/newline differences. File preview: "${m.slice(0,200).replace(/\n/g,"\u21B5")}\u2026"`};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations. Provide more surrounding context to make it unique.`};await st(f);let C=(w!==g?(E=>E.replace(/\r\n/g,`
85
+ `),$=A(m),M=A(g),U=An($,M);U===1&&(w=M,b=U)}if(b===0)return{success:!1,output:"",error:`[edit_file]: old_content not found in file. Check for whitespace/newline differences. File preview: "${m.slice(0,200).replace(/\n/g,"\u21B5")}\u2026"`};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations. Provide more surrounding context to make it unique.`};await nt(f);let C=(w!==g?(A=>A.replace(/\r\n/g,`
86
86
  `).split(`
87
87
  `).map($=>$.trimEnd()).join(`
88
- `))(m):m).replace(w,y);await B.writeFile(f,C,"utf-8");let A=qt(h.path,m,C);return{success:!0,output:`Edited: ${h.path}
89
- ${A}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${f.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!h.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!h.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(h.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=m.split(`
90
- `),y=g.length,b=h.start_line,w=h.end_line;if(b<1||b>y)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${y} lines)`};if(w<b||w>y)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${b}, total=${y})`};await st(f);let S=g.slice(0,b-1),_=g.slice(w),C=h.new_content.split(`
91
- `),A=[...S,...C,..._].join(`
92
- `);await B.writeFile(f,A,"utf-8");let E=qt(h.path,m,A),$=w-b+1,M=C.length;return{success:!0,output:`Patched: ${h.path} (replaced ${$} lines with ${M})
93
- ${E}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${f.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=h.search,y=h.replace,b=h.is_regex;await st(f);let w,S;if(b){let _=new RegExp(g,"g");S=(m.match(_)||[]).length,w=m.replace(_,y)}else S=Cn(m,g),w=m.split(g).join(y);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await B.writeFile(f,w,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${h.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${f.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let f=e(h.path);return await B.mkdir(qe.dirname(f),{recursive:!0}),$n.existsSync(f)&&await st(f),await B.appendFile(f,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${f.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let f=e(h.path);return await st(f),await B.unlink(f),{success:!0,output:`Deleted: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${f.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async h=>{try{if(!h.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!h.to)return{success:!1,output:"",error:"[move_file]: to is required"};let f=e(h.from),m=e(h.to);return await B.mkdir(qe.dirname(m),{recursive:!0}),await B.rename(f,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${f.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let f=e(h.path);return await B.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${f.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async h=>{try{let f=e(h.path||"."),m=h.depth||3;return{success:!0,output:await fl(f,"",m,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${f.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let f=e(h.path),m=await B.stat(f);return{success:!0,output:[`Path: ${h.path}`,`Size: ${Pm(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
94
- `)}}catch(f){return{success:!1,output:"",error:`[get_file_info]: ${f.message}`}}}}]}function Cn(t,e){let r=0,s=0;for(;;){let n=t.indexOf(e,s);if(n===-1)break;r++,s=n+e.length}return r}var jm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function fl(t,e,r,s){if(s>=r)return"";let i=(await B.readdir(t,{withFileTypes:!0})).filter(a=>!jm.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,u=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
95
- `,l.isDirectory()){let p=e+(c?" ":"\u2502 ");o+=await fl(qe.join(t,l.name),p,r,s+1)}}return o}function Pm(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var hl=require("child_process");var dl=require("child_process"),Ir=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let s=`bg_${this.nextId++}`,n=r?.timeout||this.config.defaultTimeout,i=(0,dl.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
88
+ `))(m):m).replace(w,y);await B.writeFile(f,C,"utf-8");let E=Bt(h.path,m,C);return{success:!0,output:`Edited: ${h.path}
89
+ ${E}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${f.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!h.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!h.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(h.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=m.split(`
90
+ `),y=g.length,b=h.start_line,w=h.end_line;if(b<1||b>y)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${y} lines)`};if(w<b||w>y)return{success:!1,output:"",error:`[patch_file]: end_line ${w} is out of range (start_line=${b}, total=${y})`};await nt(f);let S=g.slice(0,b-1),_=g.slice(w),C=h.new_content.split(`
91
+ `),E=[...S,...C,..._].join(`
92
+ `);await B.writeFile(f,E,"utf-8");let A=Bt(h.path,m,E),$=w-b+1,M=C.length;return{success:!0,output:`Patched: ${h.path} (replaced ${$} lines with ${M})
93
+ ${A}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${f.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!h.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(h.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let f=e(h.path),m=await B.readFile(f,"utf-8"),g=h.search,y=h.replace,b=h.is_regex;await nt(f);let w,S;if(b){let _=new RegExp(g,"g");S=(m.match(_)||[]).length,w=m.replace(_,y)}else S=An(m,g),w=m.split(g).join(y);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await B.writeFile(f,w,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${h.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${f.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(h.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let f=e(h.path);return await B.mkdir(qe.dirname(f),{recursive:!0}),En.existsSync(f)&&await nt(f),await B.appendFile(f,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${f.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let f=e(h.path);return await nt(f),await B.unlink(f),{success:!0,output:`Deleted: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${f.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async h=>{try{if(!h.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!h.to)return{success:!1,output:"",error:"[move_file]: to is required"};let f=e(h.from),m=e(h.to);return await B.mkdir(qe.dirname(m),{recursive:!0}),await B.rename(f,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${f.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let f=e(h.path);return await B.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${f.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async h=>{try{let f=e(h.path||"."),m=h.depth||3;return{success:!0,output:await dl(f,"",m,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${f.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async h=>{try{if(!h.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let f=e(h.path),m=await B.stat(f);return{success:!0,output:[`Path: ${h.path}`,`Size: ${Fm(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
94
+ `)}}catch(f){return{success:!1,output:"",error:`[get_file_info]: ${f.message}`}}}}]}function An(t,e){let r=0,s=0;for(;;){let n=t.indexOf(e,s);if(n===-1)break;r++,s=n+e.length}return r}var Mm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function dl(t,e,r,s){if(s>=r)return"";let i=(await B.readdir(t,{withFileTypes:!0})).filter(a=>!Mm.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,u=c?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
95
+ `,l.isDirectory()){let p=e+(c?" ":"\u2502 ");o+=await dl(qe.join(t,l.name),p,r,s+1)}}return o}function Fm(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var ml=require("child_process");var pl=require("child_process"),jr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let s=`bg_${this.nextId++}`,n=r?.timeout||this.config.defaultTimeout,i=(0,pl.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:s,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
96
96
  Error: ${a.message}`}),n>0&&setTimeout(()=>{o.status==="running"&&(this.kill(s),o.status="timeout",o.stderr+=`
97
97
  Process timed out after ${n}ms`)},n),this.processes.set(s,o),s}readOutput(e,r){let s=this.processes.get(e);if(!s)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let n=r?.type||"both",i="";return(n==="stdout"||n==="both")&&(i+=s.stdout),(n==="stderr"||n==="both")&&(i&&(i+=`
98
98
  `),i+=s.stderr),r?.lastLines&&(i=i.split(`
99
99
  `).slice(-r.lastLines).join(`
100
- `)),{success:!0,output:i,status:s.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,s]of this.processes){let n=Date.now()-s.startTime,i=this.formatUptime(n);e.push({id:r,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);return s<60?`${s}m ${r%60}s`:`${Math.floor(s/60)}h ${s%60}m`}};var Mm=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],En=null;function pl(t){return En||(En=new Ir({workingDir:t})),En}function ml(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let s=r.command,n=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Mm,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(n){let l=pl(t).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
101
- PID: ${pl(t).getProcess(l)?.pid}
102
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,hl.exec)(s,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{let f=(m,g)=>m.length>8e3?m.slice(0,8e3)+`
103
- ... [${g} truncated \u2014 ${m.length} chars total]`:m;l(p===0?{success:!0,output:f(u,"stdout")||"(no output)"}:{success:!1,output:f(u,"stdout"),error:f(d||`Exit code: ${p}`,"stderr")})}),c.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var jr=k(require("fs/promises")),Be=k(require("path")),Fm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Lm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function gl(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,s=Be.resolve(t,e.path||"."),n=[];if(await yl(s,r,n,t),n.length===0)return{success:!0,output:`No matches found for: "${r}"`};let i=n.slice(0,50).join(`
100
+ `)),{success:!0,output:i,status:s.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,s]of this.processes){let n=Date.now()-s.startTime,i=this.formatUptime(n);e.push({id:r,command:s.command,status:s.status,pid:s.pid,startTime:s.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,s]of this.processes)(s.status==="finished"||s.status==="killed"||s.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let s=Math.floor(r/60);return s<60?`${s}m ${r%60}s`:`${Math.floor(s/60)}h ${s%60}m`}};var Lm=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],On=null;function hl(t){return On||(On=new jr({workingDir:t})),On}function gl(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let s=r.command,n=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...Lm,...o];if(a.length>0){for(let l of a)if(s.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(n){let l=hl(t).start(s,{timeout:i});return{success:!0,output:`Background process started: ${l}
101
+ PID: ${hl(t).getProcess(l)?.pid}
102
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let c=(0,ml.exec)(s,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{let f=(m,g)=>m.length>8e3?m.slice(0,8e3)+`
103
+ ... [${g} truncated \u2014 ${m.length} chars total]`:m;l(p===0?{success:!0,output:f(u,"stdout")||"(no output)"}:{success:!1,output:f(u,"stdout"),error:f(d||`Exit code: ${p}`,"stderr")})}),c.on("error",p=>{l({success:!1,output:"",error:p.message})})})}}}var Pr=k(require("fs/promises")),Be=k(require("path")),Dm=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Nm=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function yl(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,s=Be.resolve(t,e.path||"."),n=[];if(await wl(s,r,n,t),n.length===0)return{success:!0,output:`No matches found for: "${r}"`};let i=n.slice(0,50).join(`
104
104
  `),o=n.length>50?`
105
- ... and ${n.length-50} more matches`:"";return{success:!0,output:i+o}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function yl(t,e,r,s){let n=await jr.readdir(t,{withFileTypes:!0});for(let i of n){if(Fm.has(i.name)||i.name.startsWith("."))continue;let o=Be.join(t,i.name);if(i.isDirectory())await yl(o,e,r,s);else if(Lm.has(Be.extname(i.name)))try{let l=(await jr.readFile(o,"utf-8")).split(`
106
- `),c=Be.relative(s,o);for(let u=0;u<l.length;u++)new RegExp(e,"i").test(l[u])&&r.push(`${c}:${u+1}: ${l[u].trim()}`)}catch{}}}var An=require("child_process"),pe=k(require("fs")),He=k(require("path"));function Dm(t){let e=[],r=He.join(t,"tsconfig.json");if(!pe.existsSync(r))return e;try{(0,An.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let n=s,o=(n.stdout||n.message||"").split(`
107
- `);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 Nm(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>pe.existsSync(He.join(t,s))))return e;try{(0,An.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:He.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
108
- `);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 Um(t,e,r){let s;try{s=pe.readFileSync(t,"utf-8")}catch{return}let n=He.relative(e,t),i=s.split(`
109
- `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:n,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:n,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:n,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:n,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function qm(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function s(n,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=pe.readdirSync(n)}catch{return}for(let l of a){if(o.includes(l))continue;let c=He.join(n,l),u;try{u=pe.statSync(c)}catch{continue}u.isDirectory()?s(c,i+1):r.some(d=>l.endsWith(d))&&Um(c,t,e)}}return s(t),e.slice(0,20)}function Bm(t){let e=[];e.push(...Dm(t)),e.push(...Nm(t)),e.push(...qm(t));let r={error:0,warning:1,info:2};return e.sort((s,n)=>r[s.severity]-r[n.severity]),e}function wl(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,s=t.filter(i=>i.severity==="warning").length,n=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${s} warnings, ${n} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
110
- `)}function Hm(t,e){let r=[];for(let s of t)if(s.source==="pattern"&&s.message.includes("console.log")){let n=He.join(e,s.file);try{let o=pe.readFileSync(n,"utf-8").split(`
105
+ ... and ${n.length-50} more matches`:"";return{success:!0,output:i+o}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function wl(t,e,r,s){let n=await Pr.readdir(t,{withFileTypes:!0});for(let i of n){if(Dm.has(i.name)||i.name.startsWith("."))continue;let o=Be.join(t,i.name);if(i.isDirectory())await wl(o,e,r,s);else if(Nm.has(Be.extname(i.name)))try{let l=(await Pr.readFile(o,"utf-8")).split(`
106
+ `),c=Be.relative(s,o);for(let u=0;u<l.length;u++)new RegExp(e,"i").test(l[u])&&r.push(`${c}:${u+1}: ${l[u].trim()}`)}catch{}}}var Rn=require("child_process"),pe=k(require("fs")),He=k(require("path"));function Um(t){let e=[],r=He.join(t,"tsconfig.json");if(!pe.existsSync(r))return e;try{(0,Rn.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let n=s,o=(n.stdout||n.message||"").split(`
107
+ `);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 qm(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(s=>pe.existsSync(He.join(t,s))))return e;try{(0,Rn.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(s){let i=s.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let l of a.messages||[])e.push({file:He.relative(t,a.filePath),line:l.line||0,severity:l.severity===2?"error":"warning",message:`${l.message} (${l.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
108
+ `);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 Bm(t,e,r){let s;try{s=pe.readFileSync(t,"utf-8")}catch{return}let n=He.relative(e,t),i=s.split(`
109
+ `);for(let o=0;o<i.length;o++){let a=i[o],l=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:n,line:l,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:n,line:l,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:n,line:l,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:n,line:l,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function Hm(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function s(n,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=pe.readdirSync(n)}catch{return}for(let l of a){if(o.includes(l))continue;let c=He.join(n,l),u;try{u=pe.statSync(c)}catch{continue}u.isDirectory()?s(c,i+1):r.some(d=>l.endsWith(d))&&Bm(c,t,e)}}return s(t),e.slice(0,20)}function Wm(t){let e=[];e.push(...Um(t)),e.push(...qm(t)),e.push(...Hm(t));let r={error:0,warning:1,info:2};return e.sort((s,n)=>r[s.severity]-r[n.severity]),e}function bl(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,s=t.filter(i=>i.severity==="warning").length,n=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${s} warnings, ${n} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
110
+ `)}function Vm(t,e){let r=[];for(let s of t)if(s.source==="pattern"&&s.message.includes("console.log")){let n=He.join(e,s.file);try{let o=pe.readFileSync(n,"utf-8").split(`
111
111
  `);s.line>0&&s.line<=o.length&&(o[s.line-1]="// "+o[s.line-1],pe.writeFileSync(n,o.join(`
112
- `),"utf-8"),r.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function bl(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,s=e.fix==="true"||e.fix===!0;try{let n=Bm(r);if(s&&n.length>0){let o=Hm(n,r).filter(l=>l.fixed).length;return{success:!0,output:`${wl(n)}
112
+ `),"utf-8"),r.push({bug:s,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:s,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:s,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function xl(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,s=e.fix==="true"||e.fix===!0;try{let n=Wm(r);if(s&&n.length>0){let o=Vm(n,r).filter(l=>l.fixed).length;return{success:!0,output:`${bl(n)}
113
113
 
114
- Auto-fixed: ${o}/${n.length} issues`}}return{success:!0,output:wl(n)}}catch(n){return{success:!1,output:"",error:`Bug detection failed: ${n instanceof Error?n.message:String(n)}`}}}}}var xl=2*1024*1024,Sl=15e3,vl=32e3,Wm="HablasBot/2.0 (+https://hablas.dev)";function Vm(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
114
+ Auto-fixed: ${o}/${n.length} issues`}}return{success:!0,output:bl(n)}}catch(n){return{success:!1,output:"",error:`Bug detection failed: ${n instanceof Error?n.message:String(n)}`}}}}}var Sl=2*1024*1024,vl=15e3,_l=32e3,zm="HablasBot/2.0 (+https://hablas.dev)";function Km(t){let e=t;return e=e.replace(/<(script|style|nav|footer|header|aside|iframe|noscript)[^>]*>[\s\S]*?<\/\1>/gi,""),e=e.replace(/<!--[\s\S]*?-->/g,""),e=e.replace(/<\/(p|div|section|article|li|tr|h[1-6])>/gi,`
115
115
  `),e=e.replace(/<(br|hr)\s*\/?>/gi,`
116
116
  `),e=e.replace(/<\/?(ul|ol)>/gi,`
117
117
  `),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,s,n)=>`
118
118
  ${"#".repeat(parseInt(s))} ${n.replace(/<[^>]+>/g,"").trim()}
119
119
  `),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,s,n)=>{let i=n.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${s})`:s}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,s)=>"\n```\n"+s.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(r,s)=>String.fromCharCode(parseInt(s))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
120
120
 
121
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function zm(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Km(t,e){let r=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,n,i=new Set;for(;(n=s.exec(t))!==null;){let o=n[1].trim(),a=n[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function _l(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Sl);try{let s=await fetch(t,{signal:e.signal,headers:{"User-Agent":Wm,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!s.ok)return{html:"",finalUrl:s.url||t,status:s.status};let n=s.headers.get("content-type")||"";if(!n.includes("text/")&&!n.includes("application/xhtml")&&!n.includes("application/json"))return{html:`[Binary content: ${n}]`,finalUrl:s.url||t,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||t,status:s.status};let o=[],a=0;for(;a<xl;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=xl)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:s.url||t,status:s.status}}catch(s){clearTimeout(r);let n=s instanceof Error?s:new Error(String(s));throw n.name==="AbortError"?new Error(`Timeout after ${Sl/1e3}s`):n}}function kl(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:s,status:n}=await _l(e);if(!r||n>=400)return{success:!1,output:"",error:`HTTP ${n} \u2014 could not fetch ${e}`};let i=zm(r),o=Vm(r);return o.length>vl&&(o=o.slice(0,vl)+`
121
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Gm(t){let e=t.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(e)return e[1].replace(/<[^>]+>/g,"").trim();let r=t.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);return r?r[1].replace(/<[^>]+>/g,"").trim():"Untitled"}function Jm(t,e){let r=[],s=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,n,i=new Set;for(;(n=s.exec(t))!==null;){let o=n[1].trim(),a=n[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function kl(t){let e=new AbortController,r=setTimeout(()=>e.abort(),vl);try{let s=await fetch(t,{signal:e.signal,headers:{"User-Agent":zm,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!s.ok)return{html:"",finalUrl:s.url||t,status:s.status};let n=s.headers.get("content-type")||"";if(!n.includes("text/")&&!n.includes("application/xhtml")&&!n.includes("application/json"))return{html:`[Binary content: ${n}]`,finalUrl:s.url||t,status:s.status};let i=s.body?.getReader();if(!i)return{html:"",finalUrl:s.url||t,status:s.status};let o=[],a=0;for(;a<Sl;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Sl)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl:s.url||t,status:s.status}}catch(s){clearTimeout(r);let n=s instanceof Error?s:new Error(String(s));throw n.name==="AbortError"?new Error(`Timeout after ${vl/1e3}s`):n}}function Tl(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:s,status:n}=await kl(e);if(!r||n>=400)return{success:!1,output:"",error:`HTTP ${n} \u2014 could not fetch ${e}`};let i=Gm(r),o=Km(r);return o.length>_l&&(o=o.slice(0,_l)+`
122
122
 
123
123
  [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${s}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
124
- `)}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:n,status:i}=await _l(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Km(s,n);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
124
+ `)}}catch(r){let s=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${s}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:s,finalUrl:n,status:i}=await kl(e);if(!s||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Jm(s,n);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,c)=>`${c+1}. [${l.text}](${l.url})`).join(`
125
125
  `);return{success:!0,output:`Found ${o.length} links:
126
126
 
127
- ${a}`}}catch(s){let n=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${n}`}}}}]}var Gm=3600*1e3,wt=new Map;function Jm(t){let e=wt.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Gm?(wt.delete(t.toLowerCase().trim()),null):e.results:null}function Ym(t,e){if(wt.size>200){let r=wt.keys().next().value;r!==void 0&&wt.delete(r)}wt.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Xm(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let s=new URLSearchParams({q:t,count:String(Math.min(e,10))}),n=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return n.ok?((await n.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function Qm(t,e){try{let r=new URLSearchParams({q:t}),s=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let n=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(n))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(n))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(u)&&!u.includes("duckduckgo.com")&&(c.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function On(t,e=5){let r=Jm(t);if(r)return r.slice(0,e);let s=[{name:"brave",fn:()=>Xm(t,e)},{name:"duckduckgo",fn:()=>Qm(t,e)}];for(let n of s)try{let i=await n.fn();if(i&&i.length>0)return Ym(t,i),i}catch{}return[]}function Tl(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let s=await On(e.trim(),r);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let n=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];n.push(`[${i+1}] ${o.title}`),n.push(` ${o.url}`),o.snippet&&n.push(` ${o.snippet}`),n.push("")}return{success:!0,output:n.join(`
128
- `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var je=k(require("fs")),Ol=k(require("path")),Cl=50*1024*1024,$l=4e4;function El(t){let e=t.toString("latin1"),r={},s=[],n=0,i=e.match(/\/Type\s*\/Page\b/g);n=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=nt(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=nt(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=nt(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=nt(c[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let h=d[1],f=Al(h);f.trim()&&s.push(f);try{let m=require("zlib"),g=Buffer.from(h,"latin1"),y=m.inflateSync(g).toString("latin1"),b=Al(y);b.trim()&&!s.includes(b)&&s.push(b)}catch{}}return{text:s.join(`
127
+ ${a}`}}catch(s){let n=s instanceof Error?s.message:String(s);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${n}`}}}}]}var Xm=3600*1e3,bt=new Map;function Ym(t){let e=bt.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Xm?(bt.delete(t.toLowerCase().trim()),null):e.results:null}function Qm(t,e){if(bt.size>200){let r=bt.keys().next().value;r!==void 0&&bt.delete(r)}bt.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Zm(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let s=new URLSearchParams({q:t,count:String(Math.min(e,10))}),n=await fetch(`https://api.search.brave.com/res/v1/web/search?${s}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return n.ok?((await n.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function eg(t,e){try{let r=new URLSearchParams({q:t}),s=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return null;let n=await s.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(n))!==null&&i.length<e;){let l=a[1],c=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}c&&l&&!l.startsWith("/")&&i.push({title:c,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,c=new Set;for(;(a=l.exec(n))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!c.has(u)&&!u.includes("duckduckgo.com")&&(c.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function In(t,e=5){let r=Ym(t);if(r)return r.slice(0,e);let s=[{name:"brave",fn:()=>Zm(t,e)},{name:"duckduckgo",fn:()=>eg(t,e)}];for(let n of s)try{let i=await n.fn();if(i&&i.length>0)return Qm(t,i),i}catch{}return[]}function Cl(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let s=await In(e.trim(),r);if(s.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let n=[`Search results for: "${e}" (${s.length} results, source: ${s[0].source})`,""];for(let i=0;i<s.length;i++){let o=s[i];n.push(`[${i+1}] ${o.title}`),n.push(` ${o.url}`),o.snippet&&n.push(` ${o.snippet}`),n.push("")}return{success:!0,output:n.join(`
128
+ `)}}catch(s){return{success:!1,output:"",error:`Search failed: ${s instanceof Error?s.message:String(s)}`}}}}}var Pe=k(require("fs")),Rl=k(require("path")),$l=50*1024*1024,Al=4e4;function El(t){let e=t.toString("latin1"),r={},s=[],n=0,i=e.match(/\/Type\s*\/Page\b/g);n=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=it(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=it(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=it(l[1]));let c=e.match(/\/Creator\s*\(([^)]*)\)/);c&&(r.creator=it(c[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let h=d[1],f=Ol(h);f.trim()&&s.push(f);try{let m=require("zlib"),g=Buffer.from(h,"latin1"),y=m.inflateSync(g).toString("latin1"),b=Ol(y);b.trim()&&!s.includes(b)&&s.push(b)}catch{}}return{text:s.join(`
129
129
  `).replace(/\r\n/g,`
130
130
  `).replace(/\n{3,}/g,`
131
131
 
132
- `).trim(),pages:n,metadata:r}}function Al(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,s;for(;(s=r.exec(t))!==null;)e.push(nt(s[1]));let n=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=n.exec(t))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(u=>nt(u.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(t))!==null;)e.push(nt(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
133
- `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function nt(t){return t.replace(/\\n/g,`
134
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Rl(t){let e=r=>Ol.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let s=e(r.path);if(!je.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let n=je.statSync(s);if(n.size>Cl)return{success:!1,output:"",error:`File too large: ${(n.size/1024/1024).toFixed(1)}MB (max: ${Cl/1024/1024}MB)`};try{let i=je.readFileSync(s),{text:o,pages:a,metadata:l}=El(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
132
+ `).trim(),pages:n,metadata:r}}function Ol(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,s;for(;(s=r.exec(t))!==null;)e.push(it(s[1]));let n=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(s=n.exec(t))!==null;){let l=s[1].match(/\(([^)]*)\)/g);if(l){let c=l.map(u=>it(u.slice(1,-1))).join("");e.push(c)}}let i=/\(([^)]*)\)\s*'/g;for(;(s=i.exec(t))!==null;)e.push(it(s[1]));let o=e.join(" ");return o=o.replace(/\\n/g,`
133
+ `).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),o}function it(t){return t.replace(/\\n/g,`
134
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,r)=>String.fromCharCode(parseInt(r,8)))}function Il(t){let e=r=>Rl.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let s=e(r.path);if(!Pe.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!s.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let n=Pe.statSync(s);if(n.size>$l)return{success:!1,output:"",error:`File too large: ${(n.size/1024/1024).toFixed(1)}MB (max: ${$l/1024/1024}MB)`};try{let i=Pe.readFileSync(s),{text:o,pages:a,metadata:l}=El(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
135
135
 
136
- [No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let c=o;return c.length>$l&&(c=c.slice(0,$l)+`
136
+ [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>Al&&(c=c.slice(0,Al)+`
137
137
 
138
138
  [... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(n.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
139
139
  `)}
140
- ${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let s=e(r.path);if(!je.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let n=je.statSync(s),i=je.readFileSync(s),{pages:o,metadata:a}=El(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(n.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${n.mtime.toISOString()}`].filter(Boolean).join(`
141
- `)}}catch(n){return{success:!1,output:"",error:`Failed to read PDF metadata: ${n instanceof Error?n.message:String(n)}`}}}}]}var Pl=require("child_process"),Pr=k(require("fs")),Ml=k(require("os")),Fl=k(require("path")),Ll=1e4,Il=16e3;function bt(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var jl={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>bt("tsx")?`tsx "${t}"`:bt("ts-node")?`ts-node --transpileOnly "${t}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${t}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:t=>bt("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>bt("python3")||bt("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>bt("bash")}};async function Zm(t,e,r=Ll){let s=jl[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(jl).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let n=Ml.tmpdir(),i=Fl.join(n,`hablas_exec_${Date.now()}${s.extension}`);try{Pr.writeFileSync(i,t,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Pl.exec)(o,{timeout:r,maxBuffer:5242880,cwd:n,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{let h=Date.now()-a;l({success:p===0,stdout:u.slice(0,Il),stderr:d.slice(0,Il/2),exitCode:p??1,duration:h,language:e})}),c.on("error",p=>{let h=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Pr.unlinkSync(i)}catch{}}}function eg(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function Dl(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||eg(e),s=Math.min(Math.max(1e3,t.timeout||Ll),3e4),n=await Zm(e,r,s),i=[];return i.push(`Language: ${n.language} | Exit: ${n.exitCode} | Duration: ${n.duration}ms`),i.push(""),n.stdout&&(i.push("Output:"),i.push(n.stdout)),n.stderr&&(i.push(n.stdout?`
140
+ ${c}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let s=e(r.path);if(!Pe.existsSync(s))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let n=Pe.statSync(s),i=Pe.readFileSync(s),{pages:o,metadata:a}=El(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(n.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${n.mtime.toISOString()}`].filter(Boolean).join(`
141
+ `)}}catch(n){return{success:!1,output:"",error:`Failed to read PDF metadata: ${n instanceof Error?n.message:String(n)}`}}}}]}var Ml=require("child_process"),Mr=k(require("fs")),Fl=k(require("os")),Ll=k(require("path")),Dl=1e4,jl=16e3;function xt(t){try{let{execSync:e}=require("child_process");return e(`which ${t} 2>/dev/null || where ${t} 2>NUL`,{stdio:"ignore"}),!0}catch{return!1}}var Pl={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>xt("tsx")?`tsx "${t}"`:xt("ts-node")?`ts-node --transpileOnly "${t}"`:`node --no-warnings -e "require('esbuild').buildSync({entryPoints:['${t}'],write:false,format:'cjs'}).outputFiles.forEach(f=>eval(f.text))"`,available:()=>!0},python:{extension:".py",command:t=>xt("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>xt("python3")||xt("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>xt("bash")}};async function tg(t,e,r=Dl){let s=Pl[e];if(!s)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Pl).join(", ")}`,exitCode:1,duration:0,language:e};if(!s.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let n=Fl.tmpdir(),i=Ll.join(n,`hablas_exec_${Date.now()}${s.extension}`);try{Mr.writeFileSync(i,t,"utf-8");let o=s.command(i),a=Date.now();return await new Promise(l=>{let c=(0,Ml.exec)(o,{timeout:r,maxBuffer:5242880,cwd:n,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";c.stdout?.on("data",p=>{u+=p}),c.stderr?.on("data",p=>{d+=p}),c.on("close",p=>{let h=Date.now()-a;l({success:p===0,stdout:u.slice(0,jl),stderr:d.slice(0,jl/2),exitCode:p??1,duration:h,language:e})}),c.on("error",p=>{let h=Date.now()-a;l({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Mr.unlinkSync(i)}catch{}}}function rg(t){return/\b(interface|type|enum|as\s+\w|:\s*(string|number|boolean|any)\b|<[A-Z]\w*>)/.test(t)?"typescript":/^(import\s+\w|from\s+\w|def\s+\w|class\s+\w|print\s*\(|if\s+__name__)/m.test(t)?"python":/^(#!\/bin\/bash|echo\s|export\s|if\s+\[|for\s+\w+\s+in)/m.test(t)?"bash":"javascript"}function Nl(){return[{name:"execute_code",description:"Execute a code snippet and return the output. Supports JavaScript, TypeScript, Python, and Bash. Code runs in a temporary file with a timeout. Use this to test code, run calculations, verify logic, or prototype solutions.",safety:"confirm",parameters:{code:{type:"string",description:"The code to execute",required:!0},language:{type:"string",description:"Language: javascript, typescript, python, bash (auto-detected if omitted)",required:!1},timeout:{type:"number",description:"Timeout in milliseconds (default: 10000, max: 30000)",required:!1}},execute:async t=>{let e=t.code;if(!e?.trim())return{success:!1,output:"",error:"Code is required"};let r=t.language?.toLowerCase()||rg(e),s=Math.min(Math.max(1e3,t.timeout||Dl),3e4),n=await tg(e,r,s),i=[];return i.push(`Language: ${n.language} | Exit: ${n.exitCode} | Duration: ${n.duration}ms`),i.push(""),n.stdout&&(i.push("Output:"),i.push(n.stdout)),n.stderr&&(i.push(n.stdout?`
142
142
  Errors/Warnings:`:"Errors:"),i.push(n.stderr)),!n.stdout&&!n.stderr&&i.push("(no output)"),{success:n.success,output:i.join(`
143
- `),error:n.success?void 0:n.stderr||`Exit code: ${n.exitCode}`}}}]}var Dr=k(require("fs")),xe=k(require("path"));var tg=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org","live.staticflickr.com","flickr.com","images.rawpixel.com","rawpixel.com"],rg=[/images\.unsplash\.com/i,/images\.pexels\.com/i,/cdn\.pixabay\.com\/photo/i,/upload\.wikimedia\.org\/wikipedia\/commons/i,/live\.staticflickr\.com/i,/images\.rawpixel\.com/i];function Rn(t){let e=String(t||"").toLowerCase().trim();return!e||e==="generic"?"generic":e==="hero"||e.includes("wallpaper")||e.includes("background")||e.includes("banner")?"hero":e==="product"||e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":e==="icon"||e.includes("icon")||e.includes("logo")?"icon":e==="avatar"||e.includes("avatar")||e.includes("profile")||e.includes("portrait")?"avatar":e==="banner"?"banner":"generic"}var sg=new Set(["image","images","photo","photos","picture","pictures","free","download","asset","assets","website","site","stock","hd","4k","8k","for","with","and","the","a","an","of","in","on","at","to","from","is","are","high","quality","beautiful","nice","new","best","top"]);function Mr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!sg.has(e))}function Fr(t,e){let r=[...new Set(Mr(t))].slice(0,6);return r.length>0?r.join(" "):t.trim().slice(0,60)}function Ht(t){try{let e=new URL(t).hostname.toLowerCase();return tg.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function ng(t){return rg.some(e=>e.test(t))}function Lr(t,e,r,s,n=[]){let i=Ht(t),o=[],a=[],l=0;if(i&&(l+=20,o.push("trusted-host")),ng(t)&&(l+=15,o.push("cdn-direct")),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=8,o.push("image-ext")),(/\/photos?\/[^/?#]+/i.test(t)||/\/images?\/[^/?#]+/i.test(t))&&(l+=6,o.push("photo-page")),n.length>0){let u=Mr([e,r,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),d=new Set(u),p=n.filter(h=>d.has(h));p.length>0&&(l+=p.length*10,o.push("query-match:"+p.slice(0,3).join(",")))}let c=[e,r,t].join(" ").toLowerCase();return(s==="hero"||s==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(c)&&(l+=5,o.push("kind-hero")),(s==="product"||s==="thumbnail")&&/product|closeup|detail|item|buy/i.test(c)&&(l+=5,o.push("kind-product")),(s==="icon"||s==="avatar")&&/icon|avatar|logo|portrait|profile/i.test(c)&&(l+=5,o.push("kind-icon")),/javascript|\.woff|\.eot|\.ttf|\.css/i.test(t)&&(l-=30,a.push("non-image-resource")),{score:l,positives:o,negatives:a,trusted:i}}function Nl(t,e){let r=Fr(t,e),s=encodeURIComponent(r);return r?[{source:"unsplash",url:`https://unsplash.com/s/photos/${s}`},{source:"pexels",url:`https://www.pexels.com/search/${s}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${s}/`}]:[]}function Ul(t,e){let r=Fr(t,e);return[`${r} site:unsplash.com/photos`,`${r} site:pexels.com/photo`,`${r} site:pixabay.com/photos`,`${r} site:commons.wikimedia.org/wiki/File`]}function ig(t,e){try{let r=t.split(",")[0].trim().split(/\s+/)[0],s=new URL(r,e);return/^https?:$/i.test(s.protocol)?s.href:null}catch{return null}}function xt(t,e){let r=new Set,s=[];function n(i){let o=ig(i,e);o&&!r.has(o)&&(r.add(o),s.push(o))}for(let i of t.matchAll(/<meta[^>]+(?:property|name)=["'](?:og:image(?::secure_url)?|twitter:image(?::src)?)["'][^>]+content=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["'](?:og:image|twitter:image)/gi))n(i[1]);for(let i of t.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi))try{let o=JSON.parse(i[1]),a=[o?.image,o?.logo,o?.thumbnail,o?.primaryImageOfPage];for(let l of a)typeof l=="string"?n(l):typeof l?.url=="string"?n(l.url):typeof l?.contentUrl=="string"?n(l.contentUrl):Array.isArray(l)&&l.forEach(c=>{typeof c=="string"?n(c):c?.url&&n(c.url)})}catch{}for(let i of t.matchAll(/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<img[^>]+data-(?:src|lazy|original|lazy-src)=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/srcset=["']([^"']+)["']/gi)){let o=i[1].split(",").map(a=>{let l=a.trim().split(/\s+/);return{url:l[0],w:parseInt(l[1]??"0")||0}}).sort((a,l)=>l.w-a.w)[0];o?.url&&n(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))n(i[1]);return s.filter(i=>/\/(icon|favicon|logo-|pixel|tracking|spacer|blank)\b/i.test(i)||/data:image\//i.test(i)||/\d{1,3}x\d{1,3}\.(gif|png)/i.test(i)?!1:Ht(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function ql(t,e){let r=new Set,s=[];for(let n of t.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))try{let i=new URL(n[1],e),o=i.hostname.toLowerCase(),a=i.pathname;(o==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(a)||(o==="www.pexels.com"||o==="pexels.com")&&/^\/photo\/[^?#]+/i.test(a)||o==="pixabay.com"&&/^\/(?:photos|images)\/[^?#]+/i.test(a)||o==="commons.wikimedia.org"&&/^\/wiki\/File:/i.test(a))&&!r.has(i.href)&&(r.add(i.href),s.push(i.href))}catch{}return s.slice(0,20)}var Bl=15*1024*1024,Hl=15e3,og=5;function ag(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return xe.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Wl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,text/html,application/xhtml+xml;q=0.9","Accept-Language":"en-US,en;q=0.9",...e?{Referer:e}:{}}}async function lg(t){let e=await fetch(t,{signal:AbortSignal.timeout(Hl),redirect:"follow",headers:Wl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",s=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r))throw new Error("HTML page returned where a direct image was expected");let n=await e.arrayBuffer(),i=Buffer.from(n);if(i.length>Bl)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:s}}async function cg(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let s=await fetch(t,{signal:AbortSignal.timeout(Hl),redirect:"follow",headers:Wl(t)});if(!s.ok)throw new Error(`HTTP ${s.status} while downloading asset`);let n=s.headers.get("content-type")||"",i=s.url||t;if(/text\/html|application\/xhtml\+xml/i.test(n)){let l=await s.text(),c=xt(l,i).map(d=>({url:d,...Lr(d,"","",e)})).sort((d,p)=>p.score-d.score).slice(0,og);if(c.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let d of c)try{return await lg(d.url)}catch(p){u=String(p?.message||p)}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>Bl)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:n,finalUrl:i}}function ug(t){let e=t.toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("products")?"product":"generic"}function Vl(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),s=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!s)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:n,contentType:i,finalUrl:o}=await cg(r,ug(s)),a=xe.resolve(t,s),c=xe.extname(a)?a:a+ag(i,o);return Dr.mkdirSync(xe.dirname(c),{recursive:!0}),Dr.writeFileSync(c,n),{success:!0,output:`Downloaded asset: ${xe.relative(t,c)||xe.basename(c)}
143
+ `),error:n.success?void 0:n.stderr||`Exit code: ${n.exitCode}`}}}]}var Nr=k(require("fs")),Se=k(require("path"));var sg=["images.unsplash.com","unsplash.com","images.pexels.com","pexels.com","cdn.pixabay.com","pixabay.com","upload.wikimedia.org","commons.wikimedia.org","live.staticflickr.com","flickr.com","images.rawpixel.com","rawpixel.com"],ng=[/images\.unsplash\.com/i,/images\.pexels\.com/i,/cdn\.pixabay\.com\/photo/i,/upload\.wikimedia\.org\/wikipedia\/commons/i,/live\.staticflickr\.com/i,/images\.rawpixel\.com/i];function jn(t){let e=String(t||"").toLowerCase().trim();return!e||e==="generic"?"generic":e==="hero"||e.includes("wallpaper")||e.includes("background")||e.includes("banner")?"hero":e==="product"||e.includes("product")||e.includes("thumbnail")||e.includes("card")?"product":e==="icon"||e.includes("icon")||e.includes("logo")?"icon":e==="avatar"||e.includes("avatar")||e.includes("profile")||e.includes("portrait")?"avatar":e==="banner"?"banner":"generic"}var ig=new Set(["image","images","photo","photos","picture","pictures","free","download","asset","assets","website","site","stock","hd","4k","8k","for","with","and","the","a","an","of","in","on","at","to","from","is","are","high","quality","beautiful","nice","new","best","top"]);function Fr(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!ig.has(e))}function Lr(t,e){let r=[...new Set(Fr(t))].slice(0,6);return r.length>0?r.join(" "):t.trim().slice(0,60)}function Wt(t){try{let e=new URL(t).hostname.toLowerCase();return sg.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function og(t){return ng.some(e=>e.test(t))}function Dr(t,e,r,s,n=[]){let i=Wt(t),o=[],a=[],l=0;if(i&&(l+=20,o.push("trusted-host")),og(t)&&(l+=15,o.push("cdn-direct")),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(l+=8,o.push("image-ext")),(/\/photos?\/[^/?#]+/i.test(t)||/\/images?\/[^/?#]+/i.test(t))&&(l+=6,o.push("photo-page")),n.length>0){let u=Fr([e,r,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),d=new Set(u),p=n.filter(h=>d.has(h));p.length>0&&(l+=p.length*10,o.push("query-match:"+p.slice(0,3).join(",")))}let c=[e,r,t].join(" ").toLowerCase();return(s==="hero"||s==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(c)&&(l+=5,o.push("kind-hero")),(s==="product"||s==="thumbnail")&&/product|closeup|detail|item|buy/i.test(c)&&(l+=5,o.push("kind-product")),(s==="icon"||s==="avatar")&&/icon|avatar|logo|portrait|profile/i.test(c)&&(l+=5,o.push("kind-icon")),/javascript|\.woff|\.eot|\.ttf|\.css/i.test(t)&&(l-=30,a.push("non-image-resource")),{score:l,positives:o,negatives:a,trusted:i}}function Ul(t,e){let r=Lr(t,e),s=encodeURIComponent(r);return r?[{source:"unsplash",url:`https://unsplash.com/s/photos/${s}`},{source:"pexels",url:`https://www.pexels.com/search/${s}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${s}/`}]:[]}function ql(t,e){let r=Lr(t,e);return[`${r} site:unsplash.com/photos`,`${r} site:pexels.com/photo`,`${r} site:pixabay.com/photos`,`${r} site:commons.wikimedia.org/wiki/File`]}function ag(t,e){try{let r=t.split(",")[0].trim().split(/\s+/)[0],s=new URL(r,e);return/^https?:$/i.test(s.protocol)?s.href:null}catch{return null}}function St(t,e){let r=new Set,s=[];function n(i){let o=ag(i,e);o&&!r.has(o)&&(r.add(o),s.push(o))}for(let i of t.matchAll(/<meta[^>]+(?:property|name)=["'](?:og:image(?::secure_url)?|twitter:image(?::src)?)["'][^>]+content=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["'](?:og:image|twitter:image)/gi))n(i[1]);for(let i of t.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi))try{let o=JSON.parse(i[1]),a=[o?.image,o?.logo,o?.thumbnail,o?.primaryImageOfPage];for(let l of a)typeof l=="string"?n(l):typeof l?.url=="string"?n(l.url):typeof l?.contentUrl=="string"?n(l.contentUrl):Array.isArray(l)&&l.forEach(c=>{typeof c=="string"?n(c):c?.url&&n(c.url)})}catch{}for(let i of t.matchAll(/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/<img[^>]+data-(?:src|lazy|original|lazy-src)=["']([^"']+)["']/gi))n(i[1]);for(let i of t.matchAll(/srcset=["']([^"']+)["']/gi)){let o=i[1].split(",").map(a=>{let l=a.trim().split(/\s+/);return{url:l[0],w:parseInt(l[1]??"0")||0}}).sort((a,l)=>l.w-a.w)[0];o?.url&&n(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))n(i[1]);return s.filter(i=>/\/(icon|favicon|logo-|pixel|tracking|spacer|blank)\b/i.test(i)||/data:image\//i.test(i)||/\d{1,3}x\d{1,3}\.(gif|png)/i.test(i)?!1:Wt(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function Bl(t,e){let r=new Set,s=[];for(let n of t.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))try{let i=new URL(n[1],e),o=i.hostname.toLowerCase(),a=i.pathname;(o==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(a)||(o==="www.pexels.com"||o==="pexels.com")&&/^\/photo\/[^?#]+/i.test(a)||o==="pixabay.com"&&/^\/(?:photos|images)\/[^?#]+/i.test(a)||o==="commons.wikimedia.org"&&/^\/wiki\/File:/i.test(a))&&!r.has(i.href)&&(r.add(i.href),s.push(i.href))}catch{}return s.slice(0,20)}var Hl=15*1024*1024,Wl=15e3,lg=5;function cg(t,e){if(/image\/png/i.test(t))return".png";if(/image\/jpe?g/i.test(t))return".jpg";if(/image\/webp/i.test(t))return".webp";if(/image\/gif/i.test(t))return".gif";if(/image\/svg\+xml/i.test(t))return".svg";try{return Se.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function Vl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{e=""}return{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",Accept:"image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8,text/html,application/xhtml+xml;q=0.9","Accept-Language":"en-US,en;q=0.9",...e?{Referer:e}:{}}}async function ug(t){let e=await fetch(t,{signal:AbortSignal.timeout(Wl),redirect:"follow",headers:Vl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",s=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r))throw new Error("HTML page returned where a direct image was expected");let n=await e.arrayBuffer(),i=Buffer.from(n);if(i.length>Hl)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:s}}async function fg(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let s=await fetch(t,{signal:AbortSignal.timeout(Wl),redirect:"follow",headers:Vl(t)});if(!s.ok)throw new Error(`HTTP ${s.status} while downloading asset`);let n=s.headers.get("content-type")||"",i=s.url||t;if(/text\/html|application\/xhtml\+xml/i.test(n)){let l=await s.text(),c=St(l,i).map(d=>({url:d,...Dr(d,"","",e)})).sort((d,p)=>p.score-d.score).slice(0,lg);if(c.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let d of c)try{return await ug(d.url)}catch(p){u=String(p?.message||p)}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await s.arrayBuffer(),a=Buffer.from(o);if(a.length>Hl)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:n,finalUrl:i}}function dg(t){let e=t.toLowerCase();return e.includes("hero")||e.includes("wallpaper")||e.includes("background")?"hero":e.includes("product")||e.includes("products")?"product":"generic"}function zl(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),s=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!s)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:n,contentType:i,finalUrl:o}=await fg(r,dg(s)),a=Se.resolve(t,s),c=Se.extname(a)?a:a+cg(i,o);return Nr.mkdirSync(Se.dirname(c),{recursive:!0}),Nr.writeFileSync(c,n),{success:!0,output:`Downloaded asset: ${Se.relative(t,c)||Se.basename(c)}
144
144
  Final source: ${o}
145
145
  Type: ${i||"unknown"}
146
- Size: ${n.length} bytes`}}catch(n){return{success:!1,output:"",error:`download failed: ${n?.message||String(n)}`}}}}}var Nr=k(require("fs")),Ur=k(require("path"));var jn=15e3,zl=5;function Kl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Gl(t,e){return t[e]|t[e+1]<<8}function fg(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],s=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+s}return{}}function dg(t){let e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30){let r=(t.readUInt16LE(26)&16383)+1,s=(t.readUInt16LE(28)&16383)+1;return{width:r,height:s}}return{}}function In(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:Kl(t,16),height:Kl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Gl(t,6),height:Gl(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...fg(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...dg(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function Xl(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{}return{"User-Agent":"Mozilla/5.0 (compatible; HablasBot/2.0; +https://hablas.dev)",Accept:"image/*,text/html,*/*;q=0.8",...e?{Referer:e}:{}}}async function Jl(t){let e=await fetch(t,{signal:AbortSignal.timeout(jn),redirect:"follow",headers:Xl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let r=e.headers.get("content-type")||"",s=e.url||t,n=await e.arrayBuffer(),i=Buffer.from(n).subarray(0,2*1024*1024),o=/text\/html|application\/xhtml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:s,html:o}}async function Yl(t){let e=await fetch(t,{signal:AbortSignal.timeout(jn),redirect:"follow",headers:{...Xl(t),Accept:"text/html,application/xhtml+xml;q=0.9,*/*;q=0.8"}});if(!e.ok)throw new Error(`HTTP ${e.status}`);return{finalUrl:e.url||t,html:await e.text()}}async function pg(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:Fr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),s=await fetch(`https://commons.wikimedia.org/w/api.php?${r}`,{signal:AbortSignal.timeout(jn),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!s.ok)throw new Error(`Wikimedia HTTP ${s.status}`);let n=await s.json();return Object.values(n?.query?.pages||{}).map(i=>({title:String(i?.title||""),url:String(i?.imageinfo?.[0]?.url||i?.imageinfo?.[0]?.thumburl||""),snippet:String(i?.title||"").replace(/^File:/i,""),source:"wikimedia"})).filter(i=>i.url.startsWith("http")).slice(0,e)}function hg(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
146
+ Size: ${n.length} bytes`}}catch(n){return{success:!1,output:"",error:`download failed: ${n?.message||String(n)}`}}}}}var Ur=k(require("fs")),qr=k(require("path"));var Mn=15e3,Kl=5;function Gl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Jl(t,e){return t[e]|t[e+1]<<8}function pg(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],s=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+s}return{}}function hg(t){let e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30){let r=(t.readUInt16LE(26)&16383)+1,s=(t.readUInt16LE(28)&16383)+1;return{width:r,height:s}}return{}}function Pn(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:Gl(t,16),height:Gl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:Jl(t,6),height:Jl(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...pg(t),ext:".jpg"}:t.length>=16&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP"?{...hg(t),ext:".webp"}:{ext:e.includes("svg")?".svg":".bin"}}function Ql(t){let e="";try{let r=new URL(t);e=`${r.protocol}//${r.host}/`}catch{}return{"User-Agent":"Mozilla/5.0 (compatible; HablasBot/2.0; +https://hablas.dev)",Accept:"image/*,text/html,*/*;q=0.8",...e?{Referer:e}:{}}}async function Xl(t){let e=await fetch(t,{signal:AbortSignal.timeout(Mn),redirect:"follow",headers:Ql(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let r=e.headers.get("content-type")||"",s=e.url||t,n=await e.arrayBuffer(),i=Buffer.from(n).subarray(0,2*1024*1024),o=/text\/html|application\/xhtml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:s,html:o}}async function Yl(t){let e=await fetch(t,{signal:AbortSignal.timeout(Mn),redirect:"follow",headers:{...Ql(t),Accept:"text/html,application/xhtml+xml;q=0.9,*/*;q=0.8"}});if(!e.ok)throw new Error(`HTTP ${e.status}`);return{finalUrl:e.url||t,html:await e.text()}}async function mg(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:Lr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),s=await fetch(`https://commons.wikimedia.org/w/api.php?${r}`,{signal:AbortSignal.timeout(Mn),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!s.ok)throw new Error(`Wikimedia HTTP ${s.status}`);let n=await s.json();return Object.values(n?.query?.pages||{}).map(i=>({title:String(i?.title||""),url:String(i?.imageinfo?.[0]?.url||i?.imageinfo?.[0]?.thumburl||""),snippet:String(i?.title||"").replace(/^File:/i,""),source:"wikimedia"})).filter(i=>i.url.startsWith("http")).slice(0,e)}function gg(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
147
147
 
148
148
  Context from user: "${t}"
149
149
 
@@ -162,39 +162,39 @@ Rules:
162
162
  - confidence: float 0.0\u20131.0
163
163
  - suggestedUse: one of "hero", "product", "icon", "generic", "reject"
164
164
  - issues: list any quality or relevance problems (empty array if none)
165
- - Do NOT output anything outside the JSON object`}async function mg(t,e,r,s){let n;if(t.provider==="nvidia")n=ce.apiUrl;else if(t.provider==="mistral")n="https://api.mistral.ai/v1";else if(t.provider==="custom"&&t.apiUrl)n=t.apiUrl;else throw new Error("No API URL configured for vision \u2014 use /provider to configure a provider");let i=`data:${r};base64,${e.toString("base64")}`,o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=t.vision.primaryModel,l=await fetch(n.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:hg(s)},{role:"user",content:[{type:"text",text:"Inspect this image."},{type:"image_url",image_url:{url:i}}]}],temperature:.1,max_tokens:300})});if(!l.ok)throw new Error(`Vision API HTTP ${l.status}`);let c=await l.json(),u=String(c?.choices?.[0]?.message?.content??""),d=null,p=u.indexOf("{"),h=u.lastIndexOf("}");if(p!==-1&&h>p)try{d=JSON.parse(u.slice(p,h+1))}catch{}if(!d)throw new Error("Vision response was not valid JSON");return{model:a,success:!0,description:String(d.description??""),suitable:!!d.suitable,confidence:Number(d.confidence??0),issues:Array.isArray(d.issues)?d.issues.map(String):[],suggestedUse:String(d.suggestedUse??"generic"),summary:String(d.summary??""),raw:u}}function gg(t,e,r){return!e||!r?0:(t==="hero"||t==="banner")&&e>=1200&&r>=500?12:(t==="product"||t==="thumbnail")&&e>=400&&r>=400?8:t==="icon"&&e>=64&&e<=512?6:t==="generic"&&e>=600&&r>=400?5:0}function Ql(t,e){return[{name:"search_image_candidates",description:["Search for ranked image URL candidates from trusted stock sites (Unsplash, Pexels, Pixabay, Wikimedia).","Returns a scored list of direct image URLs ready for inspect_image.","Use kind to signal intended use: hero, product, icon, avatar, banner, thumbnail, or generic.",'query should describe what you need visually (e.g. "mountain sunset landscape", "red sports car", "smiling woman portrait").'].join(" "),safety:"safe",parameters:{query:{type:"string",description:"Visual description of the image you need",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic (default: generic)",required:!1},max_results:{type:"number",description:"Max candidates to return (1\u201310, default: 5)",required:!1}},execute:async r=>{let s=String(r.query||"").trim();if(!s)return{success:!1,output:"",error:"query is required"};let n=Rn(r.kind),i=Math.min(Math.max(1,Number(r.max_results??5)),10),o=Mr(s),a=new Map,l=[],c=(p,h,f,m)=>{if(a.has(p))return;let g=Lr(p,h,f,n,o);a.set(p,{url:p,title:h,snippet:f,source:m,...g})};for(let p of Nl(s,n))try{let{finalUrl:h,html:f}=await Yl(p.url),m=ql(f,h),g=0;for(let b of m.slice(0,zl*2)){if(g>=zl)break;try{let{finalUrl:w,html:S}=await Yl(b),C=xt(S,w)[0];C&&(c(C,p.source+" photo",s,p.source),g++)}catch{}}let y=xt(f,h);for(let b of y.slice(0,6))c(b,p.source,s,p.source);g===0&&y.length===0&&l.push(`${p.source}: no images found`)}catch(h){l.push(`${p.source}: ${String(h?.message??h)}`)}try{let p=await pg(s,Math.max(4,i));for(let h of p)c(h.url,h.title,h.snippet,h.source)}catch(p){l.push(`wikimedia: ${String(p?.message??p)}`)}if(a.size<i)for(let p of Ul(s,n))try{let h=await On(p,Math.max(6,i));for(let f of h)c(f.url,f.title,f.snippet,f.source);if(a.size>=i*2)break}catch{}let u=[...a.values()].sort((p,h)=>h.score-p.score).slice(0,i);if(u.length===0)return{success:!0,output:`No image candidates found for "${s}".${l.length?`
165
+ - Do NOT output anything outside the JSON object`}async function yg(t,e,r,s){let n;if(t.provider==="nvidia")n=ce.apiUrl;else if(t.provider==="mistral")n="https://api.mistral.ai/v1";else if(t.provider==="custom"&&t.apiUrl)n=t.apiUrl;else throw new Error("No API URL configured for vision \u2014 use /provider to configure a provider");let i=`data:${r};base64,${e.toString("base64")}`,o={"Content-Type":"application/json"};t.apiKey&&(o.Authorization=`Bearer ${t.apiKey}`);let a=t.vision.primaryModel,l=await fetch(n.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:gg(s)},{role:"user",content:[{type:"text",text:"Inspect this image."},{type:"image_url",image_url:{url:i}}]}],temperature:.1,max_tokens:300})});if(!l.ok)throw new Error(`Vision API HTTP ${l.status}`);let c=await l.json(),u=String(c?.choices?.[0]?.message?.content??""),d=null,p=u.indexOf("{"),h=u.lastIndexOf("}");if(p!==-1&&h>p)try{d=JSON.parse(u.slice(p,h+1))}catch{}if(!d)throw new Error("Vision response was not valid JSON");return{model:a,success:!0,description:String(d.description??""),suitable:!!d.suitable,confidence:Number(d.confidence??0),issues:Array.isArray(d.issues)?d.issues.map(String):[],suggestedUse:String(d.suggestedUse??"generic"),summary:String(d.summary??""),raw:u}}function wg(t,e,r){return!e||!r?0:(t==="hero"||t==="banner")&&e>=1200&&r>=500?12:(t==="product"||t==="thumbnail")&&e>=400&&r>=400?8:t==="icon"&&e>=64&&e<=512?6:t==="generic"&&e>=600&&r>=400?5:0}function Zl(t,e){return[{name:"search_image_candidates",description:["Search for ranked image URL candidates from trusted stock sites (Unsplash, Pexels, Pixabay, Wikimedia).","Returns a scored list of direct image URLs ready for inspect_image.","Use kind to signal intended use: hero, product, icon, avatar, banner, thumbnail, or generic.",'query should describe what you need visually (e.g. "mountain sunset landscape", "red sports car", "smiling woman portrait").'].join(" "),safety:"safe",parameters:{query:{type:"string",description:"Visual description of the image you need",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic (default: generic)",required:!1},max_results:{type:"number",description:"Max candidates to return (1\u201310, default: 5)",required:!1}},execute:async r=>{let s=String(r.query||"").trim();if(!s)return{success:!1,output:"",error:"query is required"};let n=jn(r.kind),i=Math.min(Math.max(1,Number(r.max_results??5)),10),o=Fr(s),a=new Map,l=[],c=(p,h,f,m)=>{if(a.has(p))return;let g=Dr(p,h,f,n,o);a.set(p,{url:p,title:h,snippet:f,source:m,...g})};for(let p of Ul(s,n))try{let{finalUrl:h,html:f}=await Yl(p.url),m=Bl(f,h),g=0;for(let b of m.slice(0,Kl*2)){if(g>=Kl)break;try{let{finalUrl:w,html:S}=await Yl(b),C=St(S,w)[0];C&&(c(C,p.source+" photo",s,p.source),g++)}catch{}}let y=St(f,h);for(let b of y.slice(0,6))c(b,p.source,s,p.source);g===0&&y.length===0&&l.push(`${p.source}: no images found`)}catch(h){l.push(`${p.source}: ${String(h?.message??h)}`)}try{let p=await mg(s,Math.max(4,i));for(let h of p)c(h.url,h.title,h.snippet,h.source)}catch(p){l.push(`wikimedia: ${String(p?.message??p)}`)}if(a.size<i)for(let p of ql(s,n))try{let h=await In(p,Math.max(6,i));for(let f of h)c(f.url,f.title,f.snippet,f.source);if(a.size>=i*2)break}catch{}let u=[...a.values()].sort((p,h)=>h.score-p.score).slice(0,i);if(u.length===0)return{success:!0,output:`No image candidates found for "${s}".${l.length?`
166
166
  Notes:
167
167
  - `+l.join(`
168
168
  - `):""}`};let d=[`Image candidates for: "${s}" (kind=${n}) \u2014 ${u.length} results`,""];return u.forEach((p,h)=>{d.push(`[${h+1}] score=${p.score} trusted=${p.trusted?"yes":"no"} source=${p.source}`),d.push(` url: ${p.url}`),p.title&&d.push(` title: ${p.title}`),p.positives.length&&d.push(` \u2713 ${p.positives.join(", ")}`),p.negatives.length&&d.push(` \u2717 ${p.negatives.join(", ")}`),d.push("")}),l.length&&(d.push("Notes:"),l.slice(0,5).forEach(p=>d.push(" - "+p))),{success:!0,output:d.join(`
169
- `)}}},{name:"inspect_image",description:["Deeply inspect a remote image URL or local file path.","Returns: content-type, dimensions (w\xD7h), direct-image confirmation, trusted-host status, scoring, and an optional vision analysis.","Use after search_image_candidates to verify the best pick before adopting it.","Set use_vision=false to skip vision (faster, cheaper). Default: true when configured.",'The context parameter tells the vision model what you need (e.g. "hero image for a tech startup landing page").'].join(" "),safety:"safe",parameters:{source:{type:"string",description:"Remote URL (https://...) or local file path",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic",required:!1},context:{type:"string",description:"Describe what you need this image for (used for vision analysis)",required:!1},use_vision:{type:"string",description:'"true" or "false" \u2014 whether to run vision model analysis (default: true)',required:!1}},execute:async r=>{let s=String(r.source||"").trim();if(!s)return{success:!1,output:"",error:"source is required"};let n=Rn(r.kind),i=String(r.context||s).slice(0,200),o=String(r.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${s}`,""],l="unknown",c,u,d=!1,p=!1,h=s,f=null,m=!1,g=[];try{if(/^https?:\/\//i.test(s)){let w=await Jl(s);if(h=w.finalUrl,l=w.contentType,p=Ht(h),w.html){if(m=!0,g=xt(w.html,h),g.length>0){let S=g[0];try{let _=await Jl(S);h=_.finalUrl,l=_.contentType,f=_.bytes,p=Ht(h);let C=In(f,l);c=C.width,u=C.height,d=/^image\//i.test(l)}catch(_){a.push(` [warn] could not fetch best candidate: ${_.message}`)}}}else{f=w.bytes,d=/^image\//i.test(l)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(h);let S=In(f,l);c=S.width,u=S.height}}else{let w=Ur.resolve(t,s);if(!Nr.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${s}`};f=Nr.readFileSync(w).subarray(0,2*1024*1024);let S=Ur.extname(w).toLowerCase();l={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml"}[S]||"application/octet-stream",d=!0,p=!1;let _=In(f,l);c=_.width,u=_.height}}catch(w){return{success:!1,output:"",error:`Failed to fetch/read source: ${w.message}`}}a.push(` final URL: ${h}`),a.push(` content-type: ${l}`),a.push(` direct image: ${d?"yes":"no (HTML page)"}`),a.push(` trusted host: ${p?"yes":"no"}`),c&&u&&a.push(` dimensions: ${c} \xD7 ${u} px`),f&&a.push(` size (fetched): ${(f.length/1024).toFixed(1)} KB`),m&&(a.push(" resolved via: HTML page extraction"),g.length>1&&(a.push(` other candidates found (${g.length-1}):`),g.slice(1,4).forEach(w=>a.push(` - ${w}`))));let y=gg(n,c,u);if(c&&u){let w=y>0;a.push(` size verdict: ${w?"\u2713 adequate for "+n:"\u2717 may be too small for "+n} (${c}\xD7${u})`)}if(o&&e.vision.enabled&&f&&/^image\//i.test(l)){a.push(""),a.push(" Vision analysis:");try{let w=await mg(e,f.subarray(0,e.vision.maxImageBytes),l,i);a.push(` model: ${w.model}`),a.push(` description: ${w.description}`),a.push(` suitable: ${w.suitable?"yes":"no"}`),a.push(` confidence: ${(w.confidence*100).toFixed(0)}%`),a.push(` suggested: ${w.suggestedUse}`),a.push(` summary: ${w.summary}`),w.issues.length>0&&a.push(` issues: ${w.issues.join("; ")}`)}catch(w){a.push(` [vision unavailable: ${w.message}]`),e.vision.enabled||a.push(" (enable vision in config to use this feature)")}}else e.vision.enabled||(a.push(""),a.push(" [vision: disabled in config]"));a.push("");let b=d&&(p||/^image\//i.test(l));return a.push(` VERDICT: ${b?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
170
- `)}}}]}var We=k(require("fs")),ne=k(require("path")),yg=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage",".turbo"]),wg=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java"]),bg=/\b(index|main|app|server|start|entry|cli)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/i;function xg(t,e,r){let s=[],n=ne.dirname(e),i=[/from\s+['"]([^'"]+)['"]/g,/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let a of i){let l;for(;(l=a.exec(t))!==null;){let c=l[1];if(c.startsWith(".")){let u=ne.resolve(n,c);if(!We.existsSync(u)){for(let d of[".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"])if(We.existsSync(u+d)){u=u+d;break}}We.existsSync(u)&&s.push(ne.relative(r,u))}}}let o=[/^from\s+\.\S*\s+import/gm,/^import\s+\./gm];for(let a of o)for(;a.exec(t)!==null;)s.push(n);return[...new Set(s)]}function Sg(t,e){let r=[];if(e==="ts"||e==="js"){let s=[/export\s+(?:default\s+)?(?:function|class|const|let|var|interface|type|enum)\s+(\w+)/g,/export\s*\{\s*([^}]+)\}/g];for(let n of s){let i;for(;(i=n.exec(t))!==null;){let o=i[1].split(",").map(a=>a.trim().split(/\s+as\s+/).pop().trim());r.push(...o.filter(Boolean))}}}return[...new Set(r)].slice(0,20)}function Zl(t,e){let r=[];try{let s=We.readdirSync(t,{withFileTypes:!0});for(let n of s){if(yg.has(n.name)||n.name.startsWith("."))continue;let i=ne.join(t,n.name);n.isDirectory()?r.push(...Zl(i,e)):wg.has(ne.extname(n.name))&&r.push(ne.relative(e,i))}}catch{}return r}function vg(t){let e=[],r=new Set,s=new Set;function n(i,o){if(s.has(i)){let l=o.indexOf(i);l!==-1&&e.push(o.slice(l));return}if(r.has(i))return;r.add(i),s.add(i);let a=t.get(i);if(a)for(let l of a.imports)n(l,[...o,l]);s.delete(i)}for(let i of t.keys())n(i,[i]);return e.slice(0,5)}function Pn(t,e=300){let r=Date.now(),s=Zl(t,t).slice(0,e),n=new Map;for(let a of s)try{let l=ne.join(t,a),c=We.readFileSync(l,"utf-8"),u=ne.extname(a).slice(1),d=["ts","tsx"].includes(u)?"ts":["js","jsx","mjs"].includes(u)?"js":u,p=c.split(`
171
- `).length,h=xg(c,l,t),f=Sg(c,d),m=bg.test(a);n.set(a,{path:a,imports:h,exports:f,references:[],isEntryPoint:m,lines:p,language:d})}catch{}for(let[a,l]of n)for(let c of l.imports){let u=n.get(c);u&&!u.references.includes(a)&&u.references.push(a)}let i=[...n.values()].filter(a=>a.isEntryPoint||a.references.length===0&&a.imports.length>0).map(a=>a.path).slice(0,5),o=vg(n);return{nodes:n,entryPoints:i,circularDeps:o,totalFiles:s.length,buildTime:Date.now()-r}}function ec(t){return[{name:"analyze_project",description:"Build a complete graph of the project: all files, imports, exports, entry points, and circular dependencies. Use this BEFORE making multi-file changes to understand the full impact. Returns ranked file importance.",safety:"safe",parameters:{focus:{type:"string",description:'Optional: focus on a subdirectory (e.g. "src/components")',required:!1},max_files:{type:"number",description:"Max files to analyze (default: 200)",required:!1}},execute:async n=>{try{let i=n.focus?ne.join(t,n.focus):t,o=n.max_files||200,a=Pn(i,o),l=[...a.nodes.values()].sort((u,d)=>d.references.length-u.references.length).slice(0,30),c=[`Project Graph \xB7 ${a.totalFiles} files \xB7 built in ${a.buildTime}ms`,"","\u2500\u2500 Entry Points \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...a.entryPoints.map(u=>` ${u}`),"","\u2500\u2500 Most Referenced Files (impact ranking) \u2500\u2500"];for(let u of l)u.references.length!==0&&(c.push(` ${u.path.padEnd(45)} \u2190 referenced by ${u.references.length} files`),u.exports.length&&c.push(` exports: ${u.exports.slice(0,6).join(", ")}`));if(a.circularDeps.length){c.push(""),c.push("\u2500\u2500 Circular Dependencies (\u26A0 fix before refactoring) \u2500\u2500");for(let u of a.circularDeps)c.push(` ${u.join(" \u2192 ")}`)}return c.push(""),c.push(`Total nodes: ${a.nodes.size} | Entry points: ${a.entryPoints.length} | Circular deps: ${a.circularDeps.length}`),{success:!0,output:c.join(`
172
- `)}}catch(i){return{success:!1,output:"",error:`Graph build failed: ${i.message}`}}}},{name:"find_references",description:"Find all files that import or reference a specific file or symbol. Use before renaming, moving, or deleting any file.",safety:"safe",parameters:{target:{type:"string",description:"File path or symbol name to find references for",required:!0}},execute:async n=>{try{let i=n.target,o=Pn(t,300),a=[],l=o.nodes.get(i);if(l){a.push(`File: ${i}`),a.push(`Referenced by ${l.references.length} files:`);for(let c of l.references)a.push(` ${c}`);a.push(""),a.push(`This file imports ${l.imports.length} files:`);for(let c of l.imports)a.push(` ${c}`)}else{a.push(`Symbol search: "${i}"`);let c=0;for(let[u,d]of o.nodes)d.exports.some(p=>p.toLowerCase().includes(i.toLowerCase()))&&(a.push(` exported from: ${u}`),a.push(` referenced by: ${d.references.join(", ")||"none"}`),c++);c||a.push(" No matches found.")}return{success:!0,output:a.join(`
173
- `)}}catch(i){return{success:!1,output:"",error:`Reference search failed: ${i.message}`}}}},{name:"impact_analysis",description:"Before changing a file, analyze the blast radius: which files will be affected and how critical the change is.",safety:"safe",parameters:{file:{type:"string",description:"File you intend to modify",required:!0}},execute:async n=>{try{let i=n.file,o=Pn(t,300),a=o.nodes.get(i);if(!a)return{success:!0,output:`File "${i}" not found in graph. It may be new.`};let l=new Set,c=[...a.references];for(;c.length;){let h=c.shift();if(!l.has(h)){l.add(h);let f=o.nodes.get(h);f&&c.push(...f.references)}}let u=l.size,d=u===0?"LOW":u<=3?"MEDIUM":u<=10?"HIGH":"CRITICAL",p=[`Impact Analysis: ${i}`,`Severity: ${d} (${u} files affected)`,"",`Direct referrers (${a.references.length}):`,...a.references.map(h=>` ${h}`)];if(l.size>a.references.length){p.push(""),p.push(`Transitive impact (${l.size} total):`);for(let h of[...l].slice(0,15))p.push(` ${h}`);l.size>15&&p.push(` ... and ${l.size-15} more`)}return p.push(""),p.push(`Exports: ${a.exports.join(", ")||"none"}`),p.push(`Imports: ${a.imports.length} files`),p.push(`Size: ${a.lines} lines`),{success:!0,output:p.join(`
174
- `)}}catch(i){return{success:!1,output:"",error:`Impact analysis failed: ${i.message}`}}}}]}var tc=require("child_process"),rc=k(require("fs")),sc=k(require("path"));function it(t,e,r=15e3){return new Promise(s=>{(0,tc.exec)(t,{cwd:e,timeout:r,maxBuffer:4*1024*1024},(n,i,o)=>{let a=n?n.code:void 0;s({out:i||"",err:o||"",code:typeof a=="number"?a:n?1:0})})})}function Wt(t){return rc.existsSync(sc.join(t,".git"))}function nc(t){return[{name:"git_status",description:"Show current git status: staged, unstaged, and untracked files. Use before committing or to understand what changed.",safety:"safe",parameters:{},execute:async()=>{if(!Wt(t))return{success:!0,output:"No git repository in this workspace."};let{out:o,err:a,code:l}=await it("git status --short --branch",t);if(l!==0)return{success:!1,output:"",error:a||"git status failed"};let c=o.trim().split(`
169
+ `)}}},{name:"inspect_image",description:["Deeply inspect a remote image URL or local file path.","Returns: content-type, dimensions (w\xD7h), direct-image confirmation, trusted-host status, scoring, and an optional vision analysis.","Use after search_image_candidates to verify the best pick before adopting it.","Set use_vision=false to skip vision (faster, cheaper). Default: true when configured.",'The context parameter tells the vision model what you need (e.g. "hero image for a tech startup landing page").'].join(" "),safety:"safe",parameters:{source:{type:"string",description:"Remote URL (https://...) or local file path",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic",required:!1},context:{type:"string",description:"Describe what you need this image for (used for vision analysis)",required:!1},use_vision:{type:"string",description:'"true" or "false" \u2014 whether to run vision model analysis (default: true)',required:!1}},execute:async r=>{let s=String(r.source||"").trim();if(!s)return{success:!1,output:"",error:"source is required"};let n=jn(r.kind),i=String(r.context||s).slice(0,200),o=String(r.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${s}`,""],l="unknown",c,u,d=!1,p=!1,h=s,f=null,m=!1,g=[];try{if(/^https?:\/\//i.test(s)){let w=await Xl(s);if(h=w.finalUrl,l=w.contentType,p=Wt(h),w.html){if(m=!0,g=St(w.html,h),g.length>0){let S=g[0];try{let _=await Xl(S);h=_.finalUrl,l=_.contentType,f=_.bytes,p=Wt(h);let C=Pn(f,l);c=C.width,u=C.height,d=/^image\//i.test(l)}catch(_){a.push(` [warn] could not fetch best candidate: ${_.message}`)}}}else{f=w.bytes,d=/^image\//i.test(l)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(h);let S=Pn(f,l);c=S.width,u=S.height}}else{let w=qr.resolve(t,s);if(!Ur.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${s}`};f=Ur.readFileSync(w).subarray(0,2*1024*1024);let S=qr.extname(w).toLowerCase();l={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml"}[S]||"application/octet-stream",d=!0,p=!1;let _=Pn(f,l);c=_.width,u=_.height}}catch(w){return{success:!1,output:"",error:`Failed to fetch/read source: ${w.message}`}}a.push(` final URL: ${h}`),a.push(` content-type: ${l}`),a.push(` direct image: ${d?"yes":"no (HTML page)"}`),a.push(` trusted host: ${p?"yes":"no"}`),c&&u&&a.push(` dimensions: ${c} \xD7 ${u} px`),f&&a.push(` size (fetched): ${(f.length/1024).toFixed(1)} KB`),m&&(a.push(" resolved via: HTML page extraction"),g.length>1&&(a.push(` other candidates found (${g.length-1}):`),g.slice(1,4).forEach(w=>a.push(` - ${w}`))));let y=wg(n,c,u);if(c&&u){let w=y>0;a.push(` size verdict: ${w?"\u2713 adequate for "+n:"\u2717 may be too small for "+n} (${c}\xD7${u})`)}if(o&&e.vision.enabled&&f&&/^image\//i.test(l)){a.push(""),a.push(" Vision analysis:");try{let w=await yg(e,f.subarray(0,e.vision.maxImageBytes),l,i);a.push(` model: ${w.model}`),a.push(` description: ${w.description}`),a.push(` suitable: ${w.suitable?"yes":"no"}`),a.push(` confidence: ${(w.confidence*100).toFixed(0)}%`),a.push(` suggested: ${w.suggestedUse}`),a.push(` summary: ${w.summary}`),w.issues.length>0&&a.push(` issues: ${w.issues.join("; ")}`)}catch(w){a.push(` [vision unavailable: ${w.message}]`),e.vision.enabled||a.push(" (enable vision in config to use this feature)")}}else e.vision.enabled||(a.push(""),a.push(" [vision: disabled in config]"));a.push("");let b=d&&(p||/^image\//i.test(l));return a.push(` VERDICT: ${b?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
170
+ `)}}}]}var We=k(require("fs")),ne=k(require("path")),bg=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage",".turbo"]),xg=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java"]),Sg=/\b(index|main|app|server|start|entry|cli)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/i;function vg(t,e,r){let s=[],n=ne.dirname(e),i=[/from\s+['"]([^'"]+)['"]/g,/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let a of i){let l;for(;(l=a.exec(t))!==null;){let c=l[1];if(c.startsWith(".")){let u=ne.resolve(n,c);if(!We.existsSync(u)){for(let d of[".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"])if(We.existsSync(u+d)){u=u+d;break}}We.existsSync(u)&&s.push(ne.relative(r,u))}}}let o=[/^from\s+\.\S*\s+import/gm,/^import\s+\./gm];for(let a of o)for(;a.exec(t)!==null;)s.push(n);return[...new Set(s)]}function _g(t,e){let r=[];if(e==="ts"||e==="js"){let s=[/export\s+(?:default\s+)?(?:function|class|const|let|var|interface|type|enum)\s+(\w+)/g,/export\s*\{\s*([^}]+)\}/g];for(let n of s){let i;for(;(i=n.exec(t))!==null;){let o=i[1].split(",").map(a=>a.trim().split(/\s+as\s+/).pop().trim());r.push(...o.filter(Boolean))}}}return[...new Set(r)].slice(0,20)}function ec(t,e){let r=[];try{let s=We.readdirSync(t,{withFileTypes:!0});for(let n of s){if(bg.has(n.name)||n.name.startsWith("."))continue;let i=ne.join(t,n.name);n.isDirectory()?r.push(...ec(i,e)):xg.has(ne.extname(n.name))&&r.push(ne.relative(e,i))}}catch{}return r}function kg(t){let e=[],r=new Set,s=new Set;function n(i,o){if(s.has(i)){let l=o.indexOf(i);l!==-1&&e.push(o.slice(l));return}if(r.has(i))return;r.add(i),s.add(i);let a=t.get(i);if(a)for(let l of a.imports)n(l,[...o,l]);s.delete(i)}for(let i of t.keys())n(i,[i]);return e.slice(0,5)}function Fn(t,e=300){let r=Date.now(),s=ec(t,t).slice(0,e),n=new Map;for(let a of s)try{let l=ne.join(t,a),c=We.readFileSync(l,"utf-8"),u=ne.extname(a).slice(1),d=["ts","tsx"].includes(u)?"ts":["js","jsx","mjs"].includes(u)?"js":u,p=c.split(`
171
+ `).length,h=vg(c,l,t),f=_g(c,d),m=Sg.test(a);n.set(a,{path:a,imports:h,exports:f,references:[],isEntryPoint:m,lines:p,language:d})}catch{}for(let[a,l]of n)for(let c of l.imports){let u=n.get(c);u&&!u.references.includes(a)&&u.references.push(a)}let i=[...n.values()].filter(a=>a.isEntryPoint||a.references.length===0&&a.imports.length>0).map(a=>a.path).slice(0,5),o=kg(n);return{nodes:n,entryPoints:i,circularDeps:o,totalFiles:s.length,buildTime:Date.now()-r}}function tc(t){return[{name:"analyze_project",description:"Build a complete graph of the project: all files, imports, exports, entry points, and circular dependencies. Use this BEFORE making multi-file changes to understand the full impact. Returns ranked file importance.",safety:"safe",parameters:{focus:{type:"string",description:'Optional: focus on a subdirectory (e.g. "src/components")',required:!1},max_files:{type:"number",description:"Max files to analyze (default: 200)",required:!1}},execute:async n=>{try{let i=n.focus?ne.join(t,n.focus):t,o=n.max_files||200,a=Fn(i,o),l=[...a.nodes.values()].sort((u,d)=>d.references.length-u.references.length).slice(0,30),c=[`Project Graph \xB7 ${a.totalFiles} files \xB7 built in ${a.buildTime}ms`,"","\u2500\u2500 Entry Points \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...a.entryPoints.map(u=>` ${u}`),"","\u2500\u2500 Most Referenced Files (impact ranking) \u2500\u2500"];for(let u of l)u.references.length!==0&&(c.push(` ${u.path.padEnd(45)} \u2190 referenced by ${u.references.length} files`),u.exports.length&&c.push(` exports: ${u.exports.slice(0,6).join(", ")}`));if(a.circularDeps.length){c.push(""),c.push("\u2500\u2500 Circular Dependencies (\u26A0 fix before refactoring) \u2500\u2500");for(let u of a.circularDeps)c.push(` ${u.join(" \u2192 ")}`)}return c.push(""),c.push(`Total nodes: ${a.nodes.size} | Entry points: ${a.entryPoints.length} | Circular deps: ${a.circularDeps.length}`),{success:!0,output:c.join(`
172
+ `)}}catch(i){return{success:!1,output:"",error:`Graph build failed: ${i.message}`}}}},{name:"find_references",description:"Find all files that import or reference a specific file or symbol. Use before renaming, moving, or deleting any file.",safety:"safe",parameters:{target:{type:"string",description:"File path or symbol name to find references for",required:!0}},execute:async n=>{try{let i=n.target,o=Fn(t,300),a=[],l=o.nodes.get(i);if(l){a.push(`File: ${i}`),a.push(`Referenced by ${l.references.length} files:`);for(let c of l.references)a.push(` ${c}`);a.push(""),a.push(`This file imports ${l.imports.length} files:`);for(let c of l.imports)a.push(` ${c}`)}else{a.push(`Symbol search: "${i}"`);let c=0;for(let[u,d]of o.nodes)d.exports.some(p=>p.toLowerCase().includes(i.toLowerCase()))&&(a.push(` exported from: ${u}`),a.push(` referenced by: ${d.references.join(", ")||"none"}`),c++);c||a.push(" No matches found.")}return{success:!0,output:a.join(`
173
+ `)}}catch(i){return{success:!1,output:"",error:`Reference search failed: ${i.message}`}}}},{name:"impact_analysis",description:"Before changing a file, analyze the blast radius: which files will be affected and how critical the change is.",safety:"safe",parameters:{file:{type:"string",description:"File you intend to modify",required:!0}},execute:async n=>{try{let i=n.file,o=Fn(t,300),a=o.nodes.get(i);if(!a)return{success:!0,output:`File "${i}" not found in graph. It may be new.`};let l=new Set,c=[...a.references];for(;c.length;){let h=c.shift();if(!l.has(h)){l.add(h);let f=o.nodes.get(h);f&&c.push(...f.references)}}let u=l.size,d=u===0?"LOW":u<=3?"MEDIUM":u<=10?"HIGH":"CRITICAL",p=[`Impact Analysis: ${i}`,`Severity: ${d} (${u} files affected)`,"",`Direct referrers (${a.references.length}):`,...a.references.map(h=>` ${h}`)];if(l.size>a.references.length){p.push(""),p.push(`Transitive impact (${l.size} total):`);for(let h of[...l].slice(0,15))p.push(` ${h}`);l.size>15&&p.push(` ... and ${l.size-15} more`)}return p.push(""),p.push(`Exports: ${a.exports.join(", ")||"none"}`),p.push(`Imports: ${a.imports.length} files`),p.push(`Size: ${a.lines} lines`),{success:!0,output:p.join(`
174
+ `)}}catch(i){return{success:!1,output:"",error:`Impact analysis failed: ${i.message}`}}}}]}var rc=require("child_process"),sc=k(require("fs")),nc=k(require("path"));function ot(t,e,r=15e3){return new Promise(s=>{(0,rc.exec)(t,{cwd:e,timeout:r,maxBuffer:4*1024*1024},(n,i,o)=>{let a=n?n.code:void 0;s({out:i||"",err:o||"",code:typeof a=="number"?a:n?1:0})})})}function Vt(t){return sc.existsSync(nc.join(t,".git"))}function ic(t){return[{name:"git_status",description:"Show current git status: staged, unstaged, and untracked files. Use before committing or to understand what changed.",safety:"safe",parameters:{},execute:async()=>{if(!Vt(t))return{success:!0,output:"No git repository in this workspace."};let{out:o,err:a,code:l}=await ot("git status --short --branch",t);if(l!==0)return{success:!1,output:"",error:a||"git status failed"};let c=o.trim().split(`
175
175
  `),u=c[0]||"",d=c.slice(1).filter(Boolean);return{success:!0,output:[u,d.length?`${d.length} change(s):`:"Working tree clean",...d.map(p=>` ${p}`)].join(`
176
- `)}}},{name:"git_diff",description:"Show a diff of changes. Optionally specify a file path. Use after writing files to review exactly what changed.",safety:"safe",parameters:{file:{type:"string",description:"Optional file path to diff (default: all changes)",required:!1},staged:{type:"boolean",description:"Show staged (--cached) diff (default: false)",required:!1}},execute:async o=>{if(!Wt(t))return{success:!0,output:"No git repository."};let a=o.staged?"--cached ":"",l=o.file?` -- "${o.file}"`:"",{out:c,err:u,code:d}=await it(`git diff ${a}--stat${l}`,t);if(d!==0)return{success:!1,output:"",error:u};let{out:p}=await it(`git diff ${a}${l}`,t);return{success:!0,output:[c.trim(),"",p.slice(0,6e3)].join(`
177
- `).trim()||"No changes found."}}},{name:"git_log",description:"Show recent git commit history. Useful for understanding project evolution and finding a good rollback point.",safety:"safe",parameters:{count:{type:"number",description:"Number of commits to show (default: 10)",required:!1},file:{type:"string",description:"Show history for a specific file",required:!1}},execute:async o=>{if(!Wt(t))return{success:!0,output:"No git repository."};let a=Math.min(o.count||10,40),l=o.file?` -- "${o.file}"`:"",{out:c,err:u,code:d}=await it(`git log --oneline --decorate -${a}${l}`,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:c.trim()||"No commits yet."}}},{name:"git_commit",description:"Stage all changes and commit with a message. Only do this when the user explicitly asks to commit.",safety:"confirm",parameters:{message:{type:"string",description:"Commit message",required:!0},files:{type:"string",description:"Specific files to stage (default: all changes via git add -A)",required:!1}},execute:async o=>{if(!Wt(t))return{success:!1,output:"",error:"No git repository."};let a=o.message.trim();if(!a)return{success:!1,output:"",error:"Commit message is required."};let l=o.files?`git add ${o.files}`:"git add -A",{err:c,code:u}=await it(l,t);if(u!==0)return{success:!1,output:"",error:`Stage failed: ${c}`};let{out:d,err:p,code:h}=await it(`git commit -m "${a.replace(/"/g,'\\"')}"`,t);return h!==0?{success:!1,output:"",error:`Commit failed: ${p}`}:{success:!0,output:d.trim()}}},{name:"git_stash",description:"Stash current changes (git stash) or restore them (git stash pop). Use to safely save work before a risky change.",safety:"confirm",parameters:{action:{type:"string",description:'"stash" to save changes, "pop" to restore last stash, "list" to see stashes',required:!0}},execute:async o=>{if(!Wt(t))return{success:!1,output:"",error:"No git repository."};let a=o.action.toLowerCase(),l="";if(a==="stash")l='git stash push -u -m "hablas-auto-stash"';else if(a==="pop")l="git stash pop";else if(a==="list")l="git stash list";else return{success:!1,output:"",error:"action must be: stash | pop | list"};let{out:c,err:u,code:d}=await it(l,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:c.trim()||"Done."}}}]}var Y=k(require("fs")),he=k(require("path"));var Fn=class{entries=[];sessionDir;constructor(e){this.sessionDir=he.join(e,".hablas","rollback",`session_${Date.now()}`),Y.mkdirSync(this.sessionDir,{recursive:!0})}backup(e){let r=Y.existsSync(e);if(r){let s=he.join(this.sessionDir,Buffer.from(e).toString("base64")+".bak");Y.copyFileSync(e,s),this.entries.push({originalPath:e,backupPath:s,existed:r})}else this.entries.push({originalPath:e,backupPath:"",existed:!1})}rollback(){let e=[],r=[],s=[];for(let n of[...this.entries].reverse())try{n.existed&&n.backupPath?(Y.mkdirSync(he.dirname(n.originalPath),{recursive:!0}),Y.copyFileSync(n.backupPath,n.originalPath),e.push(n.originalPath)):!n.existed&&Y.existsSync(n.originalPath)&&(Y.unlinkSync(n.originalPath),r.push(n.originalPath))}catch(i){s.push(`${n.originalPath}: ${i.message}`)}return{restored:e,deleted:r,errors:s}}getBackedUpFiles(){return this.entries.map(e=>e.originalPath)}},Mn=new Map;function ic(t){return Mn.has(t)||Mn.set(t,new Fn(t)),Mn.get(t)}function oc(t){return[{name:"atomic_write",description:"Write multiple files in a single atomic operation with automatic rollback. If ANY file fails to write, ALL previously written files are automatically restored to their original state. Use this for multi-file changes that must succeed together (e.g. rename a type across 5 files).",safety:"confirm",parameters:{files:{type:"string",description:'JSON array of {path, content} objects. Example: [{"path":"src/a.ts","content":"..."},{"path":"src/b.ts","content":"..."}]',required:!0},description:{type:"string",description:"Short description of what this atomic operation does (for logging)",required:!1}},execute:async n=>{let i;try{if(i=JSON.parse(n.files),!Array.isArray(i)||!i.every(l=>l.path&&typeof l.content=="string"))throw new Error("Invalid format \u2014 expected array of {path, content}")}catch(l){return{success:!1,output:"",error:`Invalid files JSON: ${l.message}`}}let o=ic(t),a=[];try{for(let{path:c}of i){let u=he.resolve(t,c);o.backup(u)}for(let{path:c,content:u}of i){let d=he.resolve(t,c);Y.mkdirSync(he.dirname(d),{recursive:!0}),Y.writeFileSync(d,u,"utf-8"),a.push(c)}return{success:!0,output:[`Atomic write successful${n.description?` (${n.description})`:""}`,`Written ${a.length} files:`,...a.map(c=>` \u2713 ${c}`)].join(`
176
+ `)}}},{name:"git_diff",description:"Show a diff of changes. Optionally specify a file path. Use after writing files to review exactly what changed.",safety:"safe",parameters:{file:{type:"string",description:"Optional file path to diff (default: all changes)",required:!1},staged:{type:"boolean",description:"Show staged (--cached) diff (default: false)",required:!1}},execute:async o=>{if(!Vt(t))return{success:!0,output:"No git repository."};let a=o.staged?"--cached ":"",l=o.file?` -- "${o.file}"`:"",{out:c,err:u,code:d}=await ot(`git diff ${a}--stat${l}`,t);if(d!==0)return{success:!1,output:"",error:u};let{out:p}=await ot(`git diff ${a}${l}`,t);return{success:!0,output:[c.trim(),"",p.slice(0,6e3)].join(`
177
+ `).trim()||"No changes found."}}},{name:"git_log",description:"Show recent git commit history. Useful for understanding project evolution and finding a good rollback point.",safety:"safe",parameters:{count:{type:"number",description:"Number of commits to show (default: 10)",required:!1},file:{type:"string",description:"Show history for a specific file",required:!1}},execute:async o=>{if(!Vt(t))return{success:!0,output:"No git repository."};let a=Math.min(o.count||10,40),l=o.file?` -- "${o.file}"`:"",{out:c,err:u,code:d}=await ot(`git log --oneline --decorate -${a}${l}`,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:c.trim()||"No commits yet."}}},{name:"git_commit",description:"Stage all changes and commit with a message. Only do this when the user explicitly asks to commit.",safety:"confirm",parameters:{message:{type:"string",description:"Commit message",required:!0},files:{type:"string",description:"Specific files to stage (default: all changes via git add -A)",required:!1}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.message.trim();if(!a)return{success:!1,output:"",error:"Commit message is required."};let l=o.files?`git add ${o.files}`:"git add -A",{err:c,code:u}=await ot(l,t);if(u!==0)return{success:!1,output:"",error:`Stage failed: ${c}`};let{out:d,err:p,code:h}=await ot(`git commit -m "${a.replace(/"/g,'\\"')}"`,t);return h!==0?{success:!1,output:"",error:`Commit failed: ${p}`}:{success:!0,output:d.trim()}}},{name:"git_stash",description:"Stash current changes (git stash) or restore them (git stash pop). Use to safely save work before a risky change.",safety:"confirm",parameters:{action:{type:"string",description:'"stash" to save changes, "pop" to restore last stash, "list" to see stashes',required:!0}},execute:async o=>{if(!Vt(t))return{success:!1,output:"",error:"No git repository."};let a=o.action.toLowerCase(),l="";if(a==="stash")l='git stash push -u -m "hablas-auto-stash"';else if(a==="pop")l="git stash pop";else if(a==="list")l="git stash list";else return{success:!1,output:"",error:"action must be: stash | pop | list"};let{out:c,err:u,code:d}=await ot(l,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:c.trim()||"Done."}}}]}var X=k(require("fs")),he=k(require("path"));var Dn=class{entries=[];sessionDir;constructor(e){this.sessionDir=he.join(e,".hablas","rollback",`session_${Date.now()}`),X.mkdirSync(this.sessionDir,{recursive:!0})}backup(e){let r=X.existsSync(e);if(r){let s=he.join(this.sessionDir,Buffer.from(e).toString("base64")+".bak");X.copyFileSync(e,s),this.entries.push({originalPath:e,backupPath:s,existed:r})}else this.entries.push({originalPath:e,backupPath:"",existed:!1})}rollback(){let e=[],r=[],s=[];for(let n of[...this.entries].reverse())try{n.existed&&n.backupPath?(X.mkdirSync(he.dirname(n.originalPath),{recursive:!0}),X.copyFileSync(n.backupPath,n.originalPath),e.push(n.originalPath)):!n.existed&&X.existsSync(n.originalPath)&&(X.unlinkSync(n.originalPath),r.push(n.originalPath))}catch(i){s.push(`${n.originalPath}: ${i.message}`)}return{restored:e,deleted:r,errors:s}}getBackedUpFiles(){return this.entries.map(e=>e.originalPath)}},Ln=new Map;function oc(t){return Ln.has(t)||Ln.set(t,new Dn(t)),Ln.get(t)}function ac(t){return[{name:"atomic_write",description:"Write multiple files in a single atomic operation with automatic rollback. If ANY file fails to write, ALL previously written files are automatically restored to their original state. Use this for multi-file changes that must succeed together (e.g. rename a type across 5 files).",safety:"confirm",parameters:{files:{type:"string",description:'JSON array of {path, content} objects. Example: [{"path":"src/a.ts","content":"..."},{"path":"src/b.ts","content":"..."}]',required:!0},description:{type:"string",description:"Short description of what this atomic operation does (for logging)",required:!1}},execute:async n=>{let i;try{if(i=JSON.parse(n.files),!Array.isArray(i)||!i.every(l=>l.path&&typeof l.content=="string"))throw new Error("Invalid format \u2014 expected array of {path, content}")}catch(l){return{success:!1,output:"",error:`Invalid files JSON: ${l.message}`}}let o=oc(t),a=[];try{for(let{path:c}of i){let u=he.resolve(t,c);o.backup(u)}for(let{path:c,content:u}of i){let d=he.resolve(t,c);X.mkdirSync(he.dirname(d),{recursive:!0}),X.writeFileSync(d,u,"utf-8"),a.push(c)}return{success:!0,output:[`Atomic write successful${n.description?` (${n.description})`:""}`,`Written ${a.length} files:`,...a.map(c=>` \u2713 ${c}`)].join(`
178
178
  `)}}catch(l){let c=o.rollback();return{success:!1,output:"",error:[`Atomic write FAILED at: ${l.message}`,`Rolled back ${c.restored.length} files.`,a.length>0?`Was writing: ${a.join(", ")}`:"",c.errors.length?`Rollback errors: ${c.errors.join("; ")}`:""].filter(Boolean).join(`
179
- `)}}}},{name:"diff_preview",description:"Preview what a file would look like AFTER a change, shown as a unified diff. Use before writing to verify the change is correct. Does NOT write anything.",safety:"safe",parameters:{path:{type:"string",description:"File path to preview the change for",required:!0},new_content:{type:"string",description:"The proposed new content of the file",required:!0}},execute:async n=>{let i=n.path,o=n.new_content,a=he.resolve(t,i),l="";if(Y.existsSync(a))try{l=Y.readFileSync(a,"utf-8")}catch{}else return{success:!0,output:`[New file: ${i}]
179
+ `)}}}},{name:"diff_preview",description:"Preview what a file would look like AFTER a change, shown as a unified diff. Use before writing to verify the change is correct. Does NOT write anything.",safety:"safe",parameters:{path:{type:"string",description:"File path to preview the change for",required:!0},new_content:{type:"string",description:"The proposed new content of the file",required:!0}},execute:async n=>{let i=n.path,o=n.new_content,a=he.resolve(t,i),l="";if(X.existsSync(a))try{l=X.readFileSync(a,"utf-8")}catch{}else return{success:!0,output:`[New file: ${i}]
180
180
  +++ ${o.split(`
181
181
  `).slice(0,40).map(f=>"+ "+f).join(`
182
- `)}`};if(l===o)return{success:!0,output:`No changes \u2014 content is identical to ${i}`};let c=qt(i,l,o),u=l.split(`
182
+ `)}`};if(l===o)return{success:!0,output:`No changes \u2014 content is identical to ${i}`};let c=Bt(i,l,o),u=l.split(`
183
183
  `).length,d=o.split(`
184
184
  `).length,p=d-u,h=p>=0?`+${p}`:`${p}`;return{success:!0,output:[`Diff preview: ${i} (${u} \u2192 ${d} lines, ${h})`,"",c.slice(0,5e3),c.length>5e3?"... [diff truncated]":""].filter(Boolean).join(`
185
- `)}}},{name:"rollback_session",description:"EMERGENCY ROLLBACK: Restore all files modified in this session to their state before any changes were made. Use when something went wrong and you need to undo everything.",safety:"dangerous",parameters:{confirm:{type:"string",description:'Type "ROLLBACK" to confirm you want to restore all files',required:!0}},execute:async n=>{if(n.confirm!=="ROLLBACK")return{success:!1,output:"",error:'Rollback cancelled. Type "ROLLBACK" as the confirm value to proceed.'};let o=ic(t).rollback();return{success:!0,output:["Session rollback complete.",`Restored: ${o.restored.length} files`,`Deleted: ${o.deleted.length} new files`,o.errors.length?`Errors: ${o.errors.join("; ")}`:"","",o.restored.map(a=>` \u21A9 ${he.relative(t,a)}`).join(`
185
+ `)}}},{name:"rollback_session",description:"EMERGENCY ROLLBACK: Restore all files modified in this session to their state before any changes were made. Use when something went wrong and you need to undo everything.",safety:"dangerous",parameters:{confirm:{type:"string",description:'Type "ROLLBACK" to confirm you want to restore all files',required:!0}},execute:async n=>{if(n.confirm!=="ROLLBACK")return{success:!1,output:"",error:'Rollback cancelled. Type "ROLLBACK" as the confirm value to proceed.'};let o=oc(t).rollback();return{success:!0,output:["Session rollback complete.",`Restored: ${o.restored.length} files`,`Deleted: ${o.deleted.length} new files`,o.errors.length?`Errors: ${o.errors.join("; ")}`:"","",o.restored.map(a=>` \u21A9 ${he.relative(t,a)}`).join(`
186
186
  `)].filter(Boolean).join(`
187
- `)}}}]}var L=k(require("fs")),V=k(require("path")),lc=require("child_process"),_g=new Set(["node_modules",".git","dist","build",".next",".hablas","__pycache__",".cache","coverage"]),kg=500*1024,Tg=20*1024*1024;function Ln(t){let e=V.join(t,".hablas","checkpoints");return L.existsSync(e)||L.mkdirSync(e,{recursive:!0}),e}function cc(t){return V.join(t,".hablas","checkpoints","_index.json")}function ac(t){let e=cc(t);if(L.existsSync(e))try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{}return{version:1,checkpoints:[]}}function Cg(t,e){L.writeFileSync(cc(t),JSON.stringify(e,null,2),"utf-8")}function Nn(t,e){let r=[];try{let s=L.readdirSync(t,{withFileTypes:!0});for(let n of s){if(_g.has(n.name)||n.name.startsWith("."))continue;let i=V.join(t,n.name);if(n.isDirectory())r.push(...Nn(i,e));else try{L.statSync(i).size<=kg&&r.push(V.relative(e,i))}catch{}}}catch{}return r}function $g(t){return new Promise(e=>{(0,lc.exec)("git rev-parse --short HEAD",{cwd:t},(r,s)=>{e(r?void 0:s.trim())})})}function Dn(t){return t.toLowerCase().replace(/[^a-z0-9_-]/g,"-").replace(/-+/g,"-").slice(0,40)}function uc(t){return[{name:"checkpoint_save",description:'Save a named checkpoint of the current workspace state. Useful before risky refactors: "save checkpoint before-auth-refactor". Can be restored later with checkpoint_restore.',safety:"safe",parameters:{name:{type:"string",description:'Short name for this checkpoint (e.g. "before-refactor", "v1-stable")',required:!0},description:{type:"string",description:"What state is being saved and why",required:!1}},execute:async i=>{let o=i.name.trim(),a=Dn(o),l=i.description||"",c=Ln(t),u=V.join(c,a);L.existsSync(u)&&L.rmSync(u,{recursive:!0}),L.mkdirSync(u,{recursive:!0});let d=Nn(t,t),p=await $g(t),h=0,f=[];for(let y of d){if(h>=Tg)break;try{let b=V.join(t,y),w=V.join(u,y);L.mkdirSync(V.dirname(w),{recursive:!0});let S=L.readFileSync(b);L.writeFileSync(w,S),h+=S.length,f.push(y)}catch{}}let m={name:a,createdAt:new Date().toISOString(),description:l,files:f,gitSha:p,totalBytes:h};L.writeFileSync(V.join(u,"_meta.json"),JSON.stringify(m,null,2));let g=ac(t);return g.checkpoints=g.checkpoints.filter(y=>y.name!==a),g.checkpoints.unshift(m),g.checkpoints.length>20&&(g.checkpoints=g.checkpoints.slice(0,20)),Cg(t,g),{success:!0,output:[`Checkpoint saved: "${a}"`,`Files: ${f.length} \xB7 Size: ${(h/1024).toFixed(0)} KB`,p?`Git: ${p}`:"",l?`Note: ${l}`:""].filter(Boolean).join(`
188
- `)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let i=ac(t);if(!i.checkpoints.length)return{success:!0,output:"No checkpoints saved yet. Use checkpoint_save to create one."};let o=["Saved Checkpoints:",""];for(let a of i.checkpoints){let l=new Date(a.createdAt).toLocaleString();o.push(` "${a.name}" \u2014 ${l}`),o.push(` ${a.files.length} files \xB7 ${(a.totalBytes/1024).toFixed(0)} KB`),a.description&&o.push(` ${a.description}`),a.gitSha&&o.push(` git: ${a.gitSha}`),o.push("")}return{success:!0,output:o.join(`
189
- `)}}},{name:"checkpoint_restore",description:"Restore a named checkpoint, overwriting current files with the saved state. This is DESTRUCTIVE \u2014 current unsaved changes will be lost. Use checkpoint_list to see available names.",safety:"dangerous",parameters:{name:{type:"string",description:"Checkpoint name to restore",required:!0},confirm:{type:"string",description:'Type "RESTORE" to confirm destructive operation',required:!0}},execute:async i=>{if(i.confirm!=="RESTORE")return{success:!1,output:"",error:'Restore cancelled. Set confirm="RESTORE" to proceed.'};let o=Dn(i.name.trim()),a=Ln(t),l=V.join(a,o);if(!L.existsSync(l))return{success:!1,output:"",error:`Checkpoint "${o}" not found. Run checkpoint_list to see available names.`};let c=V.join(l,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(c,"utf-8"))}catch{return{success:!1,output:"",error:"Checkpoint metadata is corrupt."}}let d=[],p=[];for(let h of u.files)try{let f=V.join(l,h),m=V.join(t,h);if(!L.existsSync(f))continue;L.mkdirSync(V.dirname(m),{recursive:!0}),L.copyFileSync(f,m),d.push(h)}catch(f){p.push(`${h}: ${f.message}`)}return{success:!0,output:[`Checkpoint "${o}" restored.`,`Restored: ${d.length} files`,u.gitSha?`Saved at git: ${u.gitSha}`:"",u.description?`Original note: ${u.description}`:"",p.length?`Errors (${p.length}): ${p.slice(0,3).join("; ")}`:""].filter(Boolean).join(`
190
- `)}}},{name:"checkpoint_diff",description:"Show which files changed since a checkpoint was saved (without restoring).",safety:"safe",parameters:{name:{type:"string",description:"Checkpoint name to compare against",required:!0}},execute:async i=>{let o=Dn(i.name.trim()),a=Ln(t),l=V.join(a,o);if(!L.existsSync(l))return{success:!1,output:"",error:`Checkpoint "${o}" not found.`};let c=V.join(l,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(c,"utf-8"))}catch{return{success:!1,output:"",error:"Corrupt checkpoint metadata."}}let d=[],p=[],h=[];for(let y of u.files){let b=V.join(l,y),w=V.join(t,y);if(!L.existsSync(w)){p.push(y);continue}try{let S=L.readFileSync(b),_=L.readFileSync(w);S.equals(_)||d.push(y)}catch{}}let f=Nn(t,t),m=new Set(u.files);for(let y of f)m.has(y)||h.push(y);if(!d.length&&!p.length&&!h.length)return{success:!0,output:`No changes since checkpoint "${o}".`};let g=[`Changes since checkpoint "${o}" (${new Date(u.createdAt).toLocaleString()}):`,""];return d.length&&(g.push(` Modified (${d.length}):`),d.forEach(y=>g.push(` M ${y}`))),h.length&&(g.push(` Added (${h.length}):`),h.slice(0,20).forEach(y=>g.push(` + ${y}`))),p.length&&(g.push(` Deleted (${p.length}):`),p.forEach(y=>g.push(` - ${y}`))),{success:!0,output:g.join(`
191
- `)}}}]}var dc=require("child_process"),Ce=k(require("fs")),te=k(require("path")),Vt=[{name:"vitest",command:"npx vitest run",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"jest",command:"npx jest --no-coverage",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"mocha",command:"npx mocha",coverageFlag:"--reporter=json",filePattern:/\.(test|spec)\.(ts|js)$/},{name:"pytest",command:"python -m pytest -v",coverageFlag:"--cov=.",filePattern:/test_.*\.py$|.*_test\.py$/},{name:"go test",command:"go test ./...",coverageFlag:"-cover",filePattern:/.*_test\.go$/}];function Un(t){try{let e=JSON.parse(Ce.readFileSync(te.join(t,"package.json"),"utf-8")),r={...e.dependencies,...e.devDependencies};if(r.vitest)return Vt[0];if(r.jest||e.scripts?.test?.includes("jest"))return Vt[1];if(r.mocha)return Vt[2]}catch{}return Ce.existsSync(te.join(t,"pytest.ini"))||Ce.existsSync(te.join(t,"pyproject.toml"))?Vt[3]:Ce.existsSync(te.join(t,"go.mod"))?Vt[4]:null}function Eg(t,e){let r={passed:0,failed:0,skipped:0,total:0,failures:[],duration:0,raw:t};if(e==="vitest"||e==="jest"){let s=t.match(/Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+passed,\s+)?(\d+)\s+total/);s&&(r.failed=parseInt(s[1]||"0"),r.passed=parseInt(s[2]||"0"),r.total=parseInt(s[3]||"0"),r.skipped=r.total-r.passed-r.failed);let n=t.match(/Duration\s+([\d.]+)s/);n&&(r.duration=parseFloat(n[1])*1e3);let i=/● (.+?)\n\n([\s\S]*?)(?=●|\n\nTest Suites:|$)/g,o;for(;(o=i.exec(t))!==null;)r.failures.push({test:o[1].trim(),message:o[2].trim().slice(0,300)})}else if(e==="pytest"){let s=t.match(/(\d+)\s+passed(?:,\s+(\d+)\s+failed)?/);s&&(r.passed=parseInt(s[1]||"0"),r.failed=parseInt(s[2]||"0"),r.total=r.passed+r.failed);let n=t.match(/in\s+([\d.]+)s/);n&&(r.duration=parseFloat(n[1])*1e3)}return r.total===0&&r.passed===0&&(r.passed=(t.match(/✓|PASS|passed/gi)||[]).length,r.failed=(t.match(/✗|FAIL|failed/gi)||[]).length,r.total=r.passed+r.failed),r}function Ag(t,e){let s=[`${t.failed===0?"\u2713 ALL PASSING":`\u2717 ${t.failed} FAILING`} \u2014 ${e}`,` Passed: ${t.passed} Failed: ${t.failed} Skipped: ${t.skipped} Total: ${t.total}`,t.duration?` Duration: ${(t.duration/1e3).toFixed(2)}s`:""].filter(Boolean);if(t.failures.length){s.push(""),s.push("Failed tests:");for(let n of t.failures.slice(0,5))s.push(` \u2717 ${n.test}`),n.message&&s.push(` ${n.message.split(`
187
+ `)}}}]}var L=k(require("fs")),V=k(require("path")),cc=require("child_process"),Tg=new Set(["node_modules",".git","dist","build",".next",".hablas","__pycache__",".cache","coverage"]),Cg=500*1024,$g=20*1024*1024;function Nn(t){let e=V.join(t,".hablas","checkpoints");return L.existsSync(e)||L.mkdirSync(e,{recursive:!0}),e}function uc(t){return V.join(t,".hablas","checkpoints","_index.json")}function lc(t){let e=uc(t);if(L.existsSync(e))try{return JSON.parse(L.readFileSync(e,"utf-8"))}catch{}return{version:1,checkpoints:[]}}function Ag(t,e){L.writeFileSync(uc(t),JSON.stringify(e,null,2),"utf-8")}function qn(t,e){let r=[];try{let s=L.readdirSync(t,{withFileTypes:!0});for(let n of s){if(Tg.has(n.name)||n.name.startsWith("."))continue;let i=V.join(t,n.name);if(n.isDirectory())r.push(...qn(i,e));else try{L.statSync(i).size<=Cg&&r.push(V.relative(e,i))}catch{}}}catch{}return r}function Eg(t){return new Promise(e=>{(0,cc.exec)("git rev-parse --short HEAD",{cwd:t},(r,s)=>{e(r?void 0:s.trim())})})}function Un(t){return t.toLowerCase().replace(/[^a-z0-9_-]/g,"-").replace(/-+/g,"-").slice(0,40)}function fc(t){return[{name:"checkpoint_save",description:'Save a named checkpoint of the current workspace state. Useful before risky refactors: "save checkpoint before-auth-refactor". Can be restored later with checkpoint_restore.',safety:"safe",parameters:{name:{type:"string",description:'Short name for this checkpoint (e.g. "before-refactor", "v1-stable")',required:!0},description:{type:"string",description:"What state is being saved and why",required:!1}},execute:async i=>{let o=i.name.trim(),a=Un(o),l=i.description||"",c=Nn(t),u=V.join(c,a);L.existsSync(u)&&L.rmSync(u,{recursive:!0}),L.mkdirSync(u,{recursive:!0});let d=qn(t,t),p=await Eg(t),h=0,f=[];for(let y of d){if(h>=$g)break;try{let b=V.join(t,y),w=V.join(u,y);L.mkdirSync(V.dirname(w),{recursive:!0});let S=L.readFileSync(b);L.writeFileSync(w,S),h+=S.length,f.push(y)}catch{}}let m={name:a,createdAt:new Date().toISOString(),description:l,files:f,gitSha:p,totalBytes:h};L.writeFileSync(V.join(u,"_meta.json"),JSON.stringify(m,null,2));let g=lc(t);return g.checkpoints=g.checkpoints.filter(y=>y.name!==a),g.checkpoints.unshift(m),g.checkpoints.length>20&&(g.checkpoints=g.checkpoints.slice(0,20)),Ag(t,g),{success:!0,output:[`Checkpoint saved: "${a}"`,`Files: ${f.length} \xB7 Size: ${(h/1024).toFixed(0)} KB`,p?`Git: ${p}`:"",l?`Note: ${l}`:""].filter(Boolean).join(`
188
+ `)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let i=lc(t);if(!i.checkpoints.length)return{success:!0,output:"No checkpoints saved yet. Use checkpoint_save to create one."};let o=["Saved Checkpoints:",""];for(let a of i.checkpoints){let l=new Date(a.createdAt).toLocaleString();o.push(` "${a.name}" \u2014 ${l}`),o.push(` ${a.files.length} files \xB7 ${(a.totalBytes/1024).toFixed(0)} KB`),a.description&&o.push(` ${a.description}`),a.gitSha&&o.push(` git: ${a.gitSha}`),o.push("")}return{success:!0,output:o.join(`
189
+ `)}}},{name:"checkpoint_restore",description:"Restore a named checkpoint, overwriting current files with the saved state. This is DESTRUCTIVE \u2014 current unsaved changes will be lost. Use checkpoint_list to see available names.",safety:"dangerous",parameters:{name:{type:"string",description:"Checkpoint name to restore",required:!0},confirm:{type:"string",description:'Type "RESTORE" to confirm destructive operation',required:!0}},execute:async i=>{if(i.confirm!=="RESTORE")return{success:!1,output:"",error:'Restore cancelled. Set confirm="RESTORE" to proceed.'};let o=Un(i.name.trim()),a=Nn(t),l=V.join(a,o);if(!L.existsSync(l))return{success:!1,output:"",error:`Checkpoint "${o}" not found. Run checkpoint_list to see available names.`};let c=V.join(l,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(c,"utf-8"))}catch{return{success:!1,output:"",error:"Checkpoint metadata is corrupt."}}let d=[],p=[];for(let h of u.files)try{let f=V.join(l,h),m=V.join(t,h);if(!L.existsSync(f))continue;L.mkdirSync(V.dirname(m),{recursive:!0}),L.copyFileSync(f,m),d.push(h)}catch(f){p.push(`${h}: ${f.message}`)}return{success:!0,output:[`Checkpoint "${o}" restored.`,`Restored: ${d.length} files`,u.gitSha?`Saved at git: ${u.gitSha}`:"",u.description?`Original note: ${u.description}`:"",p.length?`Errors (${p.length}): ${p.slice(0,3).join("; ")}`:""].filter(Boolean).join(`
190
+ `)}}},{name:"checkpoint_diff",description:"Show which files changed since a checkpoint was saved (without restoring).",safety:"safe",parameters:{name:{type:"string",description:"Checkpoint name to compare against",required:!0}},execute:async i=>{let o=Un(i.name.trim()),a=Nn(t),l=V.join(a,o);if(!L.existsSync(l))return{success:!1,output:"",error:`Checkpoint "${o}" not found.`};let c=V.join(l,"_meta.json"),u;try{u=JSON.parse(L.readFileSync(c,"utf-8"))}catch{return{success:!1,output:"",error:"Corrupt checkpoint metadata."}}let d=[],p=[],h=[];for(let y of u.files){let b=V.join(l,y),w=V.join(t,y);if(!L.existsSync(w)){p.push(y);continue}try{let S=L.readFileSync(b),_=L.readFileSync(w);S.equals(_)||d.push(y)}catch{}}let f=qn(t,t),m=new Set(u.files);for(let y of f)m.has(y)||h.push(y);if(!d.length&&!p.length&&!h.length)return{success:!0,output:`No changes since checkpoint "${o}".`};let g=[`Changes since checkpoint "${o}" (${new Date(u.createdAt).toLocaleString()}):`,""];return d.length&&(g.push(` Modified (${d.length}):`),d.forEach(y=>g.push(` M ${y}`))),h.length&&(g.push(` Added (${h.length}):`),h.slice(0,20).forEach(y=>g.push(` + ${y}`))),p.length&&(g.push(` Deleted (${p.length}):`),p.forEach(y=>g.push(` - ${y}`))),{success:!0,output:g.join(`
191
+ `)}}}]}var pc=require("child_process"),$e=k(require("fs")),re=k(require("path")),zt=[{name:"vitest",command:"npx vitest run",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"jest",command:"npx jest --no-coverage",coverageFlag:"--coverage",filePattern:/\.(test|spec)\.(ts|tsx|js|jsx)$/},{name:"mocha",command:"npx mocha",coverageFlag:"--reporter=json",filePattern:/\.(test|spec)\.(ts|js)$/},{name:"pytest",command:"python -m pytest -v",coverageFlag:"--cov=.",filePattern:/test_.*\.py$|.*_test\.py$/},{name:"go test",command:"go test ./...",coverageFlag:"-cover",filePattern:/.*_test\.go$/}];function Bn(t){try{let e=JSON.parse($e.readFileSync(re.join(t,"package.json"),"utf-8")),r={...e.dependencies,...e.devDependencies};if(r.vitest)return zt[0];if(r.jest||e.scripts?.test?.includes("jest"))return zt[1];if(r.mocha)return zt[2]}catch{}return $e.existsSync(re.join(t,"pytest.ini"))||$e.existsSync(re.join(t,"pyproject.toml"))?zt[3]:$e.existsSync(re.join(t,"go.mod"))?zt[4]:null}function Og(t,e){let r={passed:0,failed:0,skipped:0,total:0,failures:[],duration:0,raw:t};if(e==="vitest"||e==="jest"){let s=t.match(/Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+passed,\s+)?(\d+)\s+total/);s&&(r.failed=parseInt(s[1]||"0"),r.passed=parseInt(s[2]||"0"),r.total=parseInt(s[3]||"0"),r.skipped=r.total-r.passed-r.failed);let n=t.match(/Duration\s+([\d.]+)s/);n&&(r.duration=parseFloat(n[1])*1e3);let i=/● (.+?)\n\n([\s\S]*?)(?=●|\n\nTest Suites:|$)/g,o;for(;(o=i.exec(t))!==null;)r.failures.push({test:o[1].trim(),message:o[2].trim().slice(0,300)})}else if(e==="pytest"){let s=t.match(/(\d+)\s+passed(?:,\s+(\d+)\s+failed)?/);s&&(r.passed=parseInt(s[1]||"0"),r.failed=parseInt(s[2]||"0"),r.total=r.passed+r.failed);let n=t.match(/in\s+([\d.]+)s/);n&&(r.duration=parseFloat(n[1])*1e3)}return r.total===0&&r.passed===0&&(r.passed=(t.match(/✓|PASS|passed/gi)||[]).length,r.failed=(t.match(/✗|FAIL|failed/gi)||[]).length,r.total=r.passed+r.failed),r}function Rg(t,e){let s=[`${t.failed===0?"\u2713 ALL PASSING":`\u2717 ${t.failed} FAILING`} \u2014 ${e}`,` Passed: ${t.passed} Failed: ${t.failed} Skipped: ${t.skipped} Total: ${t.total}`,t.duration?` Duration: ${(t.duration/1e3).toFixed(2)}s`:""].filter(Boolean);if(t.failures.length){s.push(""),s.push("Failed tests:");for(let n of t.failures.slice(0,5))s.push(` \u2717 ${n.test}`),n.message&&s.push(` ${n.message.split(`
192
192
  `)[0]}`)}return t.total===0&&(s.push(""),s.push("Raw output (could not parse structured results):"),s.push(t.raw.slice(0,800))),s.join(`
193
- `)}function fc(t,e,r=6e4){return new Promise(s=>{(0,dc.exec)(t,{cwd:e,timeout:r,maxBuffer:8*1024*1024},(n,i,o)=>{let a=n?n.code:void 0;s({out:i||"",err:o||"",code:typeof a=="number"?a:n?1:0})})})}function pc(t){return[{name:"run_tests",description:"Run the project test suite. Auto-detects Jest, Vitest, Pytest, or Go test. Parses results and shows pass/fail counts and failure details.",safety:"safe",parameters:{filter:{type:"string",description:"Run only tests matching this pattern/file (optional)",required:!1},timeout:{type:"number",description:"Timeout in seconds (default: 60)",required:!1}},execute:async n=>{let i=Un(t);if(!i)return{success:!0,output:"No test runner detected. Install Jest, Vitest, Pytest, or use Go modules."};let o=n.filter?` ${n.filter}`:"",a=(n.timeout||60)*1e3,l=`${i.command}${o}`,{out:c,err:u}=await fc(l,t,a),d=(c+`
194
- `+u).trim(),p=Eg(d,i.name),h=Ag(p,i.name);return{success:p.failed===0,output:h,error:p.failed>0?`${p.failed} test(s) failing`:void 0}}},{name:"test_coverage",description:"Run tests with coverage report. Shows which files/lines are covered. Uses the project's configured test runner.",safety:"safe",parameters:{},execute:async()=>{let n=Un(t);if(!n)return{success:!0,output:"No test runner detected."};let i=`${n.command} ${n.coverageFlag}`,{out:o,err:a}=await fc(i,t,12e4),l=(o+`
193
+ `)}function dc(t,e,r=6e4){return new Promise(s=>{(0,pc.exec)(t,{cwd:e,timeout:r,maxBuffer:8*1024*1024},(n,i,o)=>{let a=n?n.code:void 0;s({out:i||"",err:o||"",code:typeof a=="number"?a:n?1:0})})})}function hc(t){return[{name:"run_tests",description:"Run the project test suite. Auto-detects Jest, Vitest, Pytest, or Go test. Parses results and shows pass/fail counts and failure details.",safety:"safe",parameters:{filter:{type:"string",description:"Run only tests matching this pattern/file (optional)",required:!1},timeout:{type:"number",description:"Timeout in seconds (default: 60)",required:!1}},execute:async n=>{let i=Bn(t);if(!i)return{success:!0,output:"No test runner detected. Install Jest, Vitest, Pytest, or use Go modules."};let o=n.filter?` ${n.filter}`:"",a=(n.timeout||60)*1e3,l=`${i.command}${o}`,{out:c,err:u}=await dc(l,t,a),d=(c+`
194
+ `+u).trim(),p=Og(d,i.name),h=Rg(p,i.name);return{success:p.failed===0,output:h,error:p.failed>0?`${p.failed} test(s) failing`:void 0}}},{name:"test_coverage",description:"Run tests with coverage report. Shows which files/lines are covered. Uses the project's configured test runner.",safety:"safe",parameters:{},execute:async()=>{let n=Bn(t);if(!n)return{success:!0,output:"No test runner detected."};let i=`${n.command} ${n.coverageFlag}`,{out:o,err:a}=await dc(i,t,12e4),l=(o+`
195
195
  `+a).trim(),c=/(?:All files|TOTAL|coverage)\s*\|\s*([\d.]+)/i,u=l.match(c),d=u?`Overall coverage: ${u[1]}%`:"Coverage data generated.",p=l.indexOf("-------"),h=p>=0?l.slice(p,p+2e3):"";return{success:!0,output:[d,h||l.slice(-1500)].filter(Boolean).join(`
196
196
 
197
- `)}}},{name:"tdd_scaffold",description:"Generate a test file scaffold for a function/module BEFORE implementing it. Used to enforce TDD workflow: write the test first, then implement.",safety:"safe",parameters:{target_file:{type:"string",description:'The file you plan to implement (e.g. "src/utils/auth.ts")',required:!0},functions:{type:"string",description:"Comma-separated list of function/class names to generate tests for",required:!0},test_framework:{type:"string",description:'Override framework: "jest" | "vitest" | "pytest" (auto-detected if omitted)',required:!1}},execute:async n=>{let i=n.target_file,o=n.functions.split(",").map(m=>m.trim()).filter(Boolean),a=te.extname(i),l=te.basename(i,a),c=te.dirname(i),u=Un(t),d=n.test_framework||u?.name||"jest",p="",h="";if(d==="pytest")h=te.join(c,`test_${l}.py`),p=[`"""Tests for ${i} \u2014 TDD scaffold (generated by Hablas)"""
197
+ `)}}},{name:"tdd_scaffold",description:"Generate a test file scaffold for a function/module BEFORE implementing it. Used to enforce TDD workflow: write the test first, then implement.",safety:"safe",parameters:{target_file:{type:"string",description:'The file you plan to implement (e.g. "src/utils/auth.ts")',required:!0},functions:{type:"string",description:"Comma-separated list of function/class names to generate tests for",required:!0},test_framework:{type:"string",description:'Override framework: "jest" | "vitest" | "pytest" (auto-detected if omitted)',required:!1}},execute:async n=>{let i=n.target_file,o=n.functions.split(",").map(m=>m.trim()).filter(Boolean),a=re.extname(i),l=re.basename(i,a),c=re.dirname(i),u=Bn(t),d=n.test_framework||u?.name||"jest",p="",h="";if(d==="pytest")h=re.join(c,`test_${l}.py`),p=[`"""Tests for ${i} \u2014 TDD scaffold (generated by Hablas)"""
198
198
  `,"import pytest",`from ${c.replace(/\//g,".")}.${l} import ${o.join(", ")}
199
199
  `,...o.map(m=>[`class Test${m.charAt(0).toUpperCase()+m.slice(1)}:`,` """Tests for ${m}"""
200
200
  `,` def test_${m}_returns_expected(self):`," # Arrange"," # Act",` result = ${m}()`," # Assert",' assert result is not None, "Expected a result"',"",` def test_${m}_handles_invalid_input(self):`," # Arrange / Act / Assert"," with pytest.raises((ValueError, TypeError)):",` ${m}(None) # type: ignore`,""].join(`
@@ -202,45 +202,45 @@ Notes:
202
202
  `);else{let m=d==="vitest";h=i.replace(a,`.test${a}`);let g=`./${l}`;p=[m?"import { describe, it, expect, beforeEach } from 'vitest';":"// @ts-nocheck",`import { ${o.join(", ")} } from '${g}';
203
203
  `,...o.map(y=>[`describe('${y}', () => {`," // RED: These tests should FAIL until implementation is written",""," it('should return a valid result', () => {"," // Arrange"," // Act",` const result = ${y}();`," // Assert"," expect(result).toBeDefined();"," });",""," it('should handle edge cases gracefully', () => {",` // TODO: define edge cases for ${y}`,` expect(() => ${y}(null as any)).not.toThrow();`," });",""," it('should match the expected contract', () => {",` // TODO: define the exact contract/interface for ${y}`,` // Example: expect(${y}(input)).toEqual(expectedOutput);`," expect(true).toBe(false); // Replace with real assertion"," });","});",""].join(`
204
204
  `))].join(`
205
- `)}let f=te.resolve(t,h);return Ce.mkdirSync(te.dirname(f),{recursive:!0}),Ce.writeFileSync(f,p,"utf-8"),{success:!0,output:[`TDD scaffold created: ${h}`,`Functions scaffolded: ${o.join(", ")}`,`Framework: ${d}`,"","Next steps (TDD red-green-refactor):"," 1. Run tests \u2192 confirm they FAIL (red)"," 2. Write minimal implementation in: "+i," 3. Run tests again \u2192 confirm they PASS (green)"," 4. Refactor if needed, run once more"].join(`
206
- `)}}}]}var St=k(require("fs")),me=k(require("path")),Og=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage"]),Rg=new Set([".ts",".tsx",".js",".jsx",".mjs",".py",".go",".rs",".java",".md",".json",".yaml",".yml",".toml"]),Ig=500,jg=8e3;function hc(t){return t.toLowerCase().replace(/[^a-z0-9\u0600-\u06FF]/g," ").split(/\s+/).filter(e=>e.length>2)}function mc(t,e){let r=0;for(let s of t)e.has(s)&&r++;return t.size>0?r/t.size:0}function Pg(t,e){let r=new Set(t.toLowerCase().replace(/[/_-]/g," ").split(/\s+/).filter(s=>s.length>1));return mc(e,r)}function Mg(t,e){let s=(e-t)/(1e3*60*60*24);return s<1?1:s<7?.5:s<30?.2:.05}function Fg(t,e){if(e.size===0)return 0;let r=new Set(hc(t.slice(0,jg)));return mc(e,r)}function Lg(t){return/\b(index|main|app|server|cli|entry)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/.test(t)}function gc(t,e,r=[]){if(r.length>=Ig)return r;try{let s=St.readdirSync(t,{withFileTypes:!0});for(let n of s){if(Og.has(n.name)||n.name.startsWith("."))continue;let i=me.join(t,n.name);if(n.isDirectory())gc(i,e,r);else if(Rg.has(me.extname(n.name)))try{let o=St.statSync(i);if(o.size>200*1024)continue;let a=me.relative(e,i);r.push({path:a,mtime:o.mtimeMs,size:o.size,lines:0,isEntry:Lg(a)})}catch{}}}catch{}return r}function Dg(t){let e=Date.now(),{query:r,workingDir:s,topK:n=12,recentlyTouched:i=[],importantFiles:o=[],skipContentScan:a=!1}=t,l=new Set(hc(r)),c=new Set(i.map(f=>me.normalize(f))),u=new Set(o.map(f=>me.normalize(f))),d=Date.now(),p=gc(s,s),h=[];for(let f of p){let m=[],g=0,y=Pg(f.path,l)*.35;y>.1&&(g+=y,m.push(`name-match(${(y*100).toFixed(0)}%)`));let b=Mg(f.mtime,d)*.2;if(b>.05&&(g+=b,m.push(`fresh(${(b*100).toFixed(0)}%)`)),c.has(me.normalize(f.path))&&(g+=.25,m.push("touched-in-session")),u.has(me.normalize(f.path))&&(g+=.15,m.push("high-centrality")),f.isEntry&&(g+=.05,m.push("entry-point")),!a&&l.size>0&&g>0)try{let w=St.readFileSync(me.join(s,f.path),"utf-8");f.lines=w.split(`
207
- `).length;let S=Fg(w,l)*.3;S>.05&&(g+=S,m.push(`content-match(${(S*100).toFixed(0)}%)`))}catch{}(g>.02||m.length>0)&&h.push({path:f.path,score:Math.min(g,1),reasons:m.length?m:["low-relevance"],lines:f.lines,modifiedAt:f.mtime})}return h.sort((f,m)=>m.score-f.score),{files:h.slice(0,n),totalCandidates:p.length,buildTimeMs:Date.now()-e}}function yc(t){return{name:"suggest_relevant_files",description:"Given your current task/query, rank the project files by relevance and return the top candidates to read first. Use this at the START of complex tasks to avoid reading the wrong files.",safety:"safe",parameters:{query:{type:"string",description:"Description of the task \u2014 used to find relevant files",required:!0},top_k:{type:"number",description:"Number of files to return (default: 12)",required:!1}},execute:async e=>{let r=Dg({query:e.query,workingDir:t,topK:e.top_k||12,skipContentScan:!1});if(!r.files.length)return{success:!0,output:"No relevant files found. The project may be empty or all files are excluded."};let s=[`Top ${r.files.length} relevant files for: "${e.query}"`,`(scanned ${r.totalCandidates} files in ${r.buildTimeMs}ms)`,""];for(let n of r.files){let i=(n.score*100).toFixed(0).padStart(3);s.push(` [${i}%] ${n.path}${n.lines?` (${n.lines}L)`:""}`),s.push(` ${n.reasons.join(" \xB7 ")}`)}return{success:!0,output:s.join(`
208
- `)}}}}var vt=class{tools=new Map;constructor(e,r){let s=ul(e);for(let n of s)this.tools.set(n.name,n);this.tools.set("run_command",ml(e,r)),this.tools.set("search_codebase",gl(e)),this.tools.set("detect_bugs",bl(e)),this.tools.set("web_search",Tl());for(let n of kl())this.tools.set(n.name,n);for(let n of Rl(e))this.tools.set(n.name,n);for(let n of Dl())this.tools.set(n.name,n);this.tools.set("download_asset",Vl(e));for(let n of Ql(e,r))this.tools.set(n.name,n);for(let n of ec(e))this.tools.set(n.name,n);for(let n of nc(e))this.tools.set(n.name,n);for(let n of oc(e))this.tools.set(n.name,n);for(let n of uc(e))this.tools.set(n.name,n);for(let n of pc(e))this.tools.set(n.name,n);this.tools.set("suggest_relevant_files",yc(e))}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},s=[];for(let[n,i]of Object.entries(e.parameters))r[n]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(n);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:s}}}})}getToolDescriptions(){return this.getAll().map(r=>{let s=Object.entries(r.parameters).map(([n,i])=>` ${n}: ${i.type} \u2014 ${i.description}`).join(`
205
+ `)}let f=re.resolve(t,h);return $e.mkdirSync(re.dirname(f),{recursive:!0}),$e.writeFileSync(f,p,"utf-8"),{success:!0,output:[`TDD scaffold created: ${h}`,`Functions scaffolded: ${o.join(", ")}`,`Framework: ${d}`,"","Next steps (TDD red-green-refactor):"," 1. Run tests \u2192 confirm they FAIL (red)"," 2. Write minimal implementation in: "+i," 3. Run tests again \u2192 confirm they PASS (green)"," 4. Refactor if needed, run once more"].join(`
206
+ `)}}}]}var vt=k(require("fs")),me=k(require("path")),Ig=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage"]),jg=new Set([".ts",".tsx",".js",".jsx",".mjs",".py",".go",".rs",".java",".md",".json",".yaml",".yml",".toml"]),Pg=500,Mg=8e3;function mc(t){return t.toLowerCase().replace(/[^a-z0-9\u0600-\u06FF]/g," ").split(/\s+/).filter(e=>e.length>2)}function gc(t,e){let r=0;for(let s of t)e.has(s)&&r++;return t.size>0?r/t.size:0}function Fg(t,e){let r=new Set(t.toLowerCase().replace(/[/_-]/g," ").split(/\s+/).filter(s=>s.length>1));return gc(e,r)}function Lg(t,e){let s=(e-t)/(1e3*60*60*24);return s<1?1:s<7?.5:s<30?.2:.05}function Dg(t,e){if(e.size===0)return 0;let r=new Set(mc(t.slice(0,Mg)));return gc(e,r)}function Ng(t){return/\b(index|main|app|server|cli|entry)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/.test(t)}function yc(t,e,r=[]){if(r.length>=Pg)return r;try{let s=vt.readdirSync(t,{withFileTypes:!0});for(let n of s){if(Ig.has(n.name)||n.name.startsWith("."))continue;let i=me.join(t,n.name);if(n.isDirectory())yc(i,e,r);else if(jg.has(me.extname(n.name)))try{let o=vt.statSync(i);if(o.size>200*1024)continue;let a=me.relative(e,i);r.push({path:a,mtime:o.mtimeMs,size:o.size,lines:0,isEntry:Ng(a)})}catch{}}}catch{}return r}function Ug(t){let e=Date.now(),{query:r,workingDir:s,topK:n=12,recentlyTouched:i=[],importantFiles:o=[],skipContentScan:a=!1}=t,l=new Set(mc(r)),c=new Set(i.map(f=>me.normalize(f))),u=new Set(o.map(f=>me.normalize(f))),d=Date.now(),p=yc(s,s),h=[];for(let f of p){let m=[],g=0,y=Fg(f.path,l)*.35;y>.1&&(g+=y,m.push(`name-match(${(y*100).toFixed(0)}%)`));let b=Lg(f.mtime,d)*.2;if(b>.05&&(g+=b,m.push(`fresh(${(b*100).toFixed(0)}%)`)),c.has(me.normalize(f.path))&&(g+=.25,m.push("touched-in-session")),u.has(me.normalize(f.path))&&(g+=.15,m.push("high-centrality")),f.isEntry&&(g+=.05,m.push("entry-point")),!a&&l.size>0&&g>0)try{let w=vt.readFileSync(me.join(s,f.path),"utf-8");f.lines=w.split(`
207
+ `).length;let S=Dg(w,l)*.3;S>.05&&(g+=S,m.push(`content-match(${(S*100).toFixed(0)}%)`))}catch{}(g>.02||m.length>0)&&h.push({path:f.path,score:Math.min(g,1),reasons:m.length?m:["low-relevance"],lines:f.lines,modifiedAt:f.mtime})}return h.sort((f,m)=>m.score-f.score),{files:h.slice(0,n),totalCandidates:p.length,buildTimeMs:Date.now()-e}}function wc(t){return{name:"suggest_relevant_files",description:"Given your current task/query, rank the project files by relevance and return the top candidates to read first. Use this at the START of complex tasks to avoid reading the wrong files.",safety:"safe",parameters:{query:{type:"string",description:"Description of the task \u2014 used to find relevant files",required:!0},top_k:{type:"number",description:"Number of files to return (default: 12)",required:!1}},execute:async e=>{let r=Ug({query:e.query,workingDir:t,topK:e.top_k||12,skipContentScan:!1});if(!r.files.length)return{success:!0,output:"No relevant files found. The project may be empty or all files are excluded."};let s=[`Top ${r.files.length} relevant files for: "${e.query}"`,`(scanned ${r.totalCandidates} files in ${r.buildTimeMs}ms)`,""];for(let n of r.files){let i=(n.score*100).toFixed(0).padStart(3);s.push(` [${i}%] ${n.path}${n.lines?` (${n.lines}L)`:""}`),s.push(` ${n.reasons.join(" \xB7 ")}`)}return{success:!0,output:s.join(`
208
+ `)}}}}var _t=class{tools=new Map;constructor(e,r){let s=fl(e);for(let n of s)this.tools.set(n.name,n);this.tools.set("run_command",gl(e,r)),this.tools.set("search_codebase",yl(e)),this.tools.set("detect_bugs",xl(e)),this.tools.set("web_search",Cl());for(let n of Tl())this.tools.set(n.name,n);for(let n of Il(e))this.tools.set(n.name,n);for(let n of Nl())this.tools.set(n.name,n);this.tools.set("download_asset",zl(e));for(let n of Zl(e,r))this.tools.set(n.name,n);for(let n of tc(e))this.tools.set(n.name,n);for(let n of ic(e))this.tools.set(n.name,n);for(let n of ac(e))this.tools.set(n.name,n);for(let n of fc(e))this.tools.set(n.name,n);for(let n of hc(e))this.tools.set(n.name,n);this.tools.set("suggest_relevant_files",wc(e))}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},s=[];for(let[n,i]of Object.entries(e.parameters))r[n]={type:i.type==="number"?"number":"string",description:i.description},i.required&&s.push(n);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:s}}}})}getToolDescriptions(){return this.getAll().map(r=>{let s=Object.entries(r.parameters).map(([n,i])=>` ${n}: ${i.type} \u2014 ${i.description}`).join(`
209
209
  `);return`- ${r.name} [${r.safety}]: ${r.description}
210
210
  ${s}`}).join(`
211
211
 
212
- `)}};var wc=k(require("crypto"));function qn(t){return Math.ceil(t.length/3.5)}function zt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
213
- ... [truncated to fit context budget]`}var _t=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,s){let n=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===n){i.lastUsed=Date.now(),i.accessCount++;return}let o=qn(r),a=s?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:n,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let s=this.cache.get(e);return s?s.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),n=0,i=[];for(let o of s){if(n+o.tokenCount>r){if(o.importance>=7){let a=r-n;if(a>200){let l=zt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
212
+ `)}};var bc=k(require("crypto"));function Hn(t){return Math.ceil(t.length/3.5)}function Kt(t,e){let r=Math.floor(e*3.5);return t.length<=r?t:t.slice(0,r)+`
213
+ ... [truncated to fit context budget]`}var kt=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,s){let n=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===n){i.lastUsed=Date.now(),i.accessCount++;return}let o=Hn(r),a=s?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let l={path:e,content:r,hash:n,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:s?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,l),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let s=this.cache.get(e);return s?s.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,s=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),n=0,i=[];for(let o of s){if(n+o.tokenCount>r){if(o.importance>=7){let a=r-n;if(a>200){let l=Kt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
214
214
  ${l}`),n+=a}}continue}i.push(`--- ${o.path} ---
215
215
  ${o.content}`),n+=o.tokenCount}return i.join(`
216
216
 
217
217
  `)}buildAgentContext(e,r){let s=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(c=>i.length===0?!0:i.some(u=>c.path.includes(u))).sort((c,u)=>this.computeScore(u)-this.computeScore(c)),a=0,l=[];for(let c of o){if(a+c.tokenCount>s)break;l.push(`--- ${c.path} ---
218
218
  ${c.content}`),a+=c.tokenCount}return l.join(`
219
219
 
220
- `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([n,i])=>({key:n,...i,score:this.computeScore(i)})).sort((n,i)=>n.score-i.score),s=0;for(let n of r){if(s>=e)break;n.importance>=9||(s+=n.tokenCount,this.usedTokens-=n.tokenCount,this.cache.delete(n.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let n=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-n/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let n=qn(r);return n>2e3&&(s=Math.max(1,s-1)),n>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let s of r)if(s!==e){let n=this.cache.get(s);n&&!n.relatedFiles.includes(e)&&n.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return wc.createHash("md5").update(e).digest("hex")}};var Ng=0;function Kt(){return`msg_${Date.now()}_${++Ng}`}function kt(t){return Math.ceil(t.length/4)}var Tt=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=200,s=128e3){this.maxMessages=r,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let n=kt(e);this.messages.push({id:Kt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:n,compressed:!1,tags:["system"]}),this.totalTokens=n}getSessionId(){return this.sessionId}addUserMessage(e,r){let s=Kt(),n=kt(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:n,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=n,this.trimIfNeeded(),s}addAssistantMessage(e,r,s){let n=Kt(),i=kt(e),o={id:n,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),n}addToolMessage(e,r){let s=Kt(),n=kt(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:n,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=n,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=kt(e),s={id:Kt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[s],this.recalculateTokens();return}this.messages[0]=s,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(s=>s.id===e);return r?(this.messages=r.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let s=this.messages.length,n=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?n.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&n.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:n}),n}mergeFork(e,r){let s=this.forks.get(e);if(!s)return!1;let n=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(n.length>0){let i=n.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(s=>s.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],s=this.messages.slice(1),n={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=n[a.priority]-n[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,1200)+`
220
+ `)}getTotalTokens(){return this.usedTokens}getCacheSize(){return this.cache.size}getCacheInfo(){return Array.from(this.cache.values()).map(e=>({path:e.path,tokens:e.tokenCount,importance:e.importance,accesses:e.accessCount})).sort((e,r)=>r.importance-e.importance)}evictToFit(e){let r=Array.from(this.cache.entries()).map(([n,i])=>({key:n,...i,score:this.computeScore(i)})).sort((n,i)=>n.score-i.score),s=0;for(let n of r){if(s>=e)break;n.importance>=9||(s+=n.tokenCount,this.usedTokens-=n.tokenCount,this.cache.delete(n.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let n=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-n/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let s=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(s=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(s=3);let n=Hn(r);return n>2e3&&(s=Math.max(1,s-1)),n>5e3&&(s=Math.max(1,s-2)),s}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let s of r)if(s!==e){let n=this.cache.get(s);n&&!n.relatedFiles.includes(e)&&n.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return bc.createHash("md5").update(e).digest("hex")}};var qg=0;function Gt(){return`msg_${Date.now()}_${++qg}`}function Tt(t){return Math.ceil(t.length/4)}var Ct=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=200,s=128e3){this.maxMessages=r,this.maxTokens=s,this.sessionId=`session_${Date.now()}`;let n=Tt(e);this.messages.push({id:Gt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:n,compressed:!1,tags:["system"]}),this.totalTokens=n}getSessionId(){return this.sessionId}addUserMessage(e,r){let s=Gt(),n=Tt(e);return this.messages.push({id:s,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:n,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=n,this.trimIfNeeded(),s}addAssistantMessage(e,r,s){let n=Gt(),i=Tt(e),o={id:n,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:s||"hablas",tokenEstimate:i,compressed:!1,tags:s?[`agent:${s}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,s&&this.agentMessageCounts.set(s,(this.agentMessageCounts.get(s)||0)+1),this.trimIfNeeded(),n}addToolMessage(e,r){let s=Gt(),n=Tt(e);return this.messages.push({id:s,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:n,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=n,this.trimIfNeeded(),s}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=Tt(e),s={id:Gt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[s],this.recalculateTokens();return}this.messages[0]=s,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(s=>({...s})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(s=>s.id===e);return r?(this.messages=r.messages.map(s=>({...s})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let s=this.messages.length,n=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?n.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&n.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:s,session:n}),n}mergeFork(e,r){let s=this.forks.get(e);if(!s)return!1;let n=s.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(n.length>0){let i=n.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(s=>s.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(s=>s.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(s=>s.role==="assistant"&&!s.compressed&&s.priority!=="critical"&&s.tokenEstimate>300);for(let s of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(s)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],s=this.messages.slice(1),n={critical:3,high:2,normal:1,low:0},i=s.sort((o,a)=>{let l=n[a.priority]-n[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,s=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,1200)+`
221
221
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,800)+`
222
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=kt(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var $t=k(require("fs")),bc=k(require("path"));var O=k(require("fs")),R=k(require("path"));function Ug(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let r=JSON.parse(O.readFileSync(e,"utf-8")),s={...r.dependencies,...r.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let r=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function qg(t){return O.existsSync(R.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(R.join(t,"yarn.lock"))?"yarn":O.existsSync(R.join(t,"bun.lockb"))?"bun":O.existsSync(R.join(t,"package-lock.json"))?"npm":O.existsSync(R.join(t,"Cargo.toml"))?"cargo":O.existsSync(R.join(t,"go.mod"))?"go":O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml"))?"pip":"unknown"}function Bg(t){return O.existsSync(R.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(R.join(t,"package.json"))?"JavaScript":O.existsSync(R.join(t,"Cargo.toml"))?"Rust":O.existsSync(R.join(t,"go.mod"))?"Go":O.existsSync(R.join(t,"pyproject.toml"))||O.existsSync(R.join(t,"requirements.txt"))?"Python":"Unknown"}function Hg(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let r=O.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ct(t){let e=Ug(t),r=qg(t),s=Bg(t),n=Hg(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),l=O.existsSync(R.join(t,".git")),c=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)O.existsSync(R.join(t,m))&&c.push(m);let d=[],p=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of p)O.existsSync(R.join(t,m))&&d.push(m);let h=[],f=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of f)O.existsSync(R.join(t,m))&&h.push(m);return{rootPath:t,framework:e,packageManager:r,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:n,envFiles:c,configFiles:d,entryPoints:h}}function qr(t){let e=[` Project: ${R.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
223
- `)}async function Et(t,e){let r=[],s=bc.join(t,"package.json");if($t.existsSync(s))try{let o=JSON.parse($t.readFileSync(s,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let n=Ct(t);r.push(`Framework: ${n.framework}`),r.push(`Language: ${n.language}`),r.push(`Package Manager: ${n.packageManager}`),r.push(`Git: ${n.hasGit?n.gitBranch||"present":"absent"}`);let i=Wg(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&n.envFiles.length>0&&r.push(`Env files: ${n.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
224
- `)}function Wg(t,e){try{return $t.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}var ie=k(require("fs")),Vn=k(require("path")),_c=k(require("os")),kc=k(require("crypto")),Gt=Vn.join(_c.homedir(),".hablas"),Bn=Vn.join(Gt,"memory.json"),xc=1,Sc=2e3,Vg=1600,zg=8e3;function Kg(){return kc.randomBytes(8).toString("hex")}function vc(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Gg(t,e){let r=t+".tmp."+process.pid;ie.writeFileSync(r,e,"utf-8"),ie.renameSync(r,t)}var Wn=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(ie.existsSync(Gt)||ie.mkdirSync(Gt,{recursive:!0}),ie.existsSync(Bn)){let e=JSON.parse(ie.readFileSync(Bn,"utf-8"));if(e.version===xc)return e}}catch{}return{version:xc,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{ie.existsSync(Gt)||ie.mkdirSync(Gt,{recursive:!0}),Gg(Bn,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(s=>s!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],s=Date.now(),n=e.value.slice(0,zg);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=n,a.updatedAt=s,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=s+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=Kg(),o={id:i,kind:e.kind,key:e.key,value:n,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:s,updatedAt:s,accessCount:0,lastAccessed:s,ttl:e.ttl?s+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let s=this.store.entries[r];return s?s.ttl&&Date.now()>s.ttl?(this.forget(e),null):(s.accessCount++,s.lastAccessed=Date.now(),this.scheduleFlush(),s):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let s=this.store.entries[r];return s?(this.removeFromIndex(s),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let s=Date.now(),n=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&s>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let u=0,d="value",p=c.key.toLowerCase(),h=c.value.toLowerCase();if(p===o)u=1,d="key";else if(p.includes(o))u=Math.max(u,.8),d="key";else if(c.tags.some(f=>f.toLowerCase().includes(o)))u=Math.max(u,.7),d="tag";else{let f=a.filter(m=>h.includes(m)).length;f>0&&(u=Math.max(u,f/Math.max(a.length,1)*.6),d="value")}u>0&&(u=Math.min(1,u+vc(c.priority)*.05+Math.min(.1,c.accessCount*.01)),l.push({entry:c,score:u,matchedOn:d}))}return l.filter(c=>c.score>=i).sort((c,u)=>u.score-c.score).slice(0,n)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(s=>s.kind===e&&(!s.ttl||Date.now()<s.ttl)).sort((s,n)=>n.updatedAt-s.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,s)=>s.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<Sc)return;let r=Date.now();for(let s of Object.values(this.store.entries))s.ttl&&r>s.ttl&&(this.removeFromIndex(s),delete this.store.entries[s.id],e--);if(e>=Sc){let s=Object.values(this.store.entries).map(n=>({id:n.id,score:vc(n.priority)*10+n.accessCount+n.lastAccessed/1e12})).sort((n,i)=>n.score-i.score);for(let{id:n}of s.slice(0,e-Vg)){let i=this.store.entries[n];i&&(this.removeFromIndex(i),delete this.store.entries[n])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
222
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=Tt(e.content),this.totalTokens-=s-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var At=k(require("fs")),xc=k(require("path"));var O=k(require("fs")),R=k(require("path"));function Bg(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let r=JSON.parse(O.readFileSync(e,"utf-8")),s={...r.dependencies,...r.devDependencies};if(s.next)return"next";if(s.nuxt)return"nuxt";if(s["@angular/core"])return"angular";if(s.svelte||s["@sveltejs/kit"])return"svelte";if(s.vue)return"vue";if(s.react)return"react";if(s["@nestjs/core"])return"nest";if(s.fastify)return"fastify";if(s.express)return"express"}catch{}if(O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml")))try{let r=O.existsSync(R.join(t,"requirements.txt"))?O.readFileSync(R.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(O.existsSync(R.join(t,"Cargo.toml")))try{if(O.readFileSync(R.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(O.existsSync(R.join(t,"go.mod")))try{if(O.readFileSync(R.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Hg(t){return O.existsSync(R.join(t,"pnpm-lock.yaml"))?"pnpm":O.existsSync(R.join(t,"yarn.lock"))?"yarn":O.existsSync(R.join(t,"bun.lockb"))?"bun":O.existsSync(R.join(t,"package-lock.json"))?"npm":O.existsSync(R.join(t,"Cargo.toml"))?"cargo":O.existsSync(R.join(t,"go.mod"))?"go":O.existsSync(R.join(t,"requirements.txt"))||O.existsSync(R.join(t,"pyproject.toml"))?"pip":"unknown"}function Wg(t){return O.existsSync(R.join(t,"tsconfig.json"))?"TypeScript":O.existsSync(R.join(t,"package.json"))?"JavaScript":O.existsSync(R.join(t,"Cargo.toml"))?"Rust":O.existsSync(R.join(t,"go.mod"))?"Go":O.existsSync(R.join(t,"pyproject.toml"))||O.existsSync(R.join(t,"requirements.txt"))?"Python":"Unknown"}function Vg(t){let e=R.join(t,".git","HEAD");if(!O.existsSync(e))return null;try{let r=O.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function $t(t){let e=Bg(t),r=Hg(t),s=Wg(t),n=Vg(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),l=O.existsSync(R.join(t,".git")),c=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)O.existsSync(R.join(t,m))&&c.push(m);let d=[],p=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of p)O.existsSync(R.join(t,m))&&d.push(m);let h=[],f=["src/index.ts","src/index.js","src/main.ts","src/main.js","src/app.ts","src/app.js","index.ts","index.js","main.py","app.py","manage.py","main.go","src/main.rs"];for(let m of f)O.existsSync(R.join(t,m))&&h.push(m);return{rootPath:t,framework:e,packageManager:r,language:s,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:n,envFiles:c,configFiles:d,entryPoints:h}}function Br(t){let e=[` Project: ${R.basename(t.rootPath)}`,` Framework: ${t.framework}`,` Language: ${t.language}`,` Package: ${t.packageManager}`,` Git: ${t.hasGit?`\u2713 (${t.gitBranch||"detached"})`:"\u2717"}`,` Docker: ${t.hasDocker?"\u2713":"\u2717"}`,` CI/CD: ${t.hasCICD?"\u2713":"\u2717"}`,` Tests: ${t.hasTests?"\u2713":"\u2717"}`];return t.envFiles.length>0&&e.push(` Env files: ${t.envFiles.join(", ")}`),e.join(`
223
+ `)}async function Et(t,e){let r=[],s=xc.join(t,"package.json");if(At.existsSync(s))try{let o=JSON.parse(At.readFileSync(s,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let n=$t(t);r.push(`Framework: ${n.framework}`),r.push(`Language: ${n.language}`),r.push(`Package Manager: ${n.packageManager}`),r.push(`Git: ${n.hasGit?n.gitBranch||"present":"absent"}`);let i=zg(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&n.envFiles.length>0&&r.push(`Env files: ${n.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
224
+ `)}function zg(t,e){try{return At.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}var ie=k(require("fs")),Kn=k(require("path")),kc=k(require("os")),Tc=k(require("crypto")),Jt=Kn.join(kc.homedir(),".hablas"),Wn=Kn.join(Jt,"memory.json"),Sc=1,vc=2e3,Kg=1600,Gg=8e3;function Jg(){return Tc.randomBytes(8).toString("hex")}function _c(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Xg(t,e){let r=t+".tmp."+process.pid;ie.writeFileSync(r,e,"utf-8"),ie.renameSync(r,t)}var zn=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(ie.existsSync(Jt)||ie.mkdirSync(Jt,{recursive:!0}),ie.existsSync(Wn)){let e=JSON.parse(ie.readFileSync(Wn,"utf-8"));if(e.version===Sc)return e}}catch{}return{version:Sc,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{ie.existsSync(Jt)||ie.mkdirSync(Jt,{recursive:!0}),Xg(Wn,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(s=>s!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],s=Date.now(),n=e.value.slice(0,Gg);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=n,a.updatedAt=s,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=s+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=Jg(),o={id:i,kind:e.kind,key:e.key,value:n,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:s,updatedAt:s,accessCount:0,lastAccessed:s,ttl:e.ttl?s+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let s=this.store.entries[r];return s?s.ttl&&Date.now()>s.ttl?(this.forget(e),null):(s.accessCount++,s.lastAccessed=Date.now(),this.scheduleFlush(),s):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let s=this.store.entries[r];return s?(this.removeFromIndex(s),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let s=Date.now(),n=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(c=>c.length>2),l=[];for(let c of Object.values(this.store.entries)){if(c.ttl&&s>c.ttl||r?.kind&&c.kind!==r.kind||r?.project&&c.project!==r.project)continue;let u=0,d="value",p=c.key.toLowerCase(),h=c.value.toLowerCase();if(p===o)u=1,d="key";else if(p.includes(o))u=Math.max(u,.8),d="key";else if(c.tags.some(f=>f.toLowerCase().includes(o)))u=Math.max(u,.7),d="tag";else{let f=a.filter(m=>h.includes(m)).length;f>0&&(u=Math.max(u,f/Math.max(a.length,1)*.6),d="value")}u>0&&(u=Math.min(1,u+_c(c.priority)*.05+Math.min(.1,c.accessCount*.01)),l.push({entry:c,score:u,matchedOn:d}))}return l.filter(c=>c.score>=i).sort((c,u)=>u.score-c.score).slice(0,n)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(s=>s.kind===e&&(!s.ttl||Date.now()<s.ttl)).sort((s,n)=>n.updatedAt-s.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,s)=>s.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<vc)return;let r=Date.now();for(let s of Object.values(this.store.entries))s.ttl&&r>s.ttl&&(this.removeFromIndex(s),delete this.store.entries[s.id],e--);if(e>=vc){let s=Object.values(this.store.entries).map(n=>({id:n.id,score:_c(n.priority)*10+n.accessCount+n.lastAccessed/1e12})).sort((n,i)=>n.score-i.score);for(let{id:n}of s.slice(0,e-Kg)){let i=this.store.entries[n];i&&(this.removeFromIndex(i),delete this.store.entries[n])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
225
225
  Stack: ${r.stack}${r.summary?`
226
226
  Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,s){this.remember({kind:"decision",key:`decision:${e}:${r.slice(0,60)}`,value:`Decision: ${r}
227
227
  Rationale: ${s}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,r){this.remember({kind:"preference",key:`pref:${e}`,value:r,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,r,s){this.remember({kind:"task_summary",key:`task:${e}:${r.slice(0,60)}:${Date.now()}`,value:`Task: ${r}
228
228
  Outcome: ${s}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,r=3e3){let s=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){s.push("## Memory: this project");for(let o of i.slice(0,8))s.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let n=this.getByKind("preference",5);if(n.length>0){s.push("## Memory: user preferences");for(let i of n)s.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return s.join(`
229
- `).slice(0,r)}},Hn=null;function Jt(){return Hn||(Hn=new Wn),Hn}function At(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",ee("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",ee("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",ee("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",ee("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",ee("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",ee("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",ee("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",ee("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",ee("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",ee("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",ee("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",ee("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let s=Jt().buildContextBlock(r,2500);return s.trim()?[ee("PERSISTENT MEMORY",s),""]:[]})(),ee("TASK PROFILE",Xg(e)),"",ee("CURRENT PROJECT CONTEXT",Yg(t)),"",ee("REASONING PROTOCOL",Jg(e))].join(`
230
- `)}function Jg(t){return!t.needsTools||t.kind==="casual"?"For this turn: answer directly and clearly. No tool protocol needed.":t.kind==="read"?["This is a READ/INSPECT turn.","1. Locate the minimum relevant files.","2. Read them. Form your answer from evidence.","3. Do not speculate \u2014 answer only from what you observe."].join(`
229
+ `).slice(0,r)}},Vn=null;function Xt(){return Vn||(Vn=new zn),Vn}function Ot(t,e,r){return["You are Hablas.","","You are a high-caliber single-agent software engineering runtime created by Abdulmoin Hablas.","Your bar is elite production execution: correct judgment, concrete delivery, honest verification, and calm ownership.","",ee("CORE IDENTITY",["- You are the ONLY visible agent.","- You never mention internal teams, hidden layers, specialist personas, routing systems, orchestration, or agent delegation.","- You are one runtime, one conversation surface, and one unified engineering mind.","- You think with the depth of a principal engineer, systems architect, debugger, reviewer, product thinker, researcher, and delivery lead \u2014 but you answer as one coherent operator.","- Do not invent public modes, specialist theatre, or assistant handoffs.","- Image understanding, when needed, lives ONLY inside image tooling. Vision is a tool capability of inspect_image, not a second assistant, not a second runtime, and not a public model choice for Hablas."]),"",ee("PERSONALITY / INTERACTION",["- Warm-professional","- Precise","- Calm","- Direct","- Technically serious","- Evidence-driven","- Quietly proactive","- High-ownership","- No emojis","- No hype","- No filler","- No motivational fluff","- No fake confidence","- No cold robotic emptiness","","Communication rules:","- Match the user's language naturally. If the user writes Arabic, answer in Arabic. If English, answer in English. If mixed, respond in the most natural useful mix.","- For simple greetings or short social turns, reply with one short warm line plus readiness when helpful. Never return an empty-feeling answer.","- Keep identity answers compact unless the user explicitly asks for detail.","- During engineering work, reduce small talk and move the work forward.","- Prefer decisive wording when evidence exists. When uncertainty exists, state it precisely instead of hedging vaguely.","- After meaningful work, optionally suggest one concrete high-value next step \u2014 not a generic list of ideas.","- Do not echo the user's exact wording unless it improves clarity.","- Do not expose internal chain-of-thought.","- Sound like a strong engineering partner, not a sterile shell and not a chatty motivational bot."]),"",ee("MISSION",["Your mission is to convert user intent into correct, concrete engineering outcomes.","That means you must:","- understand the real task","- respect the user's architecture and constraints","- inspect reality before making claims","- use the correct tools when action is required","- modify real files when implementation is requested","- verify before claiming success","- report honestly what changed, what was verified, and what remains uncertain"]),"",ee("DECISION PRIORITIES",["When trade-offs appear, prioritize in this order:","1. Reality and correctness","2. Actual task completion","3. Preserving the user's stated architecture, constraints, and product direction","4. Minimal correct change surface","5. Verification and regression awareness","6. Clarity of delivery","7. Speed","- Prefer honest partial progress over polished fiction.","- Default to safe, conservative assumptions only when they let you continue correctly. Ask only when ambiguity would materially risk the result or cause destructive wrong work."]),"",ee("INTERPRETATION MODEL",["Interpret requests by BEHAVIOR CLASS, not by literal phrase matching.","The same intent may appear in Arabic, English, mixed language, slang, shorthand, typos, or incomplete wording.","Your job is to infer the class of work, not wait for perfect phrasing.","","Internal behavior classes:","1. Social / casual turn","2. Read-only inspection / factual project question","3. Analysis / architecture / design reasoning","4. Implementation / modification / upgrade / repair","5. Continuation of existing unfinished work","6. One-step delivery with minimal back-and-forth","7. Web / asset / external-resource acquisition","","You must infer these classes from intent, not exact wording.","Never gate behavior on specific trigger words, exact commands, or a fixed phrase list.","Typos do NOT downgrade the task.","If the user clearly wants a real project outcome, treat it as execution work even if the wording is imperfect."]),"",ee("TURN OPERATING LOOP",["Run every non-trivial turn through this internal execution cadence:","1. ORIENT \u2014 infer the real goal, success criteria, constraints, requested depth, and whether the user wants analysis or execution.","2. GROUND \u2014 inspect the relevant files, commands, or external evidence before making project-specific claims.","3. PLAN \u2014 choose the smallest correct path that satisfies the request.","4. EXECUTE \u2014 do the work with tools; avoid performative narration and avoid stalling in explanation.","5. VERIFY \u2014 run the strongest reasonable checks available for the change.","6. DELIVER \u2014 present the result in a clean, executive format tailored to the task.","","Execution cadence rules:","- For implementation work, do not ask performative questions when a safe assumption lets you continue.","- For continuation work, start from existing artifacts instead of reimagining the project from zero.","- For one-step delivery requests, maximize completion in one pass while remaining honest about limits.","- If your previous direction was weak, correct course fast instead of defending it."]),"",ee("NON-NEGOTIABLE RULES",["1. If the task does not need tools, answer directly.","2. If the task needs tools, use tools.","3. If the task is implementation-oriented, prose-only output is insufficient.","4. Read before editing when content is unknown.","5. Do not reread the same file unless:"," - it changed, or"," - you need a different section not already captured.","6. One tool call at a time.","7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.","8. Never claim a file was created, edited, downloaded, tested, verified, or fixed unless a tool actually did it.","9. Ground project-specific claims in observed files, command output, or current web evidence.","10. Verify before claiming completion.","11. If not verified, say so explicitly.","12. Ask clarifying questions only when genuinely blocked.","13. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.","14. Preserve the user's architecture, naming, and product direction unless they explicitly ask to change them.","15. Do not invent blockers. If you can proceed safely, proceed.","16. Do not return empty or placeholder replies for social turns or completed work."]),"",ee("TOOL CONTRACTS",["Choose tools by function, not habit.","","Filesystem and code editing:","- read_file: inspect actual content","- list_dir: inspect structure","- get_file_info: inspect file metadata/existence","- write_file: create new files or full rewrites","- patch_file: preferred for line-based targeted edits","- edit_file: exact-content surgical replacement when exact source text is known","- search_and_replace: bulk exact/regex replacement","- append_to_file: append intentionally","- move_file: rename/relocate","- delete_file: remove only when truly necessary","- create_dir: create folder structure","","Code understanding:","- search_codebase: find symbols, patterns, references, duplication, structure","- detect_bugs: run static issue detection when it helps","- execute_code: run isolated logic snippets when that is the correct verification route","","Build / verification / runtime:","- run_command: install, build, test, lint, typecheck, run, verify","","Git intelligence (read-only, safe):","- git_status: understand repo state before/after edits","- git_diff: inspect exact line-level changes for a file or whole tree","- git_log: recent commit history, optionally filtered by file","- git_branch: list branches and tracking info","","Persistent memory (cross-session, critical):","- search_memory: for complex tasks call this FIRST \u2014 retrieves past decisions/preferences","- remember: store key decisions and preferences that survive session restarts","- recall: retrieve a specific memory by exact key","- forget: delete an outdated or wrong memory","","Memory usage rules:","- complex implementation: call search_memory FIRST","- after significant work: call remember with the key decision/outcome","- user states a preference: call remember immediately","- casual or trivial turns: skip memory tools","","Web / internet / assets:","- web_search: current information, libraries, APIs, docs, images, references","- search_image_candidates: search and rank image candidates using trusted-source weighting and keyword scoring","- inspect_image: inspect a remote image candidate or image page before adoption; use it to check dimensions, direct-image status, source quality, suitability, and tool-local vision analysis when needed","- scrape_url: inspect page content","- extract_links: collect concrete links from a page","- download_asset: bring real external assets into the project (hero images, wallpaper, icons, etc.)","- read_pdf / pdf_metadata: inspect PDF-based specs and docs","","Tool usage principles:","- Use the minimum necessary sequence.","- Use web tools when the task depends on current internet resources or external assets.","- For image-heavy work, prefer: search_image_candidates -> inspect_image -> download_asset.","- Use download_asset when the user wants an actual local asset in the project, not just a URL suggestion.","- Prefer trusted image sources and high-confidence candidates over brute-force downloading random links.","- Avoid repeated blind retries on weak or blocked image URLs; inspect or switch candidate first.","- For image acquisition or replacement, stay inside the image toolchain. Do not fall back to run_command, execute_code, curl, powershell, or guessed public image IDs unless the user explicitly asked for low-level debugging.","- If a source is rate-limited or weak, switch trusted source or candidate instead of improvising with shell hacks.","- For frontend work, prefer integrating real local assets over leaving everything as remote placeholder links if practical.","- For implementation tasks, tool usage is part of the work itself, not an optional add-on."]),"",ee("WORK MODE CONTRACTS",["A) SOCIAL / CASUAL","- 1\u20132 natural sentences","- warm but compact","- no tools unless absolutely necessary","- if the user is just greeting, acknowledge and signal readiness","","B) READ-ONLY INSPECTION","- answer first, then support with evidence when useful","- inspect the minimum relevant evidence","- answer factually","- do not invent unseen details","- avoid giant reports for small questions","","C) ANALYSIS / ARCHITECTURE","- reason from constraints first","- inspect files only when needed to ground the recommendation","- deliver assumptions, trade-offs, constraints, and the practical next move","- do not drift into implementation if the user asked for analysis only","","D) IMPLEMENTATION / MODIFICATION / UPGRADE / FIX","- inspect -> change -> verify -> report","- enter a real tool-based execution path","- make actual file changes when needed","- finish with a tangible result, not a plan disguised as a result","- if blocked, state the exact blocker and the nearest completed state","","E) CONTINUATION OF EXISTING WORK","- continue from what exists","- reuse current artifacts, files, and structure","- do not restart the project from zero unless explicitly told to rewrite it from scratch","","F) ONE-STEP DELIVERY","- minimize unnecessary back-and-forth","- complete as much as possible in one pass","- remain honest about what was and was not verified","","G) WEB / UI / ASSET WORK","- inspect the current files first","- improve actual files, not just describe improvements","- think about hierarchy, spacing, typography, responsiveness, visual quality, coherence, and usability","- for internet images/assets, rank candidates, inspect them, then download the strongest option","- prefer trusted sources and semantically relevant candidates","- if assets already exist locally, prefer reusing or upgrading them intelligently","- if inspect_image returns weak semantic confidence, switch candidate instead of forcing a weak download","- for bulk replace-all image tasks, avoid expensive forensic auditing of every old asset unless the user explicitly asked for an audit; do a light inventory and move into replacement flow","- do not brute-force many low-quality downloads when stronger candidates are available"]),"",ee("DEBUGGING / REVIEW / QUALITY BAR",["When debugging:","- symptom -> evidence -> hypothesis -> verification -> fix -> verification again","- focus on root cause, not surface symptoms","- keep the fix minimal and justified","","Before finalizing technical work, silently review for:","- correctness","- security","- maintainability","- consistency with existing code","- regressions","- verification status","- whether the user asked for a real result and actually got one"]),"",ee("ANTI-FAILURE RULES",["- If the task is implementation-oriented and you responded without tools, your response is likely incomplete.","- If the task involves project files and you did not inspect the relevant files, your confidence should be low.","- If the task involves modification but no files were changed, the task is likely incomplete.","- If the task involves internet images/assets and you only discussed URLs without integrating anything, the task is likely incomplete unless the user asked for ideas only.","- If you detect that your previous direction was too weak, correct course and execute properly.","- If continuity is needed but you ignored prior context, your answer quality is degraded."]),"",ee("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let s=Xt().buildContextBlock(r,2500);return s.trim()?[ee("PERSISTENT MEMORY",s),""]:[]})(),ee("TASK PROFILE",Zg(e)),"",ee("CURRENT PROJECT CONTEXT",Qg(t)),"",ee("REASONING PROTOCOL",Yg(e))].join(`
230
+ `)}function Yg(t){return!t.needsTools||t.kind==="casual"?"For this turn: answer directly and clearly. No tool protocol needed.":t.kind==="read"?["This is a READ/INSPECT turn.","1. Locate the minimum relevant files.","2. Read them. Form your answer from evidence.","3. Do not speculate \u2014 answer only from what you observe."].join(`
231
231
  `):t.complexity==="XS"||t.complexity==="S"?["Compact reasoning \u2014 think briefly before acting:","<thinking>Goal | Next step | Why</thinking>","Then execute. One tool call per step."].join(`
232
232
  `):["FULL REASONING PROTOCOL (non-negotiable for this task complexity):","","BEFORE any tool call:","<thinking>"," GOAL: What does the user want? (one sentence)"," KNOWN: What do I already have?"," UNKNOWN: What must I still find out?"," PLAN: Numbered steps to reach the goal."," NEXT: The single next action and why.","</thinking>","","AFTER each tool result:","<thinking>"," OBSERVATION: What did the tool return?"," PROGRESS: Which steps are done / which remain?"," NEXT: The logical next step.","</thinking>","","Rules:","- ALWAYS think before acting \u2014 no bare tool calls.","- One tool call per step. Wait for the result.","- If a tool fails, analyze the error before retrying.","- When done: give a concise final answer WITHOUT <thinking> tags.","- Build a PLAN: block first. Then execute step 1."].join(`
233
233
  `)}function ee(t,e){let r=Array.isArray(e)?e.join(`
234
234
  `):e;return["====================",t,"====================",r].join(`
235
- `)}function Yg(t){return t.trim()||"No project context captured."}function Xg(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
235
+ `)}function Qg(t){return t.trim()||"No project context captured."}function Zg(t){return t.kind==="casual"?["- Casual/social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short, natural, and never empty-feeling.","- If the user is only greeting, acknowledge warmly and signal readiness."].join(`
236
236
  `):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Answer directly, then support with observed facts when useful.","- Keep the final answer factual, grounded, tight, and pleasantly professional."].join(`
237
237
  `):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning from constraints first.","- Inspect files only when they materially improve the recommendation.","- Deliver trade-offs, assumptions, practical guidance, and the best next move."].join(`
238
238
  `):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with minimal follow-up questions.":"- Ask a clarifying question only if the task is truly blocked.","- Real workspace tool usage is mandatory.","- Do not answer with inline code only if files can be created or modified directly.","- The task is not complete unless the relevant files were inspected and then changed or created when needed.","- Preserve the existing architecture unless the user explicitly asks for a structural change.","- Verify changes before claiming completion.","- End with a compact executive report, not a vague narrative."].join(`
239
- `)}var Qg=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|yep|nope|sure|cool|got it|noted|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك|ايوه|لا|نعم|صح|ماشي|عادي|اوك|oke|oki|👍|✅)[.!?\s]*$/i,Zg=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|install|setup|configure|integrate|connect|wire|scaffold|patch|repair|extend|modify|replace|upgrade|convert|transform|rewrite|delete|move|rename|copy|link|enable|disable|toggle|init|bootstrap|inject|wrap|expose|mount|register|optimize|compress|bundle|minify|lint|format|seed|populate|import|export|push|commit|release|publish|run|test|launch|start|stop|restart|attach|parse|validate|sanitize|encode|decode|hash|encrypt|sign|index|cache|queue|schedule|trigger|emit|listen|subscribe|stream|sync|clone|fork|merge|rebase|reset|stash|apply)\b/i,ey=/(اعمل|افعل|اكتب|انشئ|انشأ|إنشاء|اضف|اضافة|أضف|إضافة|عدل|عدّل|تعديل|احذف|حذف|اصلح|إصلاح|صلح|حسّن|تحسين|ارفع|رفع|نفذ|تنفيذ|شغّل|شغل|ابنِ|بناء|اصنع|ادمج|دمج|ربط|اربط|اضبط|ضبط|حوّل|تحويل|ولّد|توليد|طوّر|تطوير|نزّل|تنزيل|نشر|اطلق|اجرِ|جرّب|اختبر|فعّل|عطّل|حدّث|تحديث|كمّل|خلّص|انهِ|ابدأ|أوقف|اعد|ولد|احضر|جيب|حط|وصّل|اتصل|شارك|ابدا|طبق|اطبق|بدّل|استبدل|غيّر|أوصل)/,ty=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent|addd|dlete|edti|wriet|insatll|confgure|refactr|debugg|buidl|genrate|complet|migarate)\b/i,ry=/\b(architecture|architect|design|blueprint|plan|requirements?|research|compare|investigate|approach|tradeoff|trade-off|pros?|cons?|document|spec|specification|review|audit|analyze|analyse|evaluate|assess|benchmark|profile|diagnose|explain|describe|understand|overview|summary|difference between|vs\.?|versus)\b/i,sy=/(معمارية|تصميم|خطة|متطلبات|بحث|قارن|فهم|اشرح|وضح|ما هو|ما هي|لماذا|الفرق|مقارنة|تحليل|تقييم|دراسة|مراجعة|ملخص|نظرة عامة|توثيق|مواصفات)/,ny=/\b(read|inspect|check|show|list|find|what is|which|where|print|display|view|look at|open|see|tell me|get|retrieve)\b/i,iy=/(اقرأ|اعرض|اظهر|فتش|شوف|وين|انظر|اطلع|اجلب|احضر|قرأ|أظهر|أعرض|بيّن|ليش|وش|إيش)/,Tc=/\b(frontend|backend|fullstack|api|rest|graphql|websocket|endpoint|route|handler|middleware|controller|service|repository|model|schema|entity|migration|seed|store|redux|zustand|context|hook|component|widget|page|screen|view|layout|template|theme|style|css|scss|tailwind|ui|ux|design|responsive|mobile|pwa|spa|ssr|ssg|database|db|sql|nosql|postgres|mysql|sqlite|mongo|redis|elasticsearch|cache|queue|job|worker|cron|auth|oauth|jwt|session|cookie|role|permission|admin|dashboard|panel|cms|landing|hero|carousel|modal|form|input|button|table|chart|card|nav|sidebar|header|footer|banner|image|video|file|upload|download|s3|cdn|stream|search|filter|sort|docker|container|kubernetes|nginx|proxy|ssl|deploy|ci|cd|github|workflow|env|config|secret|monitor|log|test|unit|integration|e2e|coverage|build|bundle|compile|typecheck|lint)\b/i,Cc=/(واجهة|خلفية|قاعدة بيانات|مكون|صفحة|نموذج|مسار|خادم|عميل|تطبيق|موقع|واجهة برمجة|مصادقة|تسجيل|مستخدم|جدول|مخطط|ملف|مجلد|مشروع|مكتبة|حزمة|إعداد|تكوين|نشر|اختبار|بناء|سجل|خطأ|أداء|ذاكرة|نسخ احتياطي)/,oy=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from where|carry on|pick up|keep going|where we left|last time|already started|in progress|go on|dont stop|don't stop|from here)\b/i,ay=/(كمّل|تكملة|أكمل|استمر|استمرار|من السابق|المشروع الحالي|ما اكتملنا|واصل|من اللي وقفنا|اللي بدأناه|كمل|تابع|متابعة)/,ly=/\b(one step|no questions?|no ask|just give me|deliver complete|finished project|run it|dont ask|don't ask|just do it|straight to|go ahead|without asking|autonomous|auto|direct|fully|completely)\b/i,cy=/(بدون أسئلة|ما تسأل|روح عليه|مباشرة|كمّل لحالك|تلقائي|أوتوماتيك|انجزه|بدون سؤال|على طول|خلص بدون)/;function uy(t){let e=t.toLowerCase(),r={implementation:0,analysis:0,read:0,casual:0,continuity:!1,oneStep:!1};r.continuity=oy.test(e)||ay.test(t),r.oneStep=ly.test(e)||cy.test(t),r.continuity&&(r.implementation+=6),r.oneStep&&(r.implementation+=3),Zg.test(e)&&(r.implementation+=5),ey.test(t)&&(r.implementation+=5),ty.test(e)&&(r.implementation+=4),ry.test(e)&&(r.analysis+=4),sy.test(t)&&(r.analysis+=4),ny.test(e)&&(r.read+=3),iy.test(t)&&(r.read+=3),(Tc.test(e)||Cc.test(t))&&(r.implementation+=2);let n=t.split(/\s+/).filter(Boolean).length;return n<=4&&r.implementation<=3&&(r.read+=2),t.endsWith("?")&&(r.read+=2,r.analysis+=1),n>20&&(r.implementation+=2),n>40&&(r.implementation+=2),r}function fy(t){return t<=4?"XS":t<=10?"S":t<=25?"M":t<=50?"L":"XL"}function Yt(t){let e=t.trim(),r=e.toLowerCase(),s=e.split(/\s+/).filter(Boolean).length;if(Qg.test(e))return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,complexity:"XS",reason:"Pure social turn \u2014 no engineering signal detected."};let n=uy(e),i=Tc.test(r)||Cc.test(e);return n.implementation>=5||n.implementation===Math.max(n.implementation,n.analysis,n.read)&&n.implementation>=3?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n.continuity,oneStepDelivery:n.oneStep,requiresProjectContext:!0,complexity:fy(s),reason:n.continuity?"Continuation of in-progress work \u2014 loading existing context.":"Implementation request detected \u2014 tool-based execution required."}:n.analysis>=4&&n.analysis>=n.implementation?{kind:"analysis",needsTools:i,needsWrite:!1,continuity:n.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:i?"Architecture/analysis with project reference \u2014 inspection needed.":"Architecture/design reasoning \u2014 text-first turn."}:n.read>=3||e.endsWith("?")?{kind:"read",needsTools:i,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:i,complexity:"S",reason:i?"Read/inspect request \u2014 file inspection needed.":"Direct factual question \u2014 answer from knowledge."}:{kind:"analysis",needsTools:i,needsWrite:!1,continuity:n.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:"Ambiguous input \u2014 defaulting to analysis mode."}}function dy(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly with full clarity."}];if(t.kind==="read")return[{id:"locate",title:"Locate the minimum relevant files or data."},{id:"inspect",title:"Read and understand the actual content."},{id:"answer",title:"Answer precisely from observed facts only."}];if(t.kind==="analysis")return[{id:"ground",title:"Inspect key files to ground the analysis in reality."},{id:"reason",title:"Form an evidence-based architectural assessment."},{id:"deliver",title:"Present findings as a coherent engineering partner."}];let e=[];return t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery: complete without unnecessary questions."}),t.continuity&&e.push({id:"continuity",title:"Reload existing context \u2014 resume, do not restart."}),e.push({id:"orient",title:"Understand the real goal and success criteria."},{id:"ground",title:"Inspect relevant code, files, and dependencies."},{id:"plan",title:"Choose the smallest correct implementation path."},{id:"implement",title:"Apply the change with the right tools."},{id:"verify",title:"Run verification: build, lint, test, or type-check."},{id:"deliver",title:"Report: what changed, what was verified, what remains."}),e}function $c(t){let e=Yt(t);return{input:t,profile:e,plan:dy(e)}}var Ac=k(require("readline")),ge=k(require("fs")),oe=k(require("path")),Oc=k(require("os"));var Br=oe.join(Oc.homedir(),".hablas","history"),Hr=500,py=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),hy=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],my=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".svg",".sql",".png",".jpg",".jpeg",".webp"]),Ec=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Wr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Ac.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Hr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{let n=s.trim();n&&(this.history.push(n),this.history=this.history.slice(-Hr),this.saveHistory()),r(s)})})}async confirm(e){return(await this.prompt(` ${x.warning("?")} ${e} ${x.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
239
+ `)}var ey=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|yep|nope|sure|cool|got it|noted|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك|ايوه|لا|نعم|صح|ماشي|عادي|اوك|oke|oki|👍|✅)[.!?\s]*$/i,ty=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make|deploy|install|setup|configure|integrate|connect|wire|scaffold|patch|repair|extend|modify|replace|upgrade|convert|transform|rewrite|delete|move|rename|copy|link|enable|disable|toggle|init|bootstrap|inject|wrap|expose|mount|register|optimize|compress|bundle|minify|lint|format|seed|populate|import|export|push|commit|release|publish|run|test|launch|start|stop|restart|attach|parse|validate|sanitize|encode|decode|hash|encrypt|sign|index|cache|queue|schedule|trigger|emit|listen|subscribe|stream|sync|clone|fork|merge|rebase|reset|stash|apply)\b/i,ry=/(اعمل|افعل|اكتب|انشئ|انشأ|إنشاء|اضف|اضافة|أضف|إضافة|عدل|عدّل|تعديل|احذف|حذف|اصلح|إصلاح|صلح|حسّن|تحسين|ارفع|رفع|نفذ|تنفيذ|شغّل|شغل|ابنِ|بناء|اصنع|ادمج|دمج|ربط|اربط|اضبط|ضبط|حوّل|تحويل|ولّد|توليد|طوّر|تطوير|نزّل|تنزيل|نشر|اطلق|اجرِ|جرّب|اختبر|فعّل|عطّل|حدّث|تحديث|كمّل|خلّص|انهِ|ابدأ|أوقف|اعد|ولد|احضر|جيب|حط|وصّل|اتصل|شارك|ابدا|طبق|اطبق|بدّل|استبدل|غيّر|أوصل)/,sy=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent|addd|dlete|edti|wriet|insatll|confgure|refactr|debugg|buidl|genrate|complet|migarate)\b/i,ny=/\b(architecture|architect|design|blueprint|plan|requirements?|research|compare|investigate|approach|tradeoff|trade-off|pros?|cons?|document|spec|specification|review|audit|analyze|analyse|evaluate|assess|benchmark|profile|diagnose|explain|describe|understand|overview|summary|difference between|vs\.?|versus)\b/i,iy=/(معمارية|تصميم|خطة|متطلبات|بحث|قارن|فهم|اشرح|وضح|ما هو|ما هي|لماذا|الفرق|مقارنة|تحليل|تقييم|دراسة|مراجعة|ملخص|نظرة عامة|توثيق|مواصفات)/,oy=/\b(read|inspect|check|show|list|find|what is|which|where|print|display|view|look at|open|see|tell me|get|retrieve)\b/i,ay=/(اقرأ|اعرض|اظهر|فتش|شوف|وين|انظر|اطلع|اجلب|احضر|قرأ|أظهر|أعرض|بيّن|ليش|وش|إيش)/,Cc=/\b(frontend|backend|fullstack|api|rest|graphql|websocket|endpoint|route|handler|middleware|controller|service|repository|model|schema|entity|migration|seed|store|redux|zustand|context|hook|component|widget|page|screen|view|layout|template|theme|style|css|scss|tailwind|ui|ux|design|responsive|mobile|pwa|spa|ssr|ssg|database|db|sql|nosql|postgres|mysql|sqlite|mongo|redis|elasticsearch|cache|queue|job|worker|cron|auth|oauth|jwt|session|cookie|role|permission|admin|dashboard|panel|cms|landing|hero|carousel|modal|form|input|button|table|chart|card|nav|sidebar|header|footer|banner|image|video|file|upload|download|s3|cdn|stream|search|filter|sort|docker|container|kubernetes|nginx|proxy|ssl|deploy|ci|cd|github|workflow|env|config|secret|monitor|log|test|unit|integration|e2e|coverage|build|bundle|compile|typecheck|lint)\b/i,$c=/(واجهة|خلفية|قاعدة بيانات|مكون|صفحة|نموذج|مسار|خادم|عميل|تطبيق|موقع|واجهة برمجة|مصادقة|تسجيل|مستخدم|جدول|مخطط|ملف|مجلد|مشروع|مكتبة|حزمة|إعداد|تكوين|نشر|اختبار|بناء|سجل|خطأ|أداء|ذاكرة|نسخ احتياطي)/,ly=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from where|carry on|pick up|keep going|where we left|last time|already started|in progress|go on|dont stop|don't stop|from here)\b/i,cy=/(كمّل|تكملة|أكمل|استمر|استمرار|من السابق|المشروع الحالي|ما اكتملنا|واصل|من اللي وقفنا|اللي بدأناه|كمل|تابع|متابعة)/,uy=/\b(one step|no questions?|no ask|just give me|deliver complete|finished project|run it|dont ask|don't ask|just do it|straight to|go ahead|without asking|autonomous|auto|direct|fully|completely)\b/i,fy=/(بدون أسئلة|ما تسأل|روح عليه|مباشرة|كمّل لحالك|تلقائي|أوتوماتيك|انجزه|بدون سؤال|على طول|خلص بدون)/;function dy(t){let e=t.toLowerCase(),r={implementation:0,analysis:0,read:0,casual:0,continuity:!1,oneStep:!1};r.continuity=ly.test(e)||cy.test(t),r.oneStep=uy.test(e)||fy.test(t),r.continuity&&(r.implementation+=6),r.oneStep&&(r.implementation+=3),ty.test(e)&&(r.implementation+=5),ry.test(t)&&(r.implementation+=5),sy.test(e)&&(r.implementation+=4),ny.test(e)&&(r.analysis+=4),iy.test(t)&&(r.analysis+=4),oy.test(e)&&(r.read+=3),ay.test(t)&&(r.read+=3),(Cc.test(e)||$c.test(t))&&(r.implementation+=2);let n=t.split(/\s+/).filter(Boolean).length;return n<=4&&r.implementation<=3&&(r.read+=2),t.endsWith("?")&&(r.read+=2,r.analysis+=1),n>20&&(r.implementation+=2),n>40&&(r.implementation+=2),r}function py(t){return t<=4?"XS":t<=10?"S":t<=25?"M":t<=50?"L":"XL"}function Yt(t){let e=t.trim(),r=e.toLowerCase(),s=e.split(/\s+/).filter(Boolean).length;if(ey.test(e))return{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,complexity:"XS",reason:"Pure social turn \u2014 no engineering signal detected."};let n=dy(e),i=Cc.test(r)||$c.test(e);return n.implementation>=5||n.implementation===Math.max(n.implementation,n.analysis,n.read)&&n.implementation>=3?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n.continuity,oneStepDelivery:n.oneStep,requiresProjectContext:!0,complexity:py(s),reason:n.continuity?"Continuation of in-progress work \u2014 loading existing context.":"Implementation request detected \u2014 tool-based execution required."}:n.analysis>=4&&n.analysis>=n.implementation?{kind:"analysis",needsTools:i,needsWrite:!1,continuity:n.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:i?"Architecture/analysis with project reference \u2014 inspection needed.":"Architecture/design reasoning \u2014 text-first turn."}:n.read>=3||e.endsWith("?")?{kind:"read",needsTools:i,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:i,complexity:"S",reason:i?"Read/inspect request \u2014 file inspection needed.":"Direct factual question \u2014 answer from knowledge."}:{kind:"analysis",needsTools:i,needsWrite:!1,continuity:n.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:"Ambiguous input \u2014 defaulting to analysis mode."}}function hy(t){if(!t.needsTools)return[{id:"respond",title:"Respond directly with full clarity."}];if(t.kind==="read")return[{id:"locate",title:"Locate the minimum relevant files or data."},{id:"inspect",title:"Read and understand the actual content."},{id:"answer",title:"Answer precisely from observed facts only."}];if(t.kind==="analysis")return[{id:"ground",title:"Inspect key files to ground the analysis in reality."},{id:"reason",title:"Form an evidence-based architectural assessment."},{id:"deliver",title:"Present findings as a coherent engineering partner."}];let e=[];return t.oneStepDelivery&&e.push({id:"delivery-contract",title:"One-pass delivery: complete without unnecessary questions."}),t.continuity&&e.push({id:"continuity",title:"Reload existing context \u2014 resume, do not restart."}),e.push({id:"orient",title:"Understand the real goal and success criteria."},{id:"ground",title:"Inspect relevant code, files, and dependencies."},{id:"plan",title:"Choose the smallest correct implementation path."},{id:"implement",title:"Apply the change with the right tools."},{id:"verify",title:"Run verification: build, lint, test, or type-check."},{id:"deliver",title:"Report: what changed, what was verified, what remains."}),e}function Ac(t){let e=Yt(t);return{input:t,profile:e,plan:hy(e)}}var Oc=k(require("readline")),ge=k(require("fs")),oe=k(require("path")),Rc=k(require("os"));var Hr=oe.join(Rc.homedir(),".hablas","history"),Wr=500,my=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gy=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],yy=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml",".txt",".env",".sh",".bash",".zsh",".svg",".sql",".png",".jpg",".jpeg",".webp"]),Ec=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Vr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Oc.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Wr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,s=>{let n=s.trim();n&&(this.history.push(n),this.history=this.history.slice(-Wr),this.saveHistory()),r(s)})})}async confirm(e){return(await this.prompt(` ${x.warning("?")} ${e} ${x.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
240
240
  ${x.error("\u26A0")} ${e}`),console.log(` ${x.muted("Type yes to confirm this dangerous action.")}
241
- `),(await this.prompt(` ${x.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let s=Ec.filter(n=>n.startsWith(e));return[s.length?s:Ec,e]}for(let s of hy)if(e.toLowerCase().includes(s)){let n=e.split(s).pop()??"";if(n&&!n.includes(" "))try{let i=oe.dirname(n)||".",o=oe.basename(n),a=oe.resolve(this.workingDir,i),l=ge.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(n))+oe.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let s=r[1],n=this.getProjectFiles(),i=n.filter(o=>o.toLowerCase().startsWith(s.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:n.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,s,n,i=0){if(!(i>=n))try{let o=ge.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||py.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(oe.join(e,a.name),l,s,n,i+1);else{let c=oe.extname(a.name).toLowerCase();(my.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{ge.existsSync(Br)&&(this.history=ge.readFileSync(Br,"utf-8").split(`
242
- `).filter(Boolean).slice(-Hr))}catch{}}saveHistory(){try{let e=oe.dirname(Br);ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0}),ge.writeFileSync(Br,this.history.slice(-Hr).join(`
243
- `),"utf-8")}catch{}}};var gy={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},yy=`
241
+ `),(await this.prompt(` ${x.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let s=Ec.filter(n=>n.startsWith(e));return[s.length?s:Ec,e]}for(let s of gy)if(e.toLowerCase().includes(s)){let n=e.split(s).pop()??"";if(n&&!n.includes(" "))try{let i=oe.dirname(n)||".",o=oe.basename(n),a=oe.resolve(this.workingDir,i),l=ge.readdirSync(a).filter(c=>c.startsWith(o)).slice(0,8).map(c=>e.slice(0,e.lastIndexOf(n))+oe.join(i,c));if(l.length)return[l,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let s=r[1],n=this.getProjectFiles(),i=n.filter(o=>o.toLowerCase().startsWith(s.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:n.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,s,n,i=0){if(!(i>=n))try{let o=ge.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||my.has(a.name))continue;let l=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(oe.join(e,a.name),l,s,n,i+1);else{let c=oe.extname(a.name).toLowerCase();(yy.has(c)||a.name==="Dockerfile"||a.name==="Makefile")&&s.push(l)}}}catch{}}loadHistory(){try{ge.existsSync(Hr)&&(this.history=ge.readFileSync(Hr,"utf-8").split(`
242
+ `).filter(Boolean).slice(-Wr))}catch{}}saveHistory(){try{let e=oe.dirname(Hr);ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0}),ge.writeFileSync(Hr,this.history.slice(-Wr).join(`
243
+ `),"utf-8")}catch{}}};var wy={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},by=`
244
244
  ## Reasoning Protocol
245
245
 
246
246
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -269,15 +269,15 @@ After receiving a tool result, think again:
269
269
  - One tool call per turn. Wait for the result before the next call.
270
270
  - If a tool fails, analyze the error in <thinking> before retrying.
271
271
  - When done, give a concise final answer WITHOUT <thinking> tags.
272
- `.trim(),wy=`
272
+ `.trim(),xy=`
273
273
  ## Reasoning
274
274
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
275
275
  The user will NOT see thinking blocks. One tool call per turn.
276
- `.trim(),zn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...gy,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
276
+ `.trim(),Gn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...wy,...e}}updateConfig(e){Object.assign(this.config,e)}getConfig(){return{...this.config}}enrichSystemPrompt(e,r="M"){return!this.config.thinkingEnabled||r==="XS"?e:r==="S"?`${e}
277
277
 
278
- ${wy}`:`${e}
278
+ ${xy}`:`${e}
279
279
 
280
- ${yy}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],s=e,n=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=n.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(r.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(r.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
280
+ ${by}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],s=e,n=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=n.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());s=s.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(s);a&&(r.push(a[1].trim()),s=s.replace(/<thinking>[\s\S]*$/i,""));let l=/<think>([\s\S]*)$/i.exec(s);return l&&(r.push(l[1].trim()),s=s.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
281
281
 
282
282
  `).trim(),visibleContent:s.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let s=this.turnSteps[this.turnSteps.length-1];s&&(s.observation=e,r&&(s.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,s){return`
283
283
  <self_eval>
@@ -300,34 +300,34 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
300
300
  }
301
301
  </self_eval>
302
302
  `.trim()}parseSelfEval(e){let r=[/^\s*(\{[\s\S]*\})\s*$/,/```(?:json)?\s*\n([\s\S]*?)\n```/,/<self_eval_result>([\s\S]*?)<\/self_eval_result>/,/(\{[\s\S]*?"score"[\s\S]*?"completed"[\s\S]*?\})/];for(let s of r){let n=e.match(s);if(n)try{let i=JSON.parse(n[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,s=typeof e.completed=="boolean"?e.completed:r>=7,n=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:s,rationale:n,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,r,s){return r?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${s.slice(0,300)}`,"</thinking>"].join(`
303
- `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(n=>n.action).length,s=this.turnSteps.filter(n=>n.reflection).length;return`${e} steps, ${r} actions, ${s} reflections`}};function Xt(t){return new zn(t)}var by=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:t=>/EACCES|permission denied/i.test(t),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:t=>/EISDIR|is a directory/i.test(t),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:t=>/EEXIST|already exists/i.test(t),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:t=>/no match|not found in file|search string not found/i.test(t),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:t=>/command not found|not recognized/i.test(t),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:t=>/timeout|timed out|ETIMEDOUT/i.test(t),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:t=>/exit code|exited with|non-zero/i.test(t),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],Kn=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,s){let n=this.failures.get(e),i=n?n.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of by)if(a.test(r)){let l=n?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let s=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
304
- `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Qt(t=3){return new Kn(t)}var Pe=k(require("fs")),zr=k(require("path")),Rc=k(require("os")),Vr=zr.join(Rc.homedir(),".hablas","model-formats.json");function xy(){try{if(Pe.existsSync(Vr))return JSON.parse(Pe.readFileSync(Vr,"utf-8"))}catch{}return{}}function Sy(t){try{let e=zr.dirname(Vr);Pe.existsSync(e)||Pe.mkdirSync(e,{recursive:!0}),Pe.writeFileSync(Vr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Ic(t,e){let r=0,s=!1,n=!1;for(let i=e;i<t.length;i++){let o=t[i];if(n){n=!1;continue}if(o==="\\"&&s){n=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function Zt(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function vy(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function _y(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=Zt(n);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function ky(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim());if(n.parameters||n.name){let i=Zt(n);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function Ty(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;){let n=s[1],i=jc(n);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function jc(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch","git_commit","git_stash","atomic_write","diff_preview","rollback_session","checkpoint_save","checkpoint_restore","checkpoint_list","checkpoint_diff","bash_output","kill_shell"];for(let s of r){let n=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=n.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=c.exec(o))!==null;){let p=u[1].toLowerCase(),h=u[2]??u[3]??u[4];l[p]=vy(h)}let d=a.trim();d&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=d:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Cy(t){return jc(t)}function $y(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=Zt(n);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function Ey(t){let e=[],r=/\{\s*"function"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=Ic(t,s.index);if(n)try{let i=JSON.parse(n),o=Zt(i);o&&e.push({...o,format:"function_call",rawMatch:n})}catch{}}return e}function Ay(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=Ic(t,s.index);if(n)try{let i=JSON.parse(n),o=Zt(i);o&&e.push({...o,format:"json_object",rawMatch:n})}catch{}}return e}function Oy(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,n=!1;for(;(s=r.exec(t))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){n=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=c.exec(i))!==null;){let d=u[1].trim(),p=u[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[d]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!n&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(t))!==null;){let u=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Gn=[{format:"xml_tool_call_wrapper",parse:Ty},{format:"xml_prompt",parse:Cy},{format:"xml_tags",parse:_y},{format:"xml_parameters",parse:Oy},{format:"hermes",parse:ky},{format:"markdown_json",parse:$y},{format:"function_call",parse:Ey},{format:"json_object",parse:Ay}],Yn=class{registry;constructor(){this.registry=xy()}parse(e,r,s){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let n=e||"";if(!n.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=Gn.find(a=>a.format===i.format);if(o){let a=o.parse(n);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,n)}}}for(let{parse:i}of Gn){let o=i(n);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,n)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(n).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:s}of Gn)if(s(e).length>0)return r;return"unknown"}learnFormat(e,r){let s=this.registry[e];s&&s.format===r?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},Sy(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,s]of Object.entries(this.registry))e[r]={format:s.format,successCount:s.successCount};return e}buildResult(e,r){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),n=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)n=n.replace(o.rawMatch,"");return n=n.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),n=n.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),n=this.sanitizeResidualToolMarkup(n),n=n.replace(/\n{3,}/g,`
303
+ `)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(n=>n.action).length,s=this.turnSteps.filter(n=>n.reflection).length;return`${e} steps, ${r} actions, ${s} reflections`}};function Qt(t){return new Gn(t)}var Sy=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:t=>/EACCES|permission denied/i.test(t),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:t=>/EISDIR|is a directory/i.test(t),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:t=>/EEXIST|already exists/i.test(t),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:t=>/no match|not found in file|search string not found/i.test(t),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:t=>/command not found|not recognized/i.test(t),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:t=>/timeout|timed out|ETIMEDOUT/i.test(t),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:t=>/exit code|exited with|non-zero/i.test(t),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],Jn=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,s){let n=this.failures.get(e),i=n?n.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of Sy)if(a.test(r)){let l=n?.lastStrategy===a.strategy&&i>=2,c=l?"decompose_task":a.strategy;return o.lastStrategy=c,this.failures.set(e,o),{errorClass:a.errorClass,strategy:c,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let s=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&s.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":s.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":s.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":s.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":s.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":s.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":s.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return s.join(`
304
+ `)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let r=this.failures.get(e);return r?r.count<=1&&r.lastStrategy==="retry_same":!1}suggestAlternatives(e){return{read_file:["search_codebase","list_dir"],write_file:["edit_file","append_to_file"],edit_file:["search_and_replace","write_file","read_file"],search_and_replace:["edit_file","read_file"],patch_file:["edit_file","write_file"],run_command:["search_codebase"],search_codebase:["read_file","list_dir"],delete_file:["run_command"],create_dir:["run_command"],web_search:["scrape_url"]}[e]??[]}};function Zt(t=3){return new Jn(t)}var Me=k(require("fs")),Kr=k(require("path")),Ic=k(require("os")),zr=Kr.join(Ic.homedir(),".hablas","model-formats.json");function vy(){try{if(Me.existsSync(zr))return JSON.parse(Me.readFileSync(zr,"utf-8"))}catch{}return{}}function _y(t){try{let e=Kr.dirname(zr);Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),Me.writeFileSync(zr,JSON.stringify(t,null,2),"utf-8")}catch{}}function jc(t,e){let r=0,s=!1,n=!1;for(let i=e;i<t.length;i++){let o=t[i];if(n){n=!1;continue}if(o==="\\"&&s){n=!0;continue}if(o==='"'){s=!s;continue}if(!s&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function er(t){if(typeof t.name=="string"&&t.arguments&&typeof t.arguments=="object")return{tool:t.name,args:t.arguments};if(typeof t.tool=="string"&&t.args&&typeof t.args=="object")return{tool:t.tool,args:t.args};if(typeof t.name=="string"&&t.parameters&&typeof t.parameters=="object")return{tool:t.name,args:t.parameters};if(t.function&&typeof t.function=="object"){let e=t.function;if(typeof e.name=="string"){let r={};if(typeof e.arguments=="string")try{r=JSON.parse(e.arguments)}catch{r={}}else e.arguments&&typeof e.arguments=="object"&&(r=e.arguments);return{tool:e.name,args:r}}}return null}function ky(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ty(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=er(n);i&&e.push({...i,format:"xml_tags",rawMatch:s[0]})}catch{}return e}function Cy(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim());if(n.parameters||n.name){let i=er(n);i&&e.push({...i,format:"hermes",rawMatch:s[0]})}}catch{}return e}function $y(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,s;for(;(s=r.exec(t))!==null;){let n=s[1],i=Pc(n);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:s[0]})}return e}function Pc(t){let e=[],r=["read_file","write_file","edit_file","search_and_replace","run_command","search_codebase","list_dir","create_dir","delete_file","append_to_file","patch_file","move_file","get_file_info","web_search","scrape_url","extract_links","read_pdf","pdf_metadata","execute_code","detect_bugs","download_asset","search_image_candidates","inspect_image","remember","recall","search_memory","forget","memory_stats","git_status","git_diff","git_log","git_branch","git_commit","git_stash","atomic_write","diff_preview","rollback_session","checkpoint_save","checkpoint_restore","checkpoint_list","checkpoint_diff","bash_output","kill_shell"];for(let s of r){let n=new RegExp(`<<?${s}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${s}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=n.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},c=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=c.exec(o))!==null;){let p=u[1].toLowerCase(),h=u[2]??u[3]??u[4];l[p]=ky(h)}let d=a.trim();d&&(s==="write_file"||s==="append_to_file"?l.content=a:s==="run_command"?l.command=d:s==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),e.push({tool:s,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function Ay(t){return Pc(t)}function Ey(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,s;for(;(s=r.exec(t))!==null;)try{let n=JSON.parse(s[1].trim()),i=er(n);i&&e.push({...i,format:"markdown_json",rawMatch:s[0]})}catch{}return e}function Oy(t){let e=[],r=/\{\s*"function"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=jc(t,s.index);if(n)try{let i=JSON.parse(n),o=er(i);o&&e.push({...o,format:"function_call",rawMatch:n})}catch{}}return e}function Ry(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,s;for(;(s=r.exec(t))!==null;){let n=jc(t,s.index);if(n)try{let i=JSON.parse(n),o=er(i);o&&e.push({...o,format:"json_object",rawMatch:n})}catch{}}return e}function Iy(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,s,n=!1;for(;(s=r.exec(t))!==null;){let i=s[1],o=/<function=([^>]+)>/i.exec(i);if(o){n=!0;let a=o[1].trim(),l={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=c.exec(i))!==null;){let d=u[1].trim(),p=u[2].trim();p==="true"?p=!0:p==="false"?p=!1:!isNaN(Number(p))&&p!==""&&(p=Number(p)),l[d]=p}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:s[0]})}}if(!n&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,c;for(;(c=l.exec(t))!==null;){let u=c[1].trim(),d=c[2].trim();d==="true"?d=!0:d==="false"?d=!1:!isNaN(Number(d))&&d!==""&&(d=Number(d)),a[u]=d}e.push({tool:o,args:a,format:"xml_parameters",rawMatch:t})}}return e}var Xn=[{format:"xml_tool_call_wrapper",parse:$y},{format:"xml_prompt",parse:Ay},{format:"xml_tags",parse:Ty},{format:"xml_parameters",parse:Iy},{format:"hermes",parse:Cy},{format:"markdown_json",parse:Ey},{format:"function_call",parse:Oy},{format:"json_object",parse:Ry}],Qn=class{registry;constructor(){this.registry=vy()}parse(e,r,s){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return s&&this.learnFormat(s,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let n=e||"";if(!n.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(s){let i=this.registry[s];if(i&&i.format!=="native"){let o=Xn.find(a=>a.format===i.format);if(o){let a=o.parse(n);if(a.length>0)return this.learnFormat(s,i.format),this.buildResult(a,n)}}}for(let{parse:i}of Xn){let o=i(n);if(o.length>0){let a=o[0].format;return s&&this.learnFormat(s,a),this.buildResult(o,n)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(n).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:s}of Xn)if(s(e).length>0)return r;return"unknown"}learnFormat(e,r){let s=this.registry[e];s&&s.format===r?(s.successCount++,s.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},_y(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,s]of Object.entries(this.registry))e[r]={format:s.format,successCount:s.successCount};return e}buildResult(e,r){let s=e.map(o=>({function:{name:o.tool,arguments:o.args}})),n=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)n=n.replace(o.rawMatch,"");return n=n.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),n=n.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),n=this.sanitizeResidualToolMarkup(n),n=n.replace(/\n{3,}/g,`
305
305
 
306
306
  `),{toolCalls:s,displayContent:n.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
307
307
 
308
- `)}},Jn=null;function Pc(){return Jn||(Jn=new Yn),Jn}var Kr=class t{buf="";inThink=!1;visibleEmitted=!1;onToken;static THINK_OPENS=["<thinking>","<think>"];static THINK_CLOSES=["</thinking>","</think>"];static PARTIAL_SCAN=12;constructor(e){this.onToken=e}push(e){this.buf+=e,this.flush_process()}flush(){if(this.inThink){this.buf="",this.inThink=!1;return}if(this.buf.trim()){let e=this.buf.replace(/<\/?think(?:ing)?>/gi,"").trim();e&&this.emit(e)}this.buf=""}get hasVisibleContent(){return this.visibleEmitted}flush_process(){for(;this.buf.length>0;){if(this.inThink){let s=this.findFirst(t.THINK_CLOSES);if(s===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let n=this.buf.indexOf(">",s)+1;this.buf=this.buf.slice(n),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let s=this.longestPartialTail();if(s>0){let n=this.buf.slice(0,this.buf.length-s);n&&this.emit(n),this.buf=this.buf.slice(this.buf.length-s);return}this.emit(this.buf),this.buf="";return}if(e>0){this.emit(this.buf.slice(0,e)),this.buf=this.buf.slice(e);continue}this.inThink=!0;let r=this.buf.indexOf(">")+1;this.buf=this.buf.slice(r>0?r:this.buf.length)}}findFirst(e){let r=-1,s=this.buf.toLowerCase();for(let n of e){let i=s.indexOf(n.toLowerCase());i!==-1&&(r===-1||i<r)&&(r=i)}return r}longestPartialTail(){let e=t.PARTIAL_SCAN,r=this.buf.slice(-e).toLowerCase(),s=0;for(let n of t.THINK_OPENS){let i=n.toLowerCase();for(let o=Math.min(i.length-1,r.length);o>0;o--)if(i.startsWith(r.slice(-o))){s=Math.max(s,o);break}}return s}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var Ry=600,Iy=4e3,jy=16e3,Mc=2;function Py(t,e,r){let n=Pc().parse(e,t,r);return{toolCalls:n.toolCalls,displayContent:n.displayContent}}function My(t,e){return t==="write_file"&&typeof e.path=="string"?"create "+e.path:["edit_file","patch_file","search_and_replace"].includes(t)&&typeof e.path=="string"?"modify "+e.path:t==="read_file"&&typeof e.path=="string"?"read "+e.path:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):t==="remember"&&typeof e.key=="string"?"remember: "+String(e.key).slice(0,60):t==="recall"&&typeof e.key=="string"?"recall: "+String(e.key).slice(0,60):t==="search_memory"&&typeof e.query=="string"?'search memory: "'+String(e.query).slice(0,50)+'"':t==="forget"&&typeof e.key=="string"?"forget: "+String(e.key).slice(0,60):t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?"diff "+e.path:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?"log "+e.path:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Fy(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function Fc(t,e,r,s){let n=0,i=Date.now();for(;n<=Mc;){let o=await t.execute({name:e,arguments:r});if(o.success||n>=Mc)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:n};n++,s.info({tool:e,retry:n,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:n}}async function Xn(t){let{identity:e,client:r,registry:s,session:n,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Xt(),p=t.errorRecovery??Qt(),h=u?[]:s.getOllamaTools(),f=r.getModel(),m=t.maxIterations??Ry,g=[],y=[],b=[],w=new Map,S="",_=0,C=!1;for(;_<m;){if(_++,c?.aborted)return{output:S,toolsUsed:$e(g),toolResults:y,touchedFiles:$e(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let A=d.buildBudgetWarningPrompt();A&&n.addUserMessage(A,{priority:"critical",tags:["system-budget"]});let E;try{if(a.onModelStart?.(y.length>0?"Deciding next step":"Thinking",e),r.streamChatWithTools){let K=!1,re=new Kr(Le=>{K||(a.onModelStop?.(),K=!0),a.onStreamToken?.(Le,e)}),I=r.streamChatWithTools(n.getMessages(),h,Le=>{re.push(Le)},c),F=await I.next();for(;!F.done;)F=await I.next();re.flush(),E=F.value,K||a.onModelStop?.()}else E=await r.chatWithTools(n.getMessages(),h,c),a.onModelStop?.()}catch(K){a.onModelStop?.();let re=K;if(re.name==="AbortError"||c?.aborted)return{output:S,toolsUsed:$e(g),toolResults:y,touchedFiles:$e(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){a.onNotice?.("Transient error: "+de(re).message+" \u2014 retrying...","retry"),await new Promise(F=>setTimeout(F,1e3)),_--;continue}let I=de(re);return I.fatal?(a.onError?.(I.message),{output:S,toolsUsed:$e(g),toolResults:y,touchedFiles:$e(b),iterations:_,success:!1,error:I.message,completedNaturally:C}):(a.onError?.(I.message),{output:S,toolsUsed:$e(g),toolResults:y,touchedFiles:$e(b),iterations:_,success:!1,error:I.message,completedNaturally:C})}if(!E||!E.message){a.onNotice?.("Model returned an empty response \u2014 retrying...","retry"),await new Promise(K=>setTimeout(K,1500));continue}let $=E.message?.content||"",M=E.message?.tool_calls,U=d.parseThinking($);U.hasThinking&&(d.recordStep({thought:U.thinking}),o.debug({thinking:U.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:H}=Py(M,$,f);if(H&&H.trim()&&(S=H,await a.onAssistantText?.(H,e)),N.length===0){n.addAssistantMessage($,void 0,e.role),C=!0;break}n.addAssistantMessage($,N,e.role);let Q=N.length;for(let K=0;K<Q;K++){let re=N[K];if(!re?.function?.name)continue;let I=re.function.name,F=re.function.arguments||{},Le=s.getSafetyLevel(I)??"confirm";if(!s.get(I)){a.onNotice?.("Unknown tool: "+I+" \u2014 skipping","warn"),n.addToolMessage('Error: Unknown tool "'+I+'". Available: '+s.getAll().map(Z=>Z.name).join(", "));continue}if(await l(I,Le,F)==="skip"){n.addToolMessage("Tool "+I+" was skipped by policy/user.");break}let nu=My(I,F),Rt=I==="read_file"?JSON.stringify({path:F.path||"",start:F.start_line||"",end:F.end_line||""}):"";if(I==="read_file"&&Rt&&w.has(Rt)){let Z=w.get(Rt)||"";n.addToolMessage(Z),d.recordObservation(Z.slice(0,300),"Reused cached file read");continue}g.push(I),typeof F.path=="string"&&b.push(F.path),typeof F.from=="string"&&b.push(F.from),typeof F.to=="string"&&b.push(F.to),a.onToolStart?.(I,nu,F),a.onToolCall?.(),d.recordStep({thought:U.hasThinking?"Executing: "+I:"",action:I,actionInput:F});let J=await Fc(s,I,F,o);a.onToolEnd?.(I,J.success,J.error||J.output,J.duration,F);let ze;if(J.success)ze=Lc(I,J.output),d.recordObservation(ze.slice(0,300)),y.push({tool:I,success:!0,summary:J.output.slice(0,150)});else{let Z=J.error||"Unknown error",at=p.analyze(I,Z,F);if(ze=p.buildRecoveryMessage(at,Z),d.recordObservation("FAILED: "+Z,"Recovery: "+at.strategy+" \u2014 "+at.suggestion),o.info({tool:I,errorClass:at.errorClass,strategy:at.strategy},"Error recovery analysis"),y.push({tool:I,success:!1,summary:Z.slice(0,150)}),at.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let lt=await Fc(s,I,F,o);a.onToolEnd?.(I,lt.success,lt.output,lt.duration,F),lt.success&&(ze=Lc(I,lt.output),d.recordObservation(ze.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:I,success:!0,summary:lt.output.slice(0,150)})}}if(n.addToolMessage(ze),J.success&&I==="read_file"&&typeof F.path=="string"&&(i?.addFile(F.path,J.output),Rt&&w.set(Rt,ze)),J.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(I)&&typeof F.path=="string")for(let Z of[...w.keys()])Z.includes('"path":"'+String(F.path).replace(/"/g,'\\"')+'"')&&w.delete(Z);if(J.success&&I==="move_file")for(let Z of[...w.keys()])(F.from&&Z.includes('"path":"'+String(F.from).replace(/"/g,'\\"')+'"')||F.to&&Z.includes('"path":"'+String(F.to).replace(/"/g,'\\"')+'"'))&&w.delete(Z);if(o.info({tool:I,success:J.success,durationMs:J.duration,retries:J.retries},"Tool executed"),!J.success&&Fy(J.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}}d.isOverBudget()&&a.onNotice?.("Reached max reasoning steps ("+d.getConfig().maxSteps+"). Wrapping up.","warn")}return _>=m&&!C&&a.onNotice?.("Reached max iterations ("+m+"). Stopping.","warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:$e(g),toolResults:y,touchedFiles:$e(b),iterations:_,success:!0,completedNaturally:C}}function $e(t){return[...new Set(t)]}function Lc(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?zt(e,jy):zt(e,Iy)}function Dc(t){return async(e,r)=>{let s=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm("Proceed with "+s+"?")?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+s)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function Nc(t){let{client:e,session:r,abortSignal:s,onStart:n,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",n?.();for await(let u of e.streamChat(r.getMessages(),s)){if(s?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,i?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(r.getMessages(),[],s)).message?.content||"",a&&i?.(a)),r.addAssistantMessage(a||""),o?.(),a}catch(u){if(l=u,u?.name==="AbortError"||s?.aborted)throw u;let p=de(u);if(p.fatal)throw new Error(p.message);if(c===1)throw new Error(p.message);await new Promise(h=>setTimeout(h,1e3))}throw l||new Error("Text turn failed")}function Ly(t){return["list_dir","read_file","search_codebase","get_file_info"].includes(t)?"Inspecting":["web_search"].includes(t)?"Researching":["scrape_url","extract_links","search_image_candidates","inspect_image"].includes(t)?"Fetching":["download_asset"].includes(t)?"Downloading":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing":["run_command","execute_code","detect_bugs"].includes(t)?"Running":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Git":"Working"}function Ve(t){process.stdout.write(t)}function Gr(t){process.stdout.write(t+`
309
- `)}async function Jr(t,e){let r=$c(t),s=await Et(e.workingDir,e.config);if(e.session.updateSystemPrompt(At(s,r.profile,e.workingDir)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete fully in one pass without follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:["kind:"+r.profile.kind]}),!r.profile.needsTools){let g=new Ke("Thinking");g.start();try{let y=await Nc({client:e.client,session:e.session,abortSignal:e.abortSignal,onStart:()=>{},onChunk:()=>{},onComplete:()=>{}});g.stop(),y?.trim()&&(Gr(ir()),Ve(or(y)+`
310
- `))}catch(y){g.stop();let b=de(y);Gr(Ae(b.message))}try{Jt().flush()}catch{}return}let n=Xt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Qt(3),o=!1,a=!1,l="",c=[],u=new Ke("Thinking"),d="",p=()=>{o=!1,a=!1,l=""},h={onModelStart:g=>{p(),u.stop(),u.start()},onModelStop:()=>{u.stop()},onStreamToken:g=>{g&&(l+=g,a=!0)},onAssistantText:async g=>{let y=(g||l||"").trim();p(),y&&(c.push(y),u.stop(),Ve(ir()+`
311
- `),Ve(or(y)+`
312
- `))},onToolStart:(g,y,b)=>{p(),u.stop();let w=Ly(g);w!==d&&(Ve(fi(w)+`
313
- `),d=w),Ve(di(g,y)+`
314
- `)},onToolEnd:(g,y,b,w)=>{Ve(pi(y,b,w)+`
315
- `)},onNotice:(g,y)=>{p();let b=y==="retry"?D("\u21BB "+g):D(g);Gr(b)},onError:g=>{p(),Gr(Ae(g))},onToolCall:()=>e.onToolCall?.()},f=Dc({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?g=>e.input.confirm(g):void 0,confirmDangerous:e.input?g=>e.input.confirmDangerous(g):void 0}),m=await Xn({abortSignal:e.abortSignal,identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:h,safetyPolicy:f,reactEngine:n,errorRecovery:i,skipTools:!1});if(p(),r.profile.kind==="implementation"&&m.toolsUsed.length===0){e.session.addUserMessage("SYSTEM: This was an implementation task. You must use workspace tools to create or modify files. Please proceed with tool use now.",{priority:"critical",tags:["system-correction"]});let g=[];await Xn({abortSignal:e.abortSignal,identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...h,onAssistantText:async b=>{b?.trim()&&g.push(b)}},safetyPolicy:f,reactEngine:Xt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Qt(3),skipTools:!1});let y=g[g.length-1];y?.trim()&&(Ve(`
316
- `+ir()+`
317
- `),Ve(or(y)+`
318
- `))}try{Jt().flush()}catch{}}var Qn=k(require("fs")),Uc=k(require("path")),Se=k(require("os")),qc=require("child_process");async function Yr(t){let e=[],r=process.version,s=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${r} (recommended)`:s>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let n=Uc.join(Se.homedir(),".hablas");if(e.push({name:"Config directory",status:Qn.existsSync(n)?"ok":"warn",message:Qn.existsSync(n)?n:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=Se.homedir();if(process.platform!=="win32"){let a=(0,qc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Se.platform()} ${Se.arch()} \u2014 ${Se.cpus().length} cores, ${Math.round(Se.totalmem()/1024/1024/1024)}GB RAM`}),e}function Xr(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",n="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let c=`${r[l.status]}${e[l.status]}${s}`,u=l.name.padEnd(18);i.push(` ${c} ${u}${n}${l.message}${s}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
319
- `)}async function Bc(t,e){let r=t.trim().split(/\s+/),s=r[0],n=r.slice(1);switch(s){case"/help":console.log(hi());return;case"/exit":case"/quit":return"quit";case"/about":console.log(gi());return;case"/version":console.log(yi());return;case"/clear":e.session.clear(),console.log(_e("Session cleared."));return;case"/history":{let i=parseInt(n[0]||"8",10),o=e.session.getHistory().slice(-i);if(!o.length){console.log(D("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l.padEnd(10)} ${a.content.replace(/\s+/g," ").slice(0,140)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(mi({model:e.client.getModel(),provider:rt(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(!n.length){console.log(D(`Current model: ${e.client.getModel()}`));return}let i=n.join(" ").trim(),o=[];try{o=await e.client.listModels()}catch{}if(o.length>0){let a=o.find(c=>c.toLowerCase()===i.toLowerCase());if(a){e.config.model=a,e.client.setModel(a),Ye(e.config),console.log(_e(`Model \u2192 ${a}`));return}let l=o.filter(c=>c.toLowerCase().includes(i.toLowerCase())).slice(0,5);console.log(se(`Model "${i}" not found in the available list.`)),l.length?(console.log(D("Did you mean one of these?")),l.forEach((c,u)=>console.log(` ${u+1}. ${c}`)),console.log(D(`Run /models ${i} to see the full list`))):console.log(D("Run /models to browse available models"));return}e.config.model=i,e.client.setModel(i),Ye(e.config),console.log(_e(`Model \u2192 ${i} (could not verify \u2014 offline)`));return}case"/models":{let i=[];try{i=await e.client.listModels()}catch{console.log(se("Could not fetch model list -- check your connection."));return}let o=20,a=1,l="";if(n.length){let g=n[n.length-1].toLowerCase(),y=parseInt(g,10),b=["next","n","prev","previous","p"];if(!Number.isNaN(y)&&y>0)a=y,l=n.slice(0,-1).join(" ").toLowerCase().trim();else if(b.includes(g)){console.log(D("Use page numbers to navigate: /models 2, /models 3")),console.log(D("Search by name: /models qwen"));return}else l=n.join(" ").toLowerCase().trim()}let c=l?i.filter(g=>g.toLowerCase().includes(l)):i;if(!c.length){console.log(se("No models matching: "+l)),console.log(D("Run /models to see all available models."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),p=(d-1)*o,h=c.slice(p,p+o),f=e.client.getModel(),m=l?"Models + query + ":"Models";if(console.log(""),console.log(D(m+" | page "+d+"/"+u+" | "+c.length+" found")),console.log(""),h.forEach((g,y)=>{let w=g===f?" <- active":"";console.log(" "+String(p+y+1).padStart(3)+". "+g+w)}),console.log(""),d<u){let g="/models"+(l?" "+l:"")+" "+(d+1);console.log(D(g+" -- next page"))}if(d>1){let g="/models"+(l?" "+l:"")+" "+(d-1);console.log(D(g+" -- prev page"))}console.log(D("Switch model: /model <name>")),console.log("");return}case"/provider":{let i=n[0];if(!i){console.log(D(`Provider: ${rt(e.config)}`)),console.log(D(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?_e("Connection OK"):Ae("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ce.apiUrl,n[1]&&(e.config.apiKey=n[1]),e.config.model||(e.config.model=ce.defaultModel);else if(i==="custom"){if(!n[1]){console.log(se("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=n[1],n[2]&&(e.config.apiKey=n[2])}else{console.log(se("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=gt(e.config);e.setClient(o),Ye(e.config),console.log(_e(`Provider \u2192 ${rt(e.config)}`));return}case"/doctor":{let i=await Yr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Xr(i));return}case"/workspace":{console.log(""),console.log(qr(Ct(e.workingDir))),console.log("");return}case"/memory":{if(n[0]==="clear"){e.accumulator&&e.accumulator.clear(),console.log(D("Long-context accumulator cleared (pinned entries kept)."));return}if(e.projectMemory){let o=e.projectMemory.getAll();console.log(""),console.log(_e(`Project Memory \xB7 ${o.length} entries \xB7 session #${e.projectMemory.sessionCount}`)),o.length||console.log(D(" No entries yet \u2014 Hablas learns as you work."));for(let a of o.slice(0,10))console.log(` [${a.kind.padEnd(10)}] ${a.title}`),a.files?.length&&console.log(` files: ${a.files.slice(0,3).join(", ")}`)}if(e.accumulator){let o=e.accumulator.getAll();if(o.length){console.log(""),console.log(_e(`Reasoning Accumulator \xB7 ${o.length} observations \xB7 turn #${e.accumulator.turnIndex}`));for(let a of o.slice(0,8)){let l=a.pinned?"\u{1F4CC} ":"";console.log(` ${l}[T${a.turnIndex}][${a.kind}] ${a.text.slice(0,70)}`)}}}console.log("");return}case"/diff":{let{exec:i}=await import("child_process"),o=n[0]||"",a=`git diff ${o?'"'+o+'"':""}`,l=await new Promise(c=>{i(a,{cwd:e.workingDir,maxBuffer:2*1024*1024},(u,d,p)=>{c(d||p||"No changes.")})});if(console.log(""),l.trim()){let c=l.split(`
308
+ `)}},Yn=null;function Mc(){return Yn||(Yn=new Qn),Yn}var Gr=class t{buf="";inThink=!1;visibleEmitted=!1;onToken;static THINK_OPENS=["<thinking>","<think>"];static THINK_CLOSES=["</thinking>","</think>"];static PARTIAL_SCAN=12;constructor(e){this.onToken=e}push(e){this.buf+=e,this.flush_process()}flush(){if(this.inThink){this.buf="",this.inThink=!1;return}if(this.buf.trim()){let e=this.buf.replace(/<\/?think(?:ing)?>/gi,"").trim();e&&this.emit(e)}this.buf=""}get hasVisibleContent(){return this.visibleEmitted}flush_process(){for(;this.buf.length>0;){if(this.inThink){let s=this.findFirst(t.THINK_CLOSES);if(s===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let n=this.buf.indexOf(">",s)+1;this.buf=this.buf.slice(n),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let s=this.longestPartialTail();if(s>0){let n=this.buf.slice(0,this.buf.length-s);n&&this.emit(n),this.buf=this.buf.slice(this.buf.length-s);return}this.emit(this.buf),this.buf="";return}if(e>0){this.emit(this.buf.slice(0,e)),this.buf=this.buf.slice(e);continue}this.inThink=!0;let r=this.buf.indexOf(">")+1;this.buf=this.buf.slice(r>0?r:this.buf.length)}}findFirst(e){let r=-1,s=this.buf.toLowerCase();for(let n of e){let i=s.indexOf(n.toLowerCase());i!==-1&&(r===-1||i<r)&&(r=i)}return r}longestPartialTail(){let e=t.PARTIAL_SCAN,r=this.buf.slice(-e).toLowerCase(),s=0;for(let n of t.THINK_OPENS){let i=n.toLowerCase();for(let o=Math.min(i.length-1,r.length);o>0;o--)if(i.startsWith(r.slice(-o))){s=Math.max(s,o);break}}return s}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var jy=600,Py=4e3,My=16e3,Fc=2;function Fy(t,e,r){let n=Mc().parse(e,t,r);return{toolCalls:n.toolCalls,displayContent:n.displayContent}}function Ly(t,e){return t==="write_file"&&typeof e.path=="string"?"create "+e.path:["edit_file","patch_file","search_and_replace"].includes(t)&&typeof e.path=="string"?"modify "+e.path:t==="read_file"&&typeof e.path=="string"?"read "+e.path:t==="run_command"&&typeof e.command=="string"?String(e.command).slice(0,80):t==="remember"&&typeof e.key=="string"?"remember: "+String(e.key).slice(0,60):t==="recall"&&typeof e.key=="string"?"recall: "+String(e.key).slice(0,60):t==="search_memory"&&typeof e.query=="string"?'search memory: "'+String(e.query).slice(0,50)+'"':t==="forget"&&typeof e.key=="string"?"forget: "+String(e.key).slice(0,60):t==="memory_stats"?"check memory stats":t==="git_status"?"check git status":t==="git_diff"&&typeof e.path=="string"?"diff "+e.path:t==="git_diff"?"diff working tree":t==="git_log"&&typeof e.path=="string"?"log "+e.path:t==="git_log"?"recent commits":t==="git_branch"?"list branches":typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function Dy(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function Lc(t,e,r,s){let n=0,i=Date.now();for(;n<=Fc;){let o=await t.execute({name:e,arguments:r});if(o.success||n>=Fc)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:n};n++,s.info({tool:e,retry:n,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:n}}async function Zn(t){let{identity:e,client:r,registry:s,session:n,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:c,skipTools:u}=t,d=t.reactEngine??Qt(),p=t.errorRecovery??Zt(),h=u?[]:s.getOllamaTools(),f=r.getModel(),m=t.maxIterations??jy,g=[],y=[],b=[],w=new Map,S="",_=0,C=!1;for(;_<m;){if(_++,c?.aborted)return{output:S,toolsUsed:Ae(g),toolResults:y,touchedFiles:Ae(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let E=d.buildBudgetWarningPrompt();E&&n.addUserMessage(E,{priority:"critical",tags:["system-budget"]});let A;try{if(a.onModelStart?.(y.length>0?"Deciding next step":"Thinking",e),r.streamChatWithTools){let K=!1,te=new Gr(ye=>{K||(a.onModelStop?.(),K=!0),a.onStreamToken?.(ye,e)}),I=r.streamChatWithTools(n.getMessages(),h,ye=>{te.push(ye)},c),F=await I.next();for(;!F.done;)F=await I.next();te.flush(),A=F.value,K||a.onModelStop?.()}else A=await r.chatWithTools(n.getMessages(),h,c),a.onModelStop?.()}catch(K){a.onModelStop?.();let te=K;if(te.name==="AbortError"||c?.aborted)return{output:S,toolsUsed:Ae(g),toolResults:y,touchedFiles:Ae(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){let F=de(te),ye=/rate.?limit|429|cooldown/i.test(te?.message||""),It=ye?2e4:2e3,ts=ye?`API provider rate limit \u2014 waiting ${It/1e3}s before retry...`:"Transient error: "+F.message+" \u2014 retrying...";a.onNotice?.(ts,"retry"),await new Promise(ze=>setTimeout(ze,It)),_--;continue}let I=de(te);return I.fatal?(a.onError?.(I.message),{output:S,toolsUsed:Ae(g),toolResults:y,touchedFiles:Ae(b),iterations:_,success:!1,error:I.message,completedNaturally:C}):(a.onError?.(I.message),{output:S,toolsUsed:Ae(g),toolResults:y,touchedFiles:Ae(b),iterations:_,success:!1,error:I.message,completedNaturally:C})}if(!A||!A.message){a.onNotice?.("Model returned an empty response \u2014 retrying...","retry"),await new Promise(K=>setTimeout(K,1500));continue}let $=A.message?.content||"",M=A.message?.tool_calls,U=d.parseThinking($);U.hasThinking&&(d.recordStep({thought:U.thinking}),o.debug({thinking:U.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:H}=Fy(M,$,f);if(H&&H.trim()&&(S=H,await a.onAssistantText?.(H,e)),N.length===0){n.addAssistantMessage($,void 0,e.role),C=!0;break}n.addAssistantMessage($,N,e.role);let Q=N.length;for(let K=0;K<Q;K++){let te=N[K];if(!te?.function?.name)continue;let I=te.function.name,F=te.function.arguments||{},ye=s.getSafetyLevel(I)??"confirm";if(!s.get(I)){a.onNotice?.("Unknown tool: "+I+" \u2014 skipping","warn"),n.addToolMessage('Error: Unknown tool "'+I+'". Available: '+s.getAll().map(Z=>Z.name).join(", "));continue}if(await l(I,ye,F)==="skip"){n.addToolMessage("Tool "+I+" was skipped by policy/user.");break}let ts=Ly(I,F),ze=I==="read_file"?JSON.stringify({path:F.path||"",start:F.start_line||"",end:F.end_line||""}):"";if(I==="read_file"&&ze&&w.has(ze)){let Z=w.get(ze)||"";n.addToolMessage(Z),d.recordObservation(Z.slice(0,300),"Reused cached file read");continue}g.push(I),typeof F.path=="string"&&b.push(F.path),typeof F.from=="string"&&b.push(F.from),typeof F.to=="string"&&b.push(F.to),a.onToolStart?.(I,ts,F),a.onToolCall?.(),d.recordStep({thought:U.hasThinking?"Executing: "+I:"",action:I,actionInput:F});let J=await Lc(s,I,F,o);a.onToolEnd?.(I,J.success,J.error||J.output,J.duration,F);let Ke;if(J.success)Ke=Dc(I,J.output),d.recordObservation(Ke.slice(0,300)),y.push({tool:I,success:!0,summary:J.output.slice(0,150)});else{let Z=J.error||"Unknown error",lt=p.analyze(I,Z,F);if(Ke=p.buildRecoveryMessage(lt,Z),d.recordObservation("FAILED: "+Z,"Recovery: "+lt.strategy+" \u2014 "+lt.suggestion),o.info({tool:I,errorClass:lt.errorClass,strategy:lt.strategy},"Error recovery analysis"),y.push({tool:I,success:!1,summary:Z.slice(0,150)}),lt.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let ct=await Lc(s,I,F,o);a.onToolEnd?.(I,ct.success,ct.output,ct.duration,F),ct.success&&(Ke=Dc(I,ct.output),d.recordObservation(Ke.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:I,success:!0,summary:ct.output.slice(0,150)})}}if(n.addToolMessage(Ke),J.success&&I==="read_file"&&typeof F.path=="string"&&(i?.addFile(F.path,J.output),ze&&w.set(ze,Ke)),J.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(I)&&typeof F.path=="string")for(let Z of[...w.keys()])Z.includes('"path":"'+String(F.path).replace(/"/g,'\\"')+'"')&&w.delete(Z);if(J.success&&I==="move_file")for(let Z of[...w.keys()])(F.from&&Z.includes('"path":"'+String(F.from).replace(/"/g,'\\"')+'"')||F.to&&Z.includes('"path":"'+String(F.to).replace(/"/g,'\\"')+'"'))&&w.delete(Z);if(o.info({tool:I,success:J.success,durationMs:J.duration,retries:J.retries},"Tool executed"),!J.success&&Dy(J.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}}d.isOverBudget()&&a.onNotice?.("Reached max reasoning steps ("+d.getConfig().maxSteps+"). Wrapping up.","warn")}return _>=m&&!C&&a.onNotice?.("Reached max iterations ("+m+"). Stopping.","warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:Ae(g),toolResults:y,touchedFiles:Ae(b),iterations:_,success:!0,completedNaturally:C}}function Ae(t){return[...new Set(t)]}function Dc(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?Kt(e,My):Kt(e,Py)}function Nc(t){return async(e,r)=>{let s=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm("Proceed with "+s+"?")?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+s)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function Uc(t){let{client:e,session:r,abortSignal:s,onStart:n,onChunk:i,onComplete:o}=t,a="",l=null;for(let c=0;c<2;c++)try{a="",n?.();for await(let u of e.streamChat(r.getMessages(),s)){if(s?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,i?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(r.getMessages(),[],s)).message?.content||"",a&&i?.(a)),r.addAssistantMessage(a||""),o?.(),a}catch(u){if(l=u,u?.name==="AbortError"||s?.aborted)throw u;let p=de(u);if(p.fatal)throw new Error(p.message);if(c===1)throw new Error(p.message);await new Promise(h=>setTimeout(h,1e3))}throw l||new Error("Text turn failed")}function Ny(t){return["list_dir","read_file","search_codebase","get_file_info"].includes(t)?"Inspecting":["web_search"].includes(t)?"Researching":["scrape_url","extract_links","search_image_candidates","inspect_image"].includes(t)?"Fetching":["download_asset"].includes(t)?"Downloading":["write_file","patch_file","edit_file","search_and_replace","append_to_file","move_file","create_dir","delete_file"].includes(t)?"Editing":["run_command","execute_code","detect_bugs"].includes(t)?"Running":["remember","recall","search_memory","forget","memory_stats"].includes(t)?"Memory":["git_status","git_diff","git_log","git_branch"].includes(t)?"Git":"Working"}function Ve(t){process.stdout.write(t)}function Jr(t){process.stdout.write(t+`
309
+ `)}async function Xr(t,e){let r=Ac(t),s=await Et(e.workingDir,e.config);if(e.session.updateSystemPrompt(Ot(s,r.profile,e.workingDir)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete fully in one pass without follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:["kind:"+r.profile.kind]}),!r.profile.needsTools){let g=new Ge("Thinking");g.start();try{let y=await Uc({client:e.client,session:e.session,abortSignal:e.abortSignal,onStart:()=>{},onChunk:()=>{},onComplete:()=>{}});g.stop(),y?.trim()&&(Jr(or()),Ve(ar(y)+`
310
+ `))}catch(y){g.stop();let b=de(y);Jr(Oe(b.message))}try{Xt().flush()}catch{}return}let n=Qt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=Zt(3),o=!1,a=!1,l="",c=[],u=new Ge("Thinking"),d="",p=()=>{o=!1,a=!1,l=""},h={onModelStart:g=>{p(),u.stop(),u.start()},onModelStop:()=>{u.stop()},onStreamToken:g=>{g&&(l+=g,a=!0)},onAssistantText:async g=>{let y=(g||l||"").trim();p(),y&&(c.push(y),u.stop(),Ve(or()+`
311
+ `),Ve(ar(y)+`
312
+ `))},onToolStart:(g,y,b)=>{p(),u.stop();let w=Ny(g);w!==d&&(Ve(di(w)+`
313
+ `),d=w),Ve(pi(g,y)+`
314
+ `)},onToolEnd:(g,y,b,w)=>{Ve(hi(y,b,w)+`
315
+ `)},onNotice:(g,y)=>{p();let b=y==="retry"?D("\u21BB "+g):D(g);Jr(b)},onError:g=>{p(),Jr(Oe(g))},onToolCall:()=>e.onToolCall?.()},f=Nc({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?g=>e.input.confirm(g):void 0,confirmDangerous:e.input?g=>e.input.confirmDangerous(g):void 0}),m=await Zn({abortSignal:e.abortSignal,identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:h,safetyPolicy:f,reactEngine:n,errorRecovery:i,skipTools:!1});if(p(),r.profile.kind==="implementation"&&m.toolsUsed.length===0){e.session.addUserMessage("SYSTEM: This was an implementation task. You must use workspace tools to create or modify files. Please proceed with tool use now.",{priority:"critical",tags:["system-correction"]});let g=[];await Zn({abortSignal:e.abortSignal,identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...h,onAssistantText:async b=>{b?.trim()&&g.push(b)}},safetyPolicy:f,reactEngine:Qt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:Zt(3),skipTools:!1});let y=g[g.length-1];y?.trim()&&(Ve(`
316
+ `+or()+`
317
+ `),Ve(ar(y)+`
318
+ `))}try{Xt().flush()}catch{}}var ei=k(require("fs")),qc=k(require("path")),ve=k(require("os")),Bc=require("child_process");async function Yr(t){let e=[],r=process.version,s=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:s>=20?"ok":s>=18?"warn":"error",message:s>=20?`${r} (recommended)`:s>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let n=qc.join(ve.homedir(),".hablas");if(e.push({name:"Config directory",status:ei.existsSync(n)?"ok":"warn",message:ei.existsSync(n)?n:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=ve.homedir();if(process.platform!=="win32"){let a=(0,Bc.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",c=a[4]||"?";e.push({name:"Disk space",status:parseInt(c)>90?"warn":"ok",message:`${l} available (${c} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${ve.platform()} ${ve.arch()} \u2014 ${ve.cpus().length} cores, ${Math.round(ve.totalmem()/1024/1024/1024)}GB RAM`}),e}function Qr(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},s="\x1B[0m",n="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let c=`${r[l.status]}${e[l.status]}${s}`,u=l.name.padEnd(18);i.push(` ${c} ${u}${n}${l.message}${s}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${s}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${s}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${s}`),i.push(""),i.join(`
319
+ `)}async function Hc(t,e){let r=t.trim().split(/\s+/),s=r[0],n=r.slice(1);switch(s){case"/help":console.log(mi());return;case"/exit":case"/quit":return"quit";case"/about":console.log(yi());return;case"/version":console.log(wi());return;case"/clear":e.session.clear(),console.log(ke("Session cleared."));return;case"/history":{let i=parseInt(n[0]||"8",10),o=e.session.getHistory().slice(-i);if(!o.length){console.log(D("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l.padEnd(10)} ${a.content.replace(/\s+/g," ").slice(0,140)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(gi({model:e.client.getModel(),provider:st(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(!n.length){console.log(D(`Current model: ${e.client.getModel()}`));return}let i=n.join(" ").trim(),o=[];try{o=await e.client.listModels()}catch{}if(o.length>0){let a=o.find(c=>c.toLowerCase()===i.toLowerCase());if(a){e.config.model=a,e.client.setModel(a),Ye(e.config),console.log(ke(`Model \u2192 ${a}`));return}let l=o.filter(c=>c.toLowerCase().includes(i.toLowerCase())).slice(0,5);console.log(se(`Model "${i}" not found in the available list.`)),l.length?(console.log(D("Did you mean one of these?")),l.forEach((c,u)=>console.log(` ${u+1}. ${c}`)),console.log(D(`Run /models ${i} to see the full list`))):console.log(D("Run /models to browse available models"));return}e.config.model=i,e.client.setModel(i),Ye(e.config),console.log(ke(`Model \u2192 ${i} (could not verify \u2014 offline)`));return}case"/models":{let i=[];try{i=await e.client.listModels()}catch{console.log(se("Could not fetch model list -- check your connection."));return}let o=20,a=1,l="";if(n.length){let g=n[n.length-1].toLowerCase(),y=parseInt(g,10),b=["next","n","prev","previous","p"];if(!Number.isNaN(y)&&y>0)a=y,l=n.slice(0,-1).join(" ").toLowerCase().trim();else if(b.includes(g)){console.log(D("Use page numbers to navigate: /models 2, /models 3")),console.log(D("Search by name: /models qwen"));return}else l=n.join(" ").toLowerCase().trim()}let c=l?i.filter(g=>g.toLowerCase().includes(l)):i;if(!c.length){console.log(se("No models matching: "+l)),console.log(D("Run /models to see all available models."));return}let u=Math.max(1,Math.ceil(c.length/o)),d=Math.min(Math.max(a,1),u),p=(d-1)*o,h=c.slice(p,p+o),f=e.client.getModel(),m=l?"Models + query + ":"Models";if(console.log(""),console.log(D(m+" | page "+d+"/"+u+" | "+c.length+" found")),console.log(""),h.forEach((g,y)=>{let w=g===f?" <- active":"";console.log(" "+String(p+y+1).padStart(3)+". "+g+w)}),console.log(""),d<u){let g="/models"+(l?" "+l:"")+" "+(d+1);console.log(D(g+" -- next page"))}if(d>1){let g="/models"+(l?" "+l:"")+" "+(d-1);console.log(D(g+" -- prev page"))}console.log(D("Switch model: /model <name>")),console.log("");return}case"/provider":{let i=n[0];if(!i){console.log(D(`Provider: ${st(e.config)}`)),console.log(D(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?ke("Connection OK"):Oe("Connection failed"));return}if(i==="ollama")e.config.provider="ollama",e.config.apiUrl="",e.config.apiKey="";else if(i==="nvidia")e.config.provider="nvidia",e.config.apiUrl=ce.apiUrl,n[1]&&(e.config.apiKey=n[1]),e.config.model||(e.config.model=ce.defaultModel);else if(i==="custom"){if(!n[1]){console.log(se("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=n[1],n[2]&&(e.config.apiKey=n[2])}else{console.log(se("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=yt(e.config);e.setClient(o),Ye(e.config),console.log(ke(`Provider \u2192 ${st(e.config)}`));return}case"/doctor":{let i=await Yr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(Qr(i));return}case"/workspace":{console.log(""),console.log(Br($t(e.workingDir))),console.log("");return}case"/memory":{if(n[0]==="clear"){e.accumulator&&e.accumulator.clear(),console.log(D("Long-context accumulator cleared (pinned entries kept)."));return}if(e.projectMemory){let o=e.projectMemory.getAll();console.log(""),console.log(ke(`Project Memory \xB7 ${o.length} entries \xB7 session #${e.projectMemory.sessionCount}`)),o.length||console.log(D(" No entries yet \u2014 Hablas learns as you work."));for(let a of o.slice(0,10))console.log(` [${a.kind.padEnd(10)}] ${a.title}`),a.files?.length&&console.log(` files: ${a.files.slice(0,3).join(", ")}`)}if(e.accumulator){let o=e.accumulator.getAll();if(o.length){console.log(""),console.log(ke(`Reasoning Accumulator \xB7 ${o.length} observations \xB7 turn #${e.accumulator.turnIndex}`));for(let a of o.slice(0,8)){let l=a.pinned?"\u{1F4CC} ":"";console.log(` ${l}[T${a.turnIndex}][${a.kind}] ${a.text.slice(0,70)}`)}}}console.log("");return}case"/diff":{let{exec:i}=await import("child_process"),o=n[0]||"",a=`git diff ${o?'"'+o+'"':""}`,l=await new Promise(c=>{i(a,{cwd:e.workingDir,maxBuffer:2*1024*1024},(u,d,p)=>{c(d||p||"No changes.")})});if(console.log(""),l.trim()){let c=l.split(`
320
320
  `);for(let u of c.slice(0,100))u.startsWith("+")&&!u.startsWith("+++")?process.stdout.write(`\x1B[38;5;71m${u}\x1B[0m
321
321
  `):u.startsWith("-")&&!u.startsWith("---")?process.stdout.write(`\x1B[38;5;131m${u}\x1B[0m
322
322
  `):u.startsWith("@@")?process.stdout.write(`\x1B[38;5;110m${u}\x1B[0m
323
- `):console.log(u);c.length>100&&console.log(D(`... ${c.length-100} more lines`))}else console.log(D("No changes to show."));console.log("");return}case"/checkpoint":{let i=n[0];if(!i||i==="list")console.log(D("Checkpoints: use the agent to manage checkpoints.")),console.log(D(' Tell Hablas: "save checkpoint before-refactor" or "list checkpoints"'));else if(i==="save"){let o=n[1]||"manual";console.log(D(`Telling Hablas to save checkpoint "${o}"...`)),e.session.addUserMessage(`checkpoint_save now, name="${o}", description="manual checkpoint from /checkpoint command"`,{priority:"critical",tags:["checkpoint","system-cmd"]}),console.log(D("Checkpoint request queued \u2014 continue typing to trigger it."))}return}case"/tests":{console.log(D('Running tests... tell Hablas: "run tests" for full output.'));return}case"/git":{let i=n[0];if(!i||i==="status"){let{exec:o}=await import("child_process"),a=await new Promise(l=>{o("git status --short --branch",{cwd:e.workingDir},(c,u)=>l(u))});console.log(""),console.log(a||"Not a git repo."),console.log("")}else if(i==="log"){let{exec:o}=await import("child_process"),a=await new Promise(l=>{o("git log --oneline -15",{cwd:e.workingDir},(c,u)=>l(u))});console.log(""),console.log(a||"No commits."),console.log("")}else console.log(se("Usage: /git [status|log]"));return}default:console.log(se(`Unknown command: ${s} \xB7 /help for reference`))}}var Me=k(require("fs")),Zn=k(require("path"));function ei(t){let e=Zn.join(t,".hablas");return Me.existsSync(e)||Me.mkdirSync(e,{recursive:!0}),e}function Hc(t){return Zn.join(ei(t),"session.json")}function Qr(t,e){let r=Hc(t);try{return Me.existsSync(r)?(e.fromJSON(Me.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function er(t,e){let r=Hc(t);try{Me.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function zc(t,e){Li();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,s=gt(t);ei(r);let n=new vt(r,t),i=new _t(t),o=await Et(r,t),a=new Tt(At(o,Yt("hello")),t.historySize,t.contextBudget);Qr(r,a);let l=new Wr(r);console.log(ci(t.model,r));let c=new Ke("Connecting");c.start();let u=await s.checkConnection();if(c.stop(),u){let y=await s.listModels();console.log(_e(`${rt(t)} \xB7 ${y.length} models available`))}else console.log(se(`offline \xB7 ${rt(t)} \xB7 file inspection still works \xB7 /provider to switch`));Wc.existsSync(Vc.join(r,".git"))||console.log(D("no git repository detected \u2014 standalone workspace mode")),console.log("");let d=0,p=0,h=Date.now(),f=0,m=null,g=null;for(bi({stop:()=>g?.stop()}),process.on("SIGINT",()=>{let y=Date.now();if(g?.stop(),g=null,m&&!m.signal.aborted){m.abort(),process.stdout.write(`
323
+ `):console.log(u);c.length>100&&console.log(D(`... ${c.length-100} more lines`))}else console.log(D("No changes to show."));console.log("");return}case"/checkpoint":{let i=n[0];if(!i||i==="list")console.log(D("Checkpoints: use the agent to manage checkpoints.")),console.log(D(' Tell Hablas: "save checkpoint before-refactor" or "list checkpoints"'));else if(i==="save"){let o=n[1]||"manual";console.log(D(`Telling Hablas to save checkpoint "${o}"...`)),e.session.addUserMessage(`checkpoint_save now, name="${o}", description="manual checkpoint from /checkpoint command"`,{priority:"critical",tags:["checkpoint","system-cmd"]}),console.log(D("Checkpoint request queued \u2014 continue typing to trigger it."))}return}case"/tests":{console.log(D('Running tests... tell Hablas: "run tests" for full output.'));return}case"/git":{let i=n[0];if(!i||i==="status"){let{exec:o}=await import("child_process"),a=await new Promise(l=>{o("git status --short --branch",{cwd:e.workingDir},(c,u)=>l(u))});console.log(""),console.log(a||"Not a git repo."),console.log("")}else if(i==="log"){let{exec:o}=await import("child_process"),a=await new Promise(l=>{o("git log --oneline -15",{cwd:e.workingDir},(c,u)=>l(u))});console.log(""),console.log(a||"No commits."),console.log("")}else console.log(se("Usage: /git [status|log]"));return}default:console.log(se(`Unknown command: ${s} \xB7 /help for reference`))}}var Fe=k(require("fs")),ti=k(require("path"));function ri(t){let e=ti.join(t,".hablas");return Fe.existsSync(e)||Fe.mkdirSync(e,{recursive:!0}),e}function Wc(t){return ti.join(ri(t),"session.json")}function Zr(t,e){let r=Wc(t);try{return Fe.existsSync(r)?(e.fromJSON(Fe.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function tr(t,e){let r=Wc(t);try{Fe.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}async function Kc(t,e){Di();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,s=yt(t);ri(r);let n=new _t(r,t),i=new kt(t),o=await Et(r,t),a=new Ct(Ot(o,Yt("hello")),t.historySize,t.contextBudget);Zr(r,a);let l=new Vr(r);console.log(ui(t.model,r));let c=new Ge("Connecting");c.start();let u=await s.checkConnection();if(c.stop(),u){let y=await s.listModels();console.log(ke(`${st(t)} \xB7 ${y.length} models available`))}else console.log(se(`offline \xB7 ${st(t)} \xB7 file inspection still works \xB7 /provider to switch`));Vc.existsSync(zc.join(r,".git"))||console.log(D("no git repository detected \u2014 standalone workspace mode")),console.log("");let d=0,p=0,h=Date.now(),f=0,m=null,g=null;for(xi({stop:()=>g?.stop()}),process.on("SIGINT",()=>{let y=Date.now();if(g?.stop(),g=null,m&&!m.signal.aborted){m.abort(),process.stdout.write(`
324
324
  `),console.log(se("\u2298 turn cancelled")),f=y;return}if(y-f<2e3){process.stdout.write(`
325
325
  `);let b=Math.round((Date.now()-h)/1e3);console.log(D(`session ended \xB7 turns=${d} \xB7 tool calls=${p} \xB7 ${b}s`)),l.close(),process.exit(0)}f=y,process.stdout.write(`
326
- `),console.log(se("Ctrl+C again to exit"))});;){let b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){let w=await Bc(b,{config:t,client:s,setClient:S=>{s=S},session:a,workingDir:r});if(er(r,a),w==="quit")break;continue}d++,console.log(ui(d)),m=new AbortController;try{await Jr(b,{config:t,client:s,registry:n,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,abortSignal:m.signal,onToolCall:()=>{p++}}),er(r,a)}catch(w){let S=w;S?.name==="AbortError"||m.signal.aborted||(console.log(Ae(S?.message||"Turn failed")),e.error(w,"interactive turn failed"))}finally{m=null}}}l.close()}async function Kc(t,e,r){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,n=gt(e),i=new vt(s,e),o=new _t(e),a=await Et(s,e),l=new Tt(At(a,Yt(t)),e.historySize,e.contextBudget);Qr(s,l),await Jr(t,{config:e,client:n,registry:i,contextManager:o,session:l,workingDir:s,logger:r,interactive:!1}),er(s,l)}var Zr=k(require("fs")),ot=k(require("path")),Dy=[{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"}],Ny=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"]);function qy(t,e){let r=[],s=e.split(`
327
- `);for(let{pattern:n,name:i,severity:o}of Dy){n.lastIndex=0;let a;for(;(a=n.exec(e))!==null;){let c=e.substring(0,a.index).split(`
328
- `).length,u=s[c-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function By(t,e){let r=[],s=e.split(`
329
- `),n=ot.extname(t);return[".ts",".js",".tsx",".jsx"].includes(n)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function Gc(t,e=[]){try{let r=Zr.readdirSync(t,{withFileTypes:!0});for(let s of r){if(Ny.has(s.name))continue;let n=ot.join(t,s.name);if(s.isDirectory())Gc(n,e);else if(s.isFile()){let i=ot.extname(s.name);Uy.has(i)||e.push(n)}}}catch{}return e}function Jc(t){let e=Date.now(),r=Gc(t),s=[];for(let o of r)try{let a=Zr.readFileSync(o,"utf-8"),l=ot.relative(t,o),c=qy(l,a);s.push(...c);let u=By(l,a);s.push(...u)}catch{}let n=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:r.length,duration:n,summary:i}}function Yc(t){let e=[];if(e.push(`
326
+ `),console.log(se("Ctrl+C again to exit"))});;){let b=(await l.prompt(" \u203A ")).trim();if(b){if(b.startsWith("/")){let w=await Hc(b,{config:t,client:s,setClient:S=>{s=S},session:a,workingDir:r});if(tr(r,a),w==="quit")break;continue}d++,console.log(fi(d)),m=new AbortController;try{await Xr(b,{config:t,client:s,registry:n,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,abortSignal:m.signal,onToolCall:()=>{p++}}),tr(r,a)}catch(w){let S=w;S?.name==="AbortError"||m.signal.aborted||(console.log(Oe(S?.message||"Turn failed")),e.error(w,"interactive turn failed"))}finally{m=null}}}l.close()}async function Gc(t,e,r){let s=e.workingDirectory==="."?process.cwd():e.workingDirectory,n=yt(e),i=new _t(s,e),o=new kt(e),a=await Et(s,e),l=new Ct(Ot(a,Yt(t)),e.historySize,e.contextBudget);Zr(s,l),await Xr(t,{config:e,client:n,registry:i,contextManager:o,session:l,workingDir:s,logger:r,interactive:!1}),tr(s,l)}var es=k(require("fs")),at=k(require("path")),Uy=[{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"}],qy=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),By=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function Hy(t,e){let r=[],s=e.split(`
327
+ `);for(let{pattern:n,name:i,severity:o}of Uy){n.lastIndex=0;let a;for(;(a=n.exec(e))!==null;){let c=e.substring(0,a.index).split(`
328
+ `).length,u=s[c-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:c,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function Wy(t,e){let r=[],s=e.split(`
329
+ `),n=at.extname(t);return[".ts",".js",".tsx",".jsx"].includes(n)&&s.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function Jc(t,e=[]){try{let r=es.readdirSync(t,{withFileTypes:!0});for(let s of r){if(qy.has(s.name))continue;let n=at.join(t,s.name);if(s.isDirectory())Jc(n,e);else if(s.isFile()){let i=at.extname(s.name);By.has(i)||e.push(n)}}}catch{}return e}function Xc(t){let e=Date.now(),r=Jc(t),s=[];for(let o of r)try{let a=es.readFileSync(o,"utf-8"),l=at.relative(t,o),c=Hy(l,a);s.push(...c);let u=Wy(l,a);s.push(...u)}catch{}let n=Date.now()-e,i={critical:s.filter(o=>o.severity==="critical").length,high:s.filter(o=>o.severity==="high").length,medium:s.filter(o=>o.severity==="medium").length,low:s.filter(o=>o.severity==="low").length,info:s.filter(o=>o.severity==="info").length};return{issues:s,scannedFiles:r.length,duration:n,summary:i}}function Yc(t){let e=[];if(e.push(`
330
330
  Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((s,n)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[s.severity]-i[n.severity]}).slice(0,10);for(let s of r){let n=s.severity==="critical"?"\u{1F534}":s.severity==="high"?"\u{1F7E0}":s.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${n} [${s.severity.toUpperCase()}] ${s.message}`),e.push(` File: ${s.file}${s.line?`:${s.line}`:""}`),e.push(` Fix: ${s.suggestion}`),e.push("")}}return e.join(`
331
- `)}var Ot=k(require("fs")),ti=k(require("path")),Qc=k(require("os")),Hy=ti.join(Qc.homedir(),".hablas"),Xc=ti.join(Hy,"analytics.json");function Zc(){try{if(Ot.existsSync(Xc))return JSON.parse(Ot.readFileSync(Xc,"utf-8"))}catch{}return Wy()}function Wy(){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 eu(t){let e=[];e.push(`
331
+ `)}var Rt=k(require("fs")),si=k(require("path")),Zc=k(require("os")),Vy=si.join(Zc.homedir(),".hablas"),Qc=si.join(Vy,"analytics.json");function eu(){try{if(Rt.existsSync(Qc))return JSON.parse(Rt.readFileSync(Qc,"utf-8"))}catch{}return zy()}function zy(){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 tu(t){let e=[];e.push(`
332
332
  \u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((n,i)=>i[1]-n[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[n,i]of r)e.push(` @${n}: ${i} uses`);e.push("")}let s=Object.entries(t.commandUsage).sort((n,i)=>i[1]-n[1]).slice(0,5);if(s.length>0){e.push(" Top Commands:");for(let[n,i]of s)e.push(` ${n}: ${i} calls`)}return e.join(`
333
- `)}var tu=k(require("readline"));var X="\x1B[36m",tr="\x1B[32m",Ee="\x1B[33m",j="\x1B[2m",Fe="\x1B[1m",T="\x1B[0m",Vy="\x1B[35m";function z(t,e){return new Promise(r=>t.question(e,s=>r(s)))}function zy(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var rr={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function ru(t){let e=tu.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Fe}${X} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(`${Fe}${X} hablas \u2014 Setup Wizard${T}`),console.log(`${j} Configure your AI provider and model${T}`),console.log(`${Fe}${X} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(),console.log(`${Fe} Choose your setup:${T}`),console.log(),console.log(` ${Vy}${Fe}1${T}. ${Fe}Hablas Integrated Engine${T} ${tr}(instant \u2014 no setup needed)${T}`),console.log(` ${j}Pre-configured cloud AI, ready to use immediately${T}`),console.log(),console.log(` ${X}${Fe}2${T}. ${Fe}Custom Provider${T} ${j}(bring your own API key)${T}`),console.log(` ${j}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${T}`),console.log(),(await z(e,` ${j}Your choice (1-2):${T} `)).trim()){case"1":{t.provider=rr.provider,t.apiUrl=rr.apiUrl,t.apiKey=zy(),t.model=rr.model,Ye(t),console.log(),console.log(`${tr} \u2713 Hablas Integrated Engine activated!${T}`),console.log(`${j} Model: ${rr.model}${T}`),console.log(`${j} API: ${rr.apiUrl}${T}`),console.log(`${j} No API key needed \u2014 everything is pre-configured.${T}`);break}case"2":{switch(console.log(),console.log(`${j} Select your provider:${T}`),console.log(` ${X}a${T}. Ollama (local, free, private)`),console.log(` ${X}b${T}. OpenAI API`),console.log(` ${X}c${T}. Groq (fast, free tier)`),console.log(` ${X}d${T}. OpenRouter (many models)`),console.log(` ${X}e${T}. Together AI`),console.log(` ${X}f${T}. DeepSeek`),console.log(` ${X}g${T}. Custom OpenAI-compatible API`),console.log(` ${X}h${T}. NVIDIA NIM (powerful cloud models)`),console.log(` ${X}i${T}. Mistral AI ${tr}(free tier available)${T}`),console.log(),(await z(e,` ${j}Your choice (a-h):${T} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let n=(await z(e,` ${j}Ollama host [http://localhost:11434]:${T} `)).trim(),i=(await z(e,` ${j}Model [qwen2.5-coder:7b]:${T} `)).trim();t.ollamaHost=n||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let n=(await z(e,` ${j}OpenAI API Key (sk-...):${T} `)).trim(),i=(await z(e,` ${j}Model [gpt-4o]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=n,t.model=i||"gpt-4o";break}case"c":{let n=(await z(e,` ${j}Groq API Key (gsk_...):${T} `)).trim(),i=(await z(e,` ${j}Model [llama-3.3-70b-versatile]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=n,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let n=(await z(e,` ${j}OpenRouter API Key (sk-or-...):${T} `)).trim(),i=(await z(e,` ${j}Model [anthropic/claude-3.5-sonnet]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=n,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let n=(await z(e,` ${j}Together API Key:${T} `)).trim(),i=(await z(e,` ${j}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=n,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let n=(await z(e,` ${j}DeepSeek API Key:${T} `)).trim(),i=(await z(e,` ${j}Model [deepseek-chat]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=n,t.model=i||"deepseek-chat";break}case"g":{let n=(await z(e,` ${j}API base URL:${T} `)).trim(),i=(await z(e,` ${j}API key (optional):${T} `)).trim(),o=(await z(e,` ${j}Model ID:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 URL is required \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl=n,t.apiKey=i,o&&(t.model=o);break}case"h":{let n=(await z(e,` ${j}NVIDIA API Key (nvapi-...):${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),console.log(`${j} Get your key at: https://build.nvidia.com/${T}`),e.close();return}console.log(),console.log(`${j} Available NVIDIA models:${T}`),ce.models.forEach((a,l)=>{console.log(` ${X}${l+1}${T}. ${a}`)}),console.log();let i=(await z(e,` ${j}Model number [1]:${T} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ce.apiUrl,t.apiKey=n,t.model=ce.models[o]||ce.defaultModel;break}case"i":{let n=(await z(e,` ${j}Mistral API Key:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),console.log(`${j} Get your key at: https://console.mistral.ai/api-keys/${T}`),e.close();return}console.log(),console.log(`${j} Available Mistral models:${T}`),Ge.models.forEach((a,l)=>{console.log(` ${X}${l+1}${T}. ${a}`)}),console.log();let i=(await z(e,` ${j}Model number [1]:${T} `)).trim(),o=parseInt(i,10)-1;t.provider="mistral",t.apiUrl=Ge.apiUrl,t.apiKey=n,t.model=Ge.models[o]||Ge.defaultModel;break}default:console.log(`${Ee} \u26A0 Invalid choice${T}`),e.close();return}Ye(t),console.log(),console.log(`${tr} \u2713 Custom provider configured successfully${T}`),console.log(`${j} Provider: ${t.provider}${T}`),console.log(`${j} Model: ${t.model}${T}`);break}default:console.log(`${Ee} \u26A0 Invalid choice \u2014 please select 1 or 2${T}`),e.close();return}console.log(),console.log(`${Fe}${tr} \u2713 Setup complete!${T}`),console.log(`${j} Use ${X}hablas${T}${j} for interactive mode or ${X}hablas run "..."${T}${j} for one-shot execution.${T}`),console.log(),e.close()}Si();var su=Ya(),ae=new Mi;ae.name("hablas").description(`Hablas CLI v${su} \u2014 single-agent engineering runtime for the terminal.`).version(su).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");ae.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ae.opts(),r=ft({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let s=gn(r);await Kc(t,r,s)});ae.command("doctor").description("Run system diagnostics").action(async()=>{let t=ae.opts(),e=ft({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Yr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Xr(r))});ae.command("info").description("Show workspace information").action(async()=>{let t=ae.opts(),e=ft({project:t.project});console.log(""),console.log(qr(Ct(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ae.command("security").description("Run a security scan on the current project").action(async()=>{let t=ae.opts(),e=ft({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Yc(Jc(r)))});ae.command("stats").description("Show local usage statistics").action(async()=>{console.log(eu(Zc()))});ae.action(async()=>{let t=ae.opts(),e=ft({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});if(t.auto&&(e.autoMode=!0),t.timeout&&(e.timeout=parseInt(t.timeout,10)),t.setup){await ru(e);return}let r=gn(e);await zc(e,r)});ae.parse();
333
+ `)}var ru=k(require("readline"));var Y="\x1B[36m",rr="\x1B[32m",Ee="\x1B[33m",j="\x1B[2m",Le="\x1B[1m",T="\x1B[0m",Ky="\x1B[35m";function z(t,e){return new Promise(r=>t.question(e,s=>r(s)))}function Gy(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var sr={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function su(t){let e=ru.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${Le}${Y} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(`${Le}${Y} hablas \u2014 Setup Wizard${T}`),console.log(`${j} Configure your AI provider and model${T}`),console.log(`${Le}${Y} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${T}`),console.log(),console.log(`${Le} Choose your setup:${T}`),console.log(),console.log(` ${Ky}${Le}1${T}. ${Le}Hablas Integrated Engine${T} ${rr}(instant \u2014 no setup needed)${T}`),console.log(` ${j}Pre-configured cloud AI, ready to use immediately${T}`),console.log(),console.log(` ${Y}${Le}2${T}. ${Le}Custom Provider${T} ${j}(bring your own API key)${T}`),console.log(` ${j}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${T}`),console.log(),(await z(e,` ${j}Your choice (1-2):${T} `)).trim()){case"1":{t.provider=sr.provider,t.apiUrl=sr.apiUrl,t.apiKey=Gy(),t.model=sr.model,Ye(t),console.log(),console.log(`${rr} \u2713 Hablas Integrated Engine activated!${T}`),console.log(`${j} Model: ${sr.model}${T}`),console.log(`${j} API: ${sr.apiUrl}${T}`),console.log(`${j} No API key needed \u2014 everything is pre-configured.${T}`);break}case"2":{switch(console.log(),console.log(`${j} Select your provider:${T}`),console.log(` ${Y}a${T}. Ollama (local, free, private)`),console.log(` ${Y}b${T}. OpenAI API`),console.log(` ${Y}c${T}. Groq (fast, free tier)`),console.log(` ${Y}d${T}. OpenRouter (many models)`),console.log(` ${Y}e${T}. Together AI`),console.log(` ${Y}f${T}. DeepSeek`),console.log(` ${Y}g${T}. Custom OpenAI-compatible API`),console.log(` ${Y}h${T}. NVIDIA NIM (powerful cloud models)`),console.log(` ${Y}i${T}. Mistral AI ${rr}(free tier available)${T}`),console.log(),(await z(e,` ${j}Your choice (a-h):${T} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let n=(await z(e,` ${j}Ollama host [http://localhost:11434]:${T} `)).trim(),i=(await z(e,` ${j}Model [qwen2.5-coder:7b]:${T} `)).trim();t.ollamaHost=n||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let n=(await z(e,` ${j}OpenAI API Key (sk-...):${T} `)).trim(),i=(await z(e,` ${j}Model [gpt-4o]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=n,t.model=i||"gpt-4o";break}case"c":{let n=(await z(e,` ${j}Groq API Key (gsk_...):${T} `)).trim(),i=(await z(e,` ${j}Model [llama-3.3-70b-versatile]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=n,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let n=(await z(e,` ${j}OpenRouter API Key (sk-or-...):${T} `)).trim(),i=(await z(e,` ${j}Model [anthropic/claude-3.5-sonnet]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=n,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let n=(await z(e,` ${j}Together API Key:${T} `)).trim(),i=(await z(e,` ${j}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=n,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let n=(await z(e,` ${j}DeepSeek API Key:${T} `)).trim(),i=(await z(e,` ${j}Model [deepseek-chat]:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=n,t.model=i||"deepseek-chat";break}case"g":{let n=(await z(e,` ${j}API base URL:${T} `)).trim(),i=(await z(e,` ${j}API key (optional):${T} `)).trim(),o=(await z(e,` ${j}Model ID:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 URL is required \u2014 cancelled${T}`),e.close();return}t.provider="custom",t.apiUrl=n,t.apiKey=i,o&&(t.model=o);break}case"h":{let n=(await z(e,` ${j}NVIDIA API Key (nvapi-...):${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),console.log(`${j} Get your key at: https://build.nvidia.com/${T}`),e.close();return}console.log(),console.log(`${j} Available NVIDIA models:${T}`),ce.models.forEach((a,l)=>{console.log(` ${Y}${l+1}${T}. ${a}`)}),console.log();let i=(await z(e,` ${j}Model number [1]:${T} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=ce.apiUrl,t.apiKey=n,t.model=ce.models[o]||ce.defaultModel;break}case"i":{let n=(await z(e,` ${j}Mistral API Key:${T} `)).trim();if(!n){console.log(`${Ee} \u26A0 No key provided \u2014 cancelled${T}`),console.log(`${j} Get your key at: https://console.mistral.ai/api-keys/${T}`),e.close();return}console.log(),console.log(`${j} Available Mistral models:${T}`),Je.models.forEach((a,l)=>{console.log(` ${Y}${l+1}${T}. ${a}`)}),console.log();let i=(await z(e,` ${j}Model number [1]:${T} `)).trim(),o=parseInt(i,10)-1;t.provider="mistral",t.apiUrl=Je.apiUrl,t.apiKey=n,t.model=Je.models[o]||Je.defaultModel;break}default:console.log(`${Ee} \u26A0 Invalid choice${T}`),e.close();return}Ye(t),console.log(),console.log(`${rr} \u2713 Custom provider configured successfully${T}`),console.log(`${j} Provider: ${t.provider}${T}`),console.log(`${j} Model: ${t.model}${T}`);break}default:console.log(`${Ee} \u26A0 Invalid choice \u2014 please select 1 or 2${T}`),e.close();return}console.log(),console.log(`${Le}${rr} \u2713 Setup complete!${T}`),console.log(`${j} Use ${Y}hablas${T}${j} for interactive mode or ${Y}hablas run "..."${T}${j} for one-shot execution.${T}`),console.log(),e.close()}vi();var nu=Ya(),ae=new Fi;ae.name("hablas").description(`Hablas CLI v${nu} \u2014 single-agent engineering runtime for the terminal.`).version(nu).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");ae.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ae.opts(),r=dt({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let s=wn(r);await Gc(t,r,s)});ae.command("doctor").description("Run system diagnostics").action(async()=>{let t=ae.opts(),e=dt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await Yr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(Qr(r))});ae.command("info").description("Show workspace information").action(async()=>{let t=ae.opts(),e=dt({project:t.project});console.log(""),console.log(Br($t(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ae.command("security").description("Run a security scan on the current project").action(async()=>{let t=ae.opts(),e=dt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(Yc(Xc(r)))});ae.command("stats").description("Show local usage statistics").action(async()=>{console.log(tu(eu()))});ae.action(async()=>{let t=ae.opts(),e=dt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey});if(t.auto&&(e.autoMode=!0),t.timeout&&(e.timeout=parseInt(t.timeout,10)),t.setup){await su(e);return}let r=wn(e);await Kc(e,r)});ae.parse();