hablas-ai 2.6.1 → 2.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +228 -179
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -1,100 +1,149 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"use strict";var Pu=Object.create;var bi=Object.defineProperty;var ju=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Lu=Object.getPrototypeOf,Du=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Nu=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fu(e))!Du.call(t,s)&&s!==r&&bi(t,s,{get:()=>e[s],enumerable:!(n=ju(e,s))||n.enumerable});return t};var T=(t,e,r)=>(r=t!=null?Pu(Lu(t)):{},Nu(e||!t||!t.__esModule?bi(r,"default",{value:t,enumerable:!0}):r,t));var qt=P(bn=>{var dr=class extends Error{constructor(e,r,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=r,this.exitCode=e,this.nestedError=void 0}},wn=class extends dr{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};bn.CommanderError=dr;bn.InvalidArgumentError=wn});var pr=P(Sn=>{var{InvalidArgumentError:Ju}=qt(),vn=class{constructor(e,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Ju(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Yu(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Sn.Argument=vn;Sn.humanReadableArgName=Yu});var _n=P(Di=>{var{humanReadableArgName:Xu}=pr(),xn=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let r=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&r.push(n),this.sortSubcommands&&r.sort((s,i)=>s.name().localeCompare(i.name())),r}compareOptions(e,r){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(r))}visibleOptions(e){let r=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?r.push(n):n.long&&!i?r.push(e.createOption(n.long,n.description)):n.short&&!s&&r.push(e.createOption(n.short,n.description))}return this.sortOptions&&r.sort(this.compareOptions),r}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let r=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);r.push(...s)}return this.sortOptions&&r.sort(this.compareOptions),r}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(r=>{r.description=r.description||e._argsDescription[r.name()]||""}),e.registeredArguments.find(r=>r.description)?e.registeredArguments:[]}subcommandTerm(e){let r=e.registeredArguments.map(n=>Xu(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,s)=>Math.max(n,r.subcommandTerm(s).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,r.optionTerm(s).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,s)=>Math.max(n,r.argumentTerm(s).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),s=r.helpWidth||80,i=2,o=2;function a(f,m){if(m){let g=`${f.padEnd(n+o)}${m}`;return r.wrap(g,s-i,n+o)}return f}function c(f){return f.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,s,0),""]));let d=r.visibleArguments(e).map(f=>a(r.argumentTerm(f),r.argumentDescription(f)));d.length>0&&(l=l.concat(["Arguments:",c(d),""]));let p=r.visibleOptions(e).map(f=>a(r.optionTerm(f),r.optionDescription(f)));if(p.length>0&&(l=l.concat(["Options:",c(p),""])),this.showGlobalOptions){let f=r.visibleGlobalOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));f.length>0&&(l=l.concat(["Global Options:",c(f),""]))}let h=r.visibleCommands(e).map(f=>a(r.subcommandTerm(f),r.subcommandDescription(f)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let a=r-n;if(a<s)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),u=" ".repeat(n),p="\\s\u200B",h=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),f=l.match(h)||[];return c+f.map((m,g)=>m===`
|
|
8
|
+
`?"":(g>0?u:"")+m.trimEnd()).join(`
|
|
9
|
+
`)}};Di.Help=xn});var $n=P(Cn=>{var{InvalidArgumentError:Qu}=qt(),kn=class{constructor(e,r){this.flags=e,this.description=r||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=ef(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,r){return this.defaultValue=e,this.defaultValueDescription=r,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let r=e;return typeof e=="string"&&(r={[e]:!0}),this.implied=Object.assign(this.implied||{},r),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,r){return r===this.defaultValue||!Array.isArray(r)?[e]:r.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(r,n)=>{if(!this.argChoices.includes(r))throw new Qu(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,n):r},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return Zu(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Tn=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(r=>{r.negate?this.negativeOptions.set(r.attributeName(),r):this.positiveOptions.set(r.attributeName(),r)}),this.negativeOptions.forEach((r,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,r){let n=r.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return r.negate===(i===e)}};function Zu(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function ef(t){let e,r,n=t.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),r=n.shift(),!e&&/^-[^-]$/.test(r)&&(e=r,r=void 0),{shortFlag:e,longFlag:r}}Cn.Option=kn;Cn.DualOptions=Tn});var Ui=P(Ni=>{function tf(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let i=1;t[s-1]===e[n-1]?i=0:i=1,r[s][n]=Math.min(r[s-1][n]+1,r[s][n-1]+1,r[s-1][n-1]+i),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1]&&(r[s][n]=Math.min(r[s][n],r[s-2][n-2]+1))}return r[t.length][e.length]}function rf(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let r=t.startsWith("--");r&&(t=t.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let a=tf(t,o),c=Math.max(t.length,o.length);(c-a)/c>i&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),r&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Ni.suggestSimilar=rf});var Vi=P(Wi=>{var nf=require("node:events").EventEmitter,An=require("node:child_process"),Me=require("node:path"),En=require("node:fs"),z=require("node:process"),{Argument:sf,humanReadableArgName:of}=pr(),{CommanderError:On}=qt(),{Help:af}=_n(),{Option:qi,DualOptions:cf}=$n(),{suggestSimilar:Bi}=Ui(),Rn=class t extends nf{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=>z.stdout.write(r),writeErr:r=>z.stderr.write(r),getOutHelpWidth:()=>z.stdout.isTTY?z.stdout.columns:void 0,getErrHelpWidth:()=>z.stderr.isTTY?z.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let s=r,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(o);return s&&(c.description(s),c._executableHandler=!0),i.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(i.noHelp||i.hidden),c._executableFile=i.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),s?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new af,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 sf(e,r)}argument(e,r,n,s){let i=this.createArgument(e,r);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(r=>{this.argument(r)}),this}addArgument(e){let r=this.registeredArguments.slice(-1)[0];if(r&&r.variadic)throw new Error(`only the last argument can be variadic '${r.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,r){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=r??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,r){return typeof e!="object"?(this.helpCommand(e,r),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,r){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(r):this._lifeCycleHooks[e]=[r],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=r=>{if(r.code!=="commander.executeSubCommandAsync")throw r},this}_exit(e,r,n){this._exitCallback&&this._exitCallback(new On(e,r,n)),z.exit(e)}action(e){let r=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=r,this}createOption(e,r){return new qi(e,r)}_callParseArg(e,r,n,s){try{return e.parseArg(r,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let r=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(r){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${r.flags}'`)}this.options.push(e)}_registerCommand(e){let r=s=>[s.name()].concat(s.aliases()),n=r(e).find(s=>this._findCommand(s));if(n){let s=r(this._findCommand(n)).join("|"),i=r(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let r=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,a)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let c=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,c,o):i!==null&&e.variadic&&(i=e._concatValue(i,c)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,a)};return this.on("option:"+r,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+r,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,r,n,s,i){if(typeof r=="object"&&r instanceof qi)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(r,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let a=s;s=(c,l)=>{let u=a.exec(c);return u?u[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,r,n,s){return this._optionEx({},e,r,n,s)}requiredOption(e,r,n,s){return this._optionEx({mandatory:!0},e,r,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,r){return this.setOptionValueWithSource(e,r,void 0)}setOptionValueWithSource(e,r,n){return this._storeOptionsAsProperties?this[e]=r:this._optionValues[e]=r,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let r;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(r=n.getOptionValueSource(e))}),r}_prepareUserArgs(e,r){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(r=r||{},e===void 0&&r.from===void 0){z.versions?.electron&&(r.from="electron");let s=z.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(r.from="eval")}e===void 0&&(e=z.argv),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":z.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(u,d){let p=Me.resolve(u,d);if(En.existsSync(p))return p;if(s.includes(Me.extname(d)))return;let h=s.find(f=>En.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=En.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Me.resolve(Me.dirname(u),a)}if(a){let u=i(a,o);if(!u&&!e._executableFile&&this._scriptPath){let d=Me.basename(this._scriptPath,Me.extname(this._scriptPath));d!==this._name&&(u=i(a,`${d}-${e._name}`))}o=u||o}n=s.includes(Me.extname(o));let c;z.platform!=="win32"?n?(r.unshift(o),r=Hi(z.execArgv).concat(r),c=An.spawn(z.argv[0],r,{stdio:"inherit"})):c=An.spawn(o,r,{stdio:"inherit"}):(r.unshift(o),r=Hi(z.execArgv).concat(r),c=An.spawn(z.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{z.on(d,()=>{c.killed===!1&&c.exitCode===null&&c.kill(d)})});let l=this._exitCallback;c.on("close",u=>{u=u??1,l?l(new On(u,"commander.executeSubCommandAsync","(close)")):z.exit(u)}),c.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
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
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(!l)z.exit(1);else{let d=new On(1,"commander.executeSubCommandAsync","(error)");d.nestedError=u,l(d)}}),this.runningCommand=c}_dispatchSubcommand(e,r,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,r.concat(n));else return s._parseCommand(r,n)}),i}_dispatchHelpCommand(e){e||this.help();let r=this._findCommand(e);return r&&!r._executableHandler&&r.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,r)=>{e.required&&this.args[r]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,a)}return o};this._checkNumberOfArguments();let r=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,a)=>e(n,a,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),r[s]=i}),this.processedArgs=r}_chainOrCall(e,r){return e&&e.then&&typeof e.then=="function"?e.then(()=>r()):r()}_chainOrCallHooks(e,r){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[r]!==void 0).forEach(i=>{i._lifeCycleHooks[r].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),r==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,r,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,r))}),s}_parseCommand(e,r){let n=this.parseOptions(r);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),r=n.unknown,this.args=e.concat(r),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),r);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,r)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,r);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,r);this.listenerCount("command:*")?this.emit("command:*",e,r):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(r=>r._name===e||r._aliases.includes(e))}_findOption(e){return this.options.find(r=>r.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(r=>{r.mandatory&&e.getOptionValue(r.attributeName())===void 0&&e.missingMandatoryOptionValue(r)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let r=[],n=[],s=r,i=e.slice();function o(c){return c.length>1&&c[0]==="-"}let a=null;for(;i.length;){let c=i.shift();if(c==="--"){s===n&&s.push(c),s.push(...i);break}if(a&&!o(c)){this.emit(`option:${a.name()}`,c);continue}if(a=null,o(c)){let l=this._findOption(c);if(l){if(l.required){let u=i.shift();u===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,u)}else if(l.optional){let u=null;i.length>0&&!o(i[0])&&(u=i.shift()),this.emit(`option:${l.name()}`,u)}else this.emit(`option:${l.name()}`);a=l.variadic?l:null;continue}}if(c.length>2&&c[0]==="-"&&c[1]!=="-"){let l=this._findOption(`-${c[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,c.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${c.slice(2)}`));continue}}if(/^--[^=]+=/.test(c)){let l=c.indexOf("="),u=this._findOption(c.slice(0,l));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,c.slice(l+1));continue}}if(o(c)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&n.length===0){if(this._findCommand(c)){r.push(c),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&c===this._getHelpCommand().name()){r.push(c),i.length>0&&r.push(...i);break}else if(this._defaultCommandName){n.push(c),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(c),i.length>0&&s.push(...i);break}s.push(c)}return{operands:r,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},r=this.options.length;for(let n=0;n<r;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,r)=>Object.assign(e,r.opts()),{})}error(e,r){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=r||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in z.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()}`,z.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new cf(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),c=this.getOptionValue(a),l=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return l&&(l.presetArg===void 0&&c===!1||l.presetArg!==void 0&&c===l.presetArg)?l:u||o},s=o=>{let a=n(o),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=Bi(e,s)}let n=`error: unknown option '${e}'${r}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let r=this.registeredArguments.length,n=r===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${r} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],r="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),r=Bi(e,s)}let n=`error: unknown command '${e}'${r}`;this.error(n,{code:"commander.unknownCommand"})}version(e,r,n){if(e===void 0)return this._version;this._version=e,r=r||"-V, --version",n=n||"output the version number";let s=this.createOption(r,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,r){return e===void 0&&r===void 0?this._description:(this._description=e,r&&(this._argsDescription=r),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(r=this.commands[this.commands.length-1]),e===r._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return r._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(r=>this.alias(r)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let r=this.registeredArguments.map(n=>of(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?r:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=Me.basename(e,Me.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let r=this.createHelp();return r.helpWidth===void 0&&(r.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),r.formatHelp(this,r)}_getHelpContext(e){e=e||{};let r={error:!!e.error},n;return r.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),r.write=e.write||n,r.command=this,r}outputHelp(e){let r;typeof e=="function"&&(r=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(r&&(s=r(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,r){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",r=r??"display help for command",this._helpOption=this.createOption(e,r),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let r=z.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Hi(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?r=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=i[1],n=i[3],s=i[4]),r&&s!=="0"?`${r}=${n}:${parseInt(s)+1}`:e})}Wi.Command=Rn});var Ji=P(fe=>{var{Argument:zi}=pr(),{Command:In}=Vi(),{CommanderError:lf,InvalidArgumentError:Ki}=qt(),{Help:uf}=_n(),{Option:Gi}=$n();fe.program=new In;fe.createCommand=t=>new In(t);fe.createOption=(t,e)=>new Gi(t,e);fe.createArgument=(t,e)=>new zi(t,e);fe.Command=In;fe.Option=Gi;fe.Argument=zi;fe.Help=uf;fe.CommanderError=lf;fe.InvalidArgumentError=Ki;fe.InvalidOptionArgumentError=Ki});var jn=P((ab,ro)=>{"use strict";var Bt=t=>t&&typeof t.message=="string",Pn=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return Bt(r)?r:void 0}else return Bt(e)?e:void 0},eo=(t,e)=>{if(!Bt(t))return"";let r=t.stack||"";if(e.has(t))return r+`
|
|
24
|
+
causes have become circular...`;let n=Pn(t);return n?(e.add(t),r+`
|
|
25
|
+
caused by: `+eo(n,e)):r},ff=t=>eo(t,new Set),to=(t,e,r)=>{if(!Bt(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Pn(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+to(s,e,i)}else return n},df=t=>to(t,new Set);ro.exports={isErrorLike:Bt,getErrorCause:Pn,stackWithCauses:ff,messageWithCauses:df}});var Fn=P((cb,so)=>{"use strict";var pf=Symbol("circular-ref-tag"),hr=Symbol("pino-raw-err-ref"),no=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[hr]},set:function(t){this[hr]=t}}});Object.defineProperty(no,hr,{writable:!0,value:{}});so.exports={pinoErrProto:no,pinoErrorSymbols:{seen:pf,rawSymbol:hr}}});var ao=P((lb,oo)=>{"use strict";oo.exports=Dn;var{messageWithCauses:hf,stackWithCauses:mf,isErrorLike:io}=jn(),{pinoErrProto:gf,pinoErrorSymbols:yf}=Fn(),{seen:Ln}=yf,{toString:wf}=Object.prototype;function Dn(t){if(!io(t))return t;t[Ln]=void 0;let e=Object.create(gf);e.type=wf.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=hf(t),e.stack=mf(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Dn(r)));for(let r in t)if(e[r]===void 0){let n=t[r];io(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Ln)&&(e[r]=Dn(n)):e[r]=n}return delete t[Ln],e.raw=t,e}});var lo=P((ub,co)=>{"use strict";co.exports=gr;var{isErrorLike:Nn}=jn(),{pinoErrProto:bf,pinoErrorSymbols:vf}=Fn(),{seen:mr}=vf,{toString:Sf}=Object.prototype;function gr(t){if(!Nn(t))return t;t[mr]=void 0;let e=Object.create(bf);e.type=Sf.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=>gr(r))),Nn(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,mr)&&(e.cause=gr(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Nn(n)?Object.prototype.hasOwnProperty.call(n,mr)||(e[r]=gr(n)):e[r]=n}return delete t[mr],e.raw=t,e}});var ho=P((fb,po)=>{"use strict";po.exports={mapHttpRequest:xf,reqSerializer:fo};var Un=Symbol("pino-raw-req-ref"),uo=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Un]},set:function(t){this[Un]=t}}});Object.defineProperty(uo,Un,{writable:!0,value:{}});function fo(t){let e=t.info||t.socket,r=Object.create(uo);if(r.id=typeof t.id=="function"?t.id():t.id||(t.info?t.info.id:void 0),r.method=t.method,t.originalUrl)r.url=t.originalUrl;else{let n=t.path;r.url=typeof n=="string"?n:t.url?t.url.path||t.url:void 0}return t.query&&(r.query=t.query),t.params&&(r.params=t.params),r.headers=t.headers,r.remoteAddress=e&&e.remoteAddress,r.remotePort=e&&e.remotePort,r.raw=t.raw||t,r}function xf(t){return{req:fo(t)}}});var wo=P((db,yo)=>{"use strict";yo.exports={mapHttpResponse:_f,resSerializer:go};var qn=Symbol("pino-raw-res-ref"),mo=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[qn]},set:function(t){this[qn]=t}}});Object.defineProperty(mo,qn,{writable:!0,value:{}});function go(t){let e=Object.create(mo);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function _f(t){return{res:go(t)}}});var Hn=P((pb,bo)=>{"use strict";var Bn=ao(),kf=lo(),yr=ho(),wr=wo();bo.exports={err:Bn,errWithCause:kf,mapHttpRequest:yr.mapHttpRequest,mapHttpResponse:wr.mapHttpResponse,req:yr.reqSerializer,res:wr.resSerializer,wrapErrorSerializer:function(e){return e===Bn?e:function(n){return e(Bn(n))}},wrapRequestSerializer:function(e){return e===yr.reqSerializer?e:function(n){return e(yr.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===wr.resSerializer?e:function(n){return e(wr.resSerializer(n))}}}});var Wn=P((hb,vo)=>{"use strict";function Tf(t,e){return e}vo.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=Tf;let r=new Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(r))return;let n=r.slice(2),s=[];for(let i of n)i&&s.push(i.getFileName());return s}});var Co=P((mb,To)=>{"use strict";function Vn(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]=Vn(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]=Vn(t[r]));return e}return t}function So(t){let e=[],r="",n=!1,s=!1,i="";for(let o=0;o<t.length;o++){let a=t[o];!n&&a==="."?r&&(e.push(r),r=""):a==="["?(r&&(e.push(r),r=""),n=!0):a==="]"&&n?(e.push(r),r="",n=!1,s=!1):(a==='"'||a==="'")&&n?s?a===i?(s=!1,i=""):r+=a:(s=!0,i=a):r+=a}return r&&e.push(r),e}function xo(t,e,r){let n=t;for(let i=0;i<e.length-1;i++){let o=e[i];if(typeof n!="object"||n===null||!(o in n)||typeof n[o]!="object"||n[o]===null)return!1;n=n[o]}let s=e[e.length-1];if(s==="*"){if(Array.isArray(n))for(let i=0;i<n.length;i++)n[i]=r;else if(typeof n=="object"&&n!==null)for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(n[i]=r)}else typeof n=="object"&&n!==null&&s in n&&Object.prototype.hasOwnProperty.call(n,s)&&(n[s]=r);return!0}function _o(t,e){let r=t;for(let s=0;s<e.length-1;s++){let i=e[s];if(typeof r!="object"||r===null||!(i in r)||typeof r[i]!="object"||r[i]===null)return!1;r=r[i]}let n=e[e.length-1];if(n==="*"){if(Array.isArray(r))for(let s=0;s<r.length;s++)r[s]=void 0;else if(typeof r=="object"&&r!==null)for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&delete r[s]}else typeof r=="object"&&r!==null&&n in r&&Object.prototype.hasOwnProperty.call(r,n)&&delete r[n];return!0}var br=Symbol("PATH_NOT_FOUND");function Cf(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return br;r=r[n]}return r}function $f(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null)return;r=r[n]}return r}function Af(t,e,r,n=!1){for(let s of e){let i=So(s);if(i.includes("*"))ko(t,i,r,s,n);else if(n)_o(t,i);else{let o=Cf(t,i);if(o===br)continue;let a=typeof r=="function"?r(o,i):r;xo(t,i,a)}}}function ko(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let c of o){if(a==null||typeof a!="object"||a===null)return;a=a[c]}if(Array.isArray(a))if(s)for(let c=0;c<a.length;c++)a[c]=void 0;else for(let c=0;c<a.length;c++){let l=[...o,c.toString()],u=typeof r=="function"?r(a[c],l):r;a[c]=u}else if(typeof a=="object"&&a!==null)if(s){let c=[];for(let l in a)Object.prototype.hasOwnProperty.call(a,l)&&c.push(l);for(let l of c)delete a[l]}else for(let c in a){let l=[...o,c],u=typeof r=="function"?r(a[c],l):r;a[c]=u}}else Ef(t,e,r,i,n,s)}function Ef(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),c=[];function l(u,d){if(d===o.length){if(Array.isArray(u))for(let p=0;p<u.length;p++)c[d]=p.toString(),l(u[p],d+1);else if(typeof u=="object"&&u!==null)for(let p in u)c[d]=p,l(u[p],d+1)}else if(d<o.length){let p=o[d];u&&typeof u=="object"&&u!==null&&p in u&&(c[d]=p,l(u[p],d+1))}else if(a.includes("*"))ko(u,a,typeof r=="function"?(h,f)=>{let m=[...c.slice(0,d),...f];return r(h,m)}:r,s,i);else if(i)_o(u,a);else{let p=typeof r=="function"?r($f(u,a),[...c.slice(0,d),...a]):r;xo(u,a,p)}}if(o.length===0)l(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],c[d]=p}u!=null&&l(u,o.length)}}function Of(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=So(r),s=e;for(let i=0;i<n.length;i++){let o=n[i];s.has(o)||s.set(o,new Map),s=s.get(o)}}return e}function Rf(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let c=0;c<n.length;c++){let l=c.toString();s.has(l)||s.has("*")?a[c]=r(n[c],s.get(l)||s.get("*")):a[c]=n[c]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function If(t){if(typeof t!="string")throw new Error("Paths must be (non-empty) strings");if(t==="")throw new Error("Invalid redaction path ()");if(t.includes(".."))throw new Error(`Invalid redaction path (${t})`);if(t.includes(","))throw new Error(`Invalid redaction path (${t})`);let e=0,r=!1,n="";for(let s=0;s<t.length;s++){let i=t[s];if((i==='"'||i==="'")&&e>0)r?i===n&&(r=!1,n=""):(r=!0,n=i);else if(i==="["&&!r)e++;else if(i==="]"&&!r&&(e--,e<0))throw new Error(`Invalid redaction path (${t})`)}if(e!==0)throw new Error(`Invalid redaction path (${t})`)}function Mf(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)If(e)}function Pf(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Mf(e);let o=Of(e);return function(c){if(s&&(c===null||typeof c!="object")&&(c==null||typeof c!="object"))return n?n(c):c;let l=Rf(c,o),u=c,d=r;return typeof r=="function"&&(d=r),Af(l,e,d,i),n===!1?(l.restore=function(){return Vn(u)},l):typeof n=="function"?n(l):JSON.stringify(l)}}To.exports=Pf});var yt=P((gb,$o)=>{"use strict";var jf=Symbol("pino.setLevel"),Ff=Symbol("pino.getLevel"),Lf=Symbol("pino.levelVal"),Df=Symbol("pino.levelComp"),Nf=Symbol("pino.useLevelLabels"),Uf=Symbol("pino.useOnlyCustomLevels"),qf=Symbol("pino.mixin"),Bf=Symbol("pino.lsCache"),Hf=Symbol("pino.chindings"),Wf=Symbol("pino.asJson"),Vf=Symbol("pino.write"),zf=Symbol("pino.redactFmt"),Kf=Symbol("pino.time"),Gf=Symbol("pino.timeSliceIndex"),Jf=Symbol("pino.stream"),Yf=Symbol("pino.stringify"),Xf=Symbol("pino.stringifySafe"),Qf=Symbol("pino.stringifiers"),Zf=Symbol("pino.end"),ed=Symbol("pino.formatOpts"),td=Symbol("pino.messageKey"),rd=Symbol("pino.errorKey"),nd=Symbol("pino.nestedKey"),sd=Symbol("pino.nestedKeyStr"),id=Symbol("pino.mixinMergeStrategy"),od=Symbol("pino.msgPrefix"),ad=Symbol("pino.wildcardFirst"),cd=Symbol.for("pino.serializers"),ld=Symbol.for("pino.formatters"),ud=Symbol.for("pino.hooks"),fd=Symbol.for("pino.metadata");$o.exports={setLevelSym:jf,getLevelSym:Ff,levelValSym:Lf,levelCompSym:Df,useLevelLabelsSym:Nf,mixinSym:qf,lsCacheSym:Bf,chindingsSym:Hf,asJsonSym:Wf,writeSym:Vf,serializersSym:cd,redactFmtSym:zf,timeSym:Kf,timeSliceIndexSym:Gf,streamSym:Jf,stringifySym:Yf,stringifySafeSym:Xf,stringifiersSym:Qf,endSym:Zf,formatOptsSym:ed,messageKeySym:td,errorKeySym:rd,nestedKeySym:nd,wildcardFirstSym:ad,needsMetadataGsym:fd,useOnlyCustomLevelsSym:Uf,formattersSym:ld,hooksSym:ud,nestedKeyStrSym:sd,mixinMergeStrategySym:id,msgPrefixSym:od}});var Kn=P((yb,Ro)=>{"use strict";var Ao=Co(),{redactFmtSym:dd,wildcardFirstSym:vr}=yt(),zn=/[^.[\]]+|\[([^[\]]*?)\]/g,Eo="[Redacted]",Oo=!1;function pd(t,e){let{paths:r,censor:n,remove:s}=hd(t),i=r.reduce((c,l)=>{zn.lastIndex=0;let u=zn.exec(l),d=zn.exec(l),p=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(p==="*"&&(p=vr),d===null)return c[p]=null,c;if(c[p]===null)return c;let{index:h}=d,f=`${l.substr(h,l.length-1)}`;return c[p]=c[p]||[],p!==vr&&c[p].length===0&&c[p].push(...c[vr]||[]),p===vr&&Object.keys(c).forEach(function(m){c[m]&&c[m].push(f)}),c[p].push(f),c},{}),o={[dd]:Ao({paths:r,censor:n,serialize:e,strict:Oo,remove:s})},a=(...c)=>e(typeof n=="function"?n(...c):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((c,l)=>{if(i[l]===null)c[l]=u=>a(u,[l]);else{let u=typeof n=="function"?(d,p)=>n(d,[l,...p]):n;c[l]=Ao({paths:i[l],censor:u,serialize:e,strict:Oo,remove:s})}return c},o)}function hd(t){if(Array.isArray(t))return t={paths:t,censor:Eo},t;let{paths:e,censor:r=Eo,remove:n}=t;if(Array.isArray(e)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),{paths:e,censor:r,remove:n}}Ro.exports=pd});var Po=P((wb,Mo)=>{"use strict";var md=()=>"",gd=()=>`,"time":${Date.now()}`,yd=()=>`,"time":${Math.round(Date.now()/1e3)}`,wd=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,bd=1000000n,Io=1000000000n,vd=BigInt(Date.now())*bd,Sd=process.hrtime.bigint(),xd=()=>{let t=process.hrtime.bigint()-Sd,e=vd+t,r=e/Io,n=e%Io,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),c=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${c}T${l}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};Mo.exports={nullTime:md,epochTime:gd,unixTime:yd,isoTime:wd,isoTimeNano:xd}});var Fo=P((bb,jo)=>{"use strict";function _d(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}jo.exports=kd;function kd(t,e,r){var n=r&&r.stringify||_d,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-s,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>=c||e[u]==null)break;d<h&&(l+=t.slice(d,h)),l+=Number(e[u]),d=h+2,h++;break;case 105:if(u>=c||e[u]==null)break;d<h&&(l+=t.slice(d,h)),l+=Math.floor(Number(e[u])),d=h+2,h++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;d<h&&(l+=t.slice(d,h));var f=typeof e[u];if(f==="string"){l+="'"+e[u]+"'",d=h+2,h++;break}if(f==="function"){l+=e[u].name||"<anonymous>",d=h+2,h++;break}l+=n(e[u]),d=h+2,h++;break;case 115:if(u>=c)break;d<h&&(l+=t.slice(d,h)),l+=String(e[u]),d=h+2,h++;break;case 37:d<h&&(l+=t.slice(d,h)),l+="%",d=h+2,h++,u--;break}++u}++h}return d===-1?t:(d<p&&(l+=t.slice(d)),l)}});var Jn=P((vb,Gn)=>{"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));Gn.exports=e}else{let t=function(e){if((e>0&&e<1/0)===!1)throw typeof e!="number"&&typeof e!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(e);for(;n>Date.now(););};Gn.exports=t}});var Wo=P((Sb,Ho)=>{"use strict";var B=require("fs"),Td=require("events"),Cd=require("util").inherits,Lo=require("path"),Xn=Jn(),$d=require("assert"),Sr=100,xr=Buffer.allocUnsafe(0),Ad=16*1024,Do="buffer",No="utf8",[Ed,Od]=(process.versions.node||"0.0").split(".").map(Number),Rd=Ed>=22&&Od>=7;function Uo(t,e){e._opening=!0,e._writing=!0,e._asyncDrainScheduled=!1;function r(i,o){if(i){e._reopening=!1,e._writing=!1,e._opening=!1,e.sync?process.nextTick(()=>{e.listenerCount("error")>0&&e.emit("error",i)}):e.emit("error",i);return}let a=e._reopening;e.fd=o,e.file=t,e._reopening=!1,e._opening=!1,e._writing=!1,e.sync?process.nextTick(()=>e.emit("ready")):e.emit("ready"),!e.destroyed&&(!e._writing&&e._len>e.minLength||e._flushPending?e._actualWrite():a&&process.nextTick(()=>e.emit("drain")))}let n=e.append?"a":"w",s=e.mode;if(e.sync)try{e.mkdir&&B.mkdirSync(Lo.dirname(t),{recursive:!0});let i=B.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?B.mkdir(Lo.dirname(t),{recursive:!0},i=>{if(i)return r(i);B.open(t,n,s,r)}):B.open(t,n,s,r)}function xe(t){if(!(this instanceof xe))return new xe(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:c=!0,mkdir:l,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(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Ad,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=c||!1,this.mode=h,this.retryEAGAIN=u||(()=>!0),this.mkdir=l||!1;let f,m;if(p===Do)this._writingBuf=xr,this.write=Pd,this.flush=Fd,this.flushSync=Dd,this._actualWrite=Ud,f=()=>B.writeSync(this.fd,this._writingBuf),m=()=>B.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===No)this._writingBuf="",this.write=Md,this.flush=jd,this.flushSync=Ld,this._actualWrite=Nd,f=()=>Buffer.isBuffer(this._writingBuf)?B.writeSync(this.fd,this._writingBuf):B.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?B.write(this.fd,this._writingBuf,this.release):B.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${No}" and "${Do}", but passed ${p}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Uo(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{Xn(Sr),this.release(void 0,0)}catch(v){this.release(v)}else setTimeout(m,Sr);else this._writing=!1,this.emit("error",g);return}this.emit("write",y);let b=Yn(this._writingBuf,this._len,y);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let v=f(),_=Yn(this._writingBuf,this._len,v);this._len=_.len,this._writingBuf=_.writingBuf}while(this._writingBuf.length)}catch(v){this.release(v);return}}this._fsync&&B.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,_r(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Id,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 Yn(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 Id(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Cd(xe,Td);function qo(t,e){return t.length===0?xr:t.length===1?t[0]:Buffer.concat(t,e)}function Md(t){if(this.destroyed)throw new Error("SonicBoom destroyed");t=""+t;let e=Buffer.byteLength(t),r=this._len+e,n=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(n.length===0||Buffer.byteLength(n[n.length-1])+e>this.maxWrite?n.push(t):n[n.length-1]+=t,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Pd(t){if(this.destroyed)throw new Error("SonicBoom destroyed");let e=this._len+t.length,r=this._bufs,n=this._lens;return this.maxLength&&e>this.maxLength?(this.emit("drop",t),this._len<this._hwm):(r.length===0||n[n.length-1]+t.length>this.maxWrite?(r.push([t]),n.push(t.length)):(r[r.length-1].push(t),n[n.length-1]+=t.length),this._len=e,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function Bo(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{B.fsync(this.fd,n=>{this._flushPending=!1,t(n)})}catch(n){t(n)}this.off("error",r)},r=n=>{this._flushPending=!1,t(n),this.off("drain",e)};this.once("drain",e),this.once("error",r)}function jd(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&&Bo.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Fd(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&&Bo.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}xe.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&&B.close(e,r=>{if(r)return this.emit("error",r)})}),Uo(this.file,this)};xe.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():_r(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)?B.writeSync(this.fd,t):B.writeSync(this.fd,t,"utf8"),r=Yn(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;Xn(Sr)}}try{B.fsyncSync(this.fd)}catch{}}function Dd(){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=xr);let t=xr;for(;this._bufs.length||t.length;){t.length<=0&&(t=qo(this._bufs[0],this._lens[0]));try{let e=B.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;Xn(Sr)}}}xe.prototype.destroy=function(){this.destroyed||_r(this)};function Nd(){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)?B.writeSync(this.fd,this._writingBuf):B.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else B.write(this.fd,this._writingBuf,t)}function Ud(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:qo(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=B.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Rd&&(this._writingBuf=Buffer.from(this._writingBuf)),B.write(this.fd,this._writingBuf,t)}function _r(t){if(t.fd===-1){t.once("ready",_r.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],$d(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{B.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?B.close(t.fd,r):r()}function r(n){if(n){t.emit("error",n);return}t._ending&&!t._writing&&t.emit("finish"),t.emit("close")}}xe.SonicBoom=xe;xe.default=xe;Ho.exports=xe});var Qn=P((xb,Jo)=>{"use strict";var _e={exit:[],beforeExit:[]},Vo={exit:Hd,beforeExit:Wd},wt;function qd(){wt===void 0&&(wt=new FinalizationRegistry(Vd))}function Bd(t){_e[t].length>0||process.on(t,Vo[t])}function zo(t){_e[t].length>0||(process.removeListener(t,Vo[t]),_e.exit.length===0&&_e.beforeExit.length===0&&(wt=void 0))}function Hd(){Ko("exit")}function Wd(){Ko("beforeExit")}function Ko(t){for(let e of _e[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}_e[t]=[]}function Vd(t){for(let e of["exit","beforeExit"]){let r=_e[e].indexOf(t);_e[e].splice(r,r+1),zo(e)}}function Go(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");Bd(t);let n=new WeakRef(e);n.fn=r,qd(),wt.register(e,n),_e[t].push(n)}function zd(t,e){Go("exit",t,e)}function Kd(t,e){Go("beforeExit",t,e)}function Gd(t){if(wt!==void 0){wt.unregister(t);for(let e of["exit","beforeExit"])_e[e]=_e[e].filter(r=>{let n=r.deref();return n&&n!==t}),zo(e)}}Jo.exports={register:zd,registerBeforeExit:Kd,unregister:Gd}});var Yo=P((_b,Jd)=>{Jd.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 Qo=P((kb,Xo)=>{"use strict";function Yd(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,a,c);l.async?l.value.then(o):setImmediate(o)};o()}function Xd(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let c=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),l=Atomics.waitAsync(t,e,r,c);l.async?l.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}Xo.exports={wait:Yd,waitDiff:Xd}});var ea=P((Tb,Zo)=>{"use strict";Zo.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var da=P((Cb,fa)=>{"use strict";var{version:Qd}=Yo(),{EventEmitter:Zd}=require("events"),{Worker:ep}=require("worker_threads"),{join:tp}=require("path"),{pathToFileURL:rp}=require("url"),{wait:np}=Qo(),{WRITE_INDEX:Pe,READ_INDEX:rt,SEQ_INDEX:Zn}=ea(),sp=require("buffer"),ip=require("assert"),x=Symbol("kImpl"),op=sp.constants.MAX_STRING_LENGTH;function ta(){}function ns(t,e){Atomics.add(t[x].state,Zn,1),e(),Atomics.add(t[x].state,Zn,1),Atomics.notify(t[x].state,Zn)}function ra(t){ns(t,()=>{Atomics.store(t[x].state,rt,0),Atomics.store(t[x].state,Pe,0)})}var Ht=class{constructor(e){this._value=e}deref(){return this._value}},kr=class{register(){}unregister(){}},ap=process.env.NODE_V8_COVERAGE?kr:global.FinalizationRegistry||kr,cp=process.env.NODE_V8_COVERAGE?Ht:global.WeakRef||Ht,na=new ap(t=>{t.exited||t.terminate()});function lp(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||tp(__dirname,"lib","worker.js"),o=new ep(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:rp(r).href,dataBuf:t[x].dataBuf,stateBuf:t[x].stateBuf,workerData:{$context:{threadStreamVersion:Qd},...n}}});return o.stream=new Ht(t),o.on("message",up),o.on("exit",oa),na.register(t,o),o}function sa(t){ip(!t[x].sync),t[x].needDrain&&(t[x].needDrain=!1,t.emit("drain"))}function ia(t){for(;;){let e=Atomics.load(t[x].state,Pe),r=t[x].data.length-e;if(r>0){if(t[x].bufLen===0){t[x].flushing=!1,t[x].ending?ss(t):t[x].needDrain&&process.nextTick(sa,t);return}la(t,r,ta);continue}if(r===0){if(e===0&&t[x].bufLen===0)return;Tr(t,()=>{t.destroyed||(ra(t),ia(t))});return}pe(t,new Error("overwritten"));return}}function up(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 cp(e),Tr(e,()=>{e[x].ready=!0,e.emit("ready")});break;case"ERROR":pe(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"){pe(e,new Error("this should not happen: "+t.code));break}let r=e[x].flushCallbacks.get(t.id);r&&(e[x].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:pe(e,new Error("this should not happen: "+t.code))}}function oa(t){let e=this.stream.deref();e!==void 0&&(na.unregister(e),e.worker.exited=!0,e.worker.off("exit",oa),pe(e,t!==0?new Error("the worker thread exited"):null))}var ts=class extends Zd{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[x]={},this[x].stateBuf=new SharedArrayBuffer(128),this[x].state=new Int32Array(this[x].stateBuf),this[x].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[x].data=Buffer.from(this[x].dataBuf),this[x].sync=e.sync||!1,this[x].ending=!1,this[x].ended=!1,this[x].needDrain=!1,this[x].destroyed=!1,this[x].flushing=!1,this[x].ready=!1,this[x].finished=!1,this[x].errored=null,this[x].closed=!1,this[x].buf=[],this[x].bufHead=0,this[x].bufLen=0,this[x].flushCallbacks=new Map,this[x].nextFlushId=0,this.worker=lp(this,e),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(e){let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(this[x].destroyed)return rs(this,new Error("the worker has exited")),!1;if(this[x].ending)return rs(this,new Error("the worker is ending")),!1;if(this[x].flushing&&this[x].bufLen+r.length>=op)try{es(this),this[x].flushing=!0}catch(n){return pe(this,n),!1}if(this[x].buf.push(r),this[x].bufLen+=r.length,this[x].sync)try{return es(this),!0}catch(n){return pe(this,n),!1}return this[x].flushing||(this[x].flushing=!0,setImmediate(ia,this)),this[x].needDrain=this[x].data.length-this[x].bufLen-Atomics.load(this[x].state,Pe)<=0,!this[x].needDrain}end(){this[x].destroyed||(this[x].ending=!0,ss(this))}flush(e){e=typeof e=="function"?e:ta,aa(this,r=>{if(r){process.nextTick(e,r);return}ca(this,e)})}flushSync(){this[x].destroyed||(es(this),ua(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[x].ready}get destroyed(){return this[x].destroyed}get closed(){return this[x].closed}get writable(){return!this[x].destroyed&&!this[x].ending}get writableEnded(){return this[x].ending}get writableFinished(){return this[x].finished}get writableNeedDrain(){return this[x].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[x].errored}};function aa(t,e){if(t[x].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[x].sync&&(t[x].flushing||t[x].bufLen>0)){setImmediate(aa,t,e);return}Tr(t,e)}function Tr(t,e){let r=Atomics.load(t[x].state,Pe);np(t[x].state,rt,r,1/0,(n,s)=>{if(n){pe(t,n),e(n);return}if(s!=="ok"){Tr(t,e);return}e()})}function ca(t,e){if(t[x].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[x].ready){let n=()=>{i(),ca(t,e)},s=()=>{i(),process.nextTick(e,new Error("the worker has exited"))},i=()=>{t.off("ready",n),t.off("close",s)};t.once("ready",n),t.once("close",s);return}let r=++t[x].nextFlushId;t[x].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[x].flushCallbacks.delete(r),pe(t,n),process.nextTick(e,n)}}function fp(t,e){let r=t[x].flushCallbacks;if(r.size===0)return;let n=e||new Error("the worker has exited");for(let s of r.values())process.nextTick(s,n);r.clear()}function rs(t,e){setImmediate(()=>{t.emit("error",e)})}function pe(t,e){t[x].destroyed||(t[x].destroyed=!0,fp(t,e),e&&(t[x].errored=e,rs(t,e)),t.worker.exited?setImmediate(()=>{t[x].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[x].closed=!0,t.emit("close")}))}function la(t,e,r){let s=Atomics.load(t[x].state,Pe),i=e;for(;i>0&&t[x].bufLen!==0;){let o=t[x].bufHead,a=t[x].buf[o];if(a.length<=i){a.copy(t[x].data,s),s+=a.length,i-=a.length,t[x].bufLen-=a.length,t[x].bufHead=o+1,t[x].bufHead===t[x].buf.length?(t[x].buf.length=0,t[x].bufHead=0):t[x].bufHead>=1024&&t[x].bufHead*2>=t[x].buf.length&&(t[x].buf.splice(0,t[x].bufHead),t[x].bufHead=0);continue}a.copy(t[x].data,s,0,i),t[x].buf[o]=a.subarray(i),t[x].bufLen-=i,s+=i,i=0}return ns(t,()=>{Atomics.store(t[x].state,Pe,s)}),r(),!0}function ss(t){if(!(t[x].ended||!t[x].ending||t[x].flushing)){t[x].ended=!0;try{t.flushSync();let e=Atomics.load(t[x].state,rt);ns(t,()=>{Atomics.store(t[x].state,Pe,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[x].state,rt,e,1e3),e=Atomics.load(t[x].state,rt),e===-2){pe(t,new Error("end() failed"));return}if(++r===10){pe(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[x].finished=!0,t.emit("finish")})}catch(e){pe(t,e)}}}function es(t){let e=()=>{t[x].ending?ss(t):t[x].needDrain&&process.nextTick(sa,t)};for(t[x].flushing=!1;t[x].bufLen!==0;){let r=Atomics.load(t[x].state,Pe),n=t[x].data.length-r;if(n===0){ua(t),ra(t);continue}else if(n<0)throw new Error("overwritten");la(t,n,e)}}function ua(t){if(t[x].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[x].state,Pe),r=0;for(;;){let n=Atomics.load(t[x].state,rt);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[x].state,rt,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}fa.exports=ts});var as=P(($b,ma)=>{"use strict";var{createRequire:dp}=require("module"),{existsSync:pp}=require("node:fs"),hp=Wn(),{join:is,isAbsolute:ha,sep:mp}=require("node:path"),{fileURLToPath:gp}=require("node:url"),yp=Jn(),os=Qn(),wp=da();function bp(t){os.register(t,kp),os.registerBeforeExit(t,Tp),t.on("close",function(){os.unregister(t)})}function vp(){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 Sp(t){let e=t.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!e)return t;let r=[],n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--require"||i==="-r"||i==="--import"){let o=e[s+1];if(o&&pa(o)){n=!0,s++;continue}r.push(i),o&&(r.push(o),s++);continue}if(i.startsWith("--require=")||i.startsWith("-r=")||i.startsWith("--import=")){let o=i.slice(i.indexOf("=")+1);if(pa(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function pa(t){let e=xp(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=gp(r)}catch{return!1}return ha(r)&&!pp(r)}function xp(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function _p(t,e,r,n,s){if(!r.execArgv&&vp()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let c=Sp(process.env.NODE_OPTIONS);c!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:c}})}r={...r,name:s};let i=new wp({filename:t,workerData:e,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&bp(i)}function a(){i.closed||(i.flushSync(),yp(100),i.end())}return i}function kp(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Tp(t){t.flushSync()}function Cp(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=hp(),sync:a=!1}=t,c={...t.options},l=typeof o=="string"?[o]:o,u=typeof globalThis=="object"&&Object.prototype.hasOwnProperty.call(globalThis,"__bundlerPathsOverrides")&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides=="object"?globalThis.__bundlerPathsOverrides:Object.create(null),d=t.target;if(d&&r)throw new Error("only one of target or targets can be specified");r?(d=u["pino-worker"]||is(__dirname,"worker.js"),c.targets=r.filter(f=>f.target).map(f=>({...f,target:h(f.target)})),c.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"]||is(__dirname,"worker.js"),c.pipelines=[e.map(f=>({...f,target:h(f.target)}))]),n&&(c.levels=n),s&&(c.dedupe=s),c.pinoWillSendConfig=!0;let p=r||e?"pino.transport":d;return _p(h(d),c,i,a,p);function h(f){if(f=u[f]||f,ha(f)||f.indexOf("file://")===0)return f;if(f==="pino/file")return is(__dirname,"..","file.js");let m;for(let g of l)try{let y=g==="node:repl"?process.cwd()+mp:g;m=dp(y).resolve(f);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${f}"`);return m}}ma.exports=Cp});var Ar=P((Ab,Aa)=>{"use strict";var $p=require("node:diagnostics_channel"),ga=Fo(),{mapHttpRequest:Ap,mapHttpResponse:Ep}=Hn(),ls=Wo(),ya=Qn(),{lsCacheSym:Op,chindingsSym:xa,writeSym:wa,serializersSym:_a,formatOptsSym:ba,endSym:Rp,stringifiersSym:ka,stringifySym:Ta,stringifySafeSym:us,wildcardFirstSym:Ca,nestedKeySym:Ip,formattersSym:$a,messageKeySym:Mp,errorKeySym:Pp,nestedKeyStrSym:jp,msgPrefixSym:Cr}=yt(),{isMainThread:Fp}=require("worker_threads"),Lp=as(),[Dp]=process.versions.node.split(".").map(t=>Number(t)),va=$p.tracingChannel("pino_asJson"),cs=Dp>=25?t=>JSON.stringify(t):Up;function bt(){}function Np(t,e){if(!e)return r;return function(...s){e.call(this,s,r,t)};function r(n,...s){if(typeof n=="object"){let i=n;n!==null&&(n.method&&n.headers&&n.socket?n=Ap(n):typeof n.setHeader=="function"&&(n=Ep(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Cr]=="string"&&i!==void 0&&i!==null&&(i=this[Cr]+i),this[wa](n,ga(i,o,this[ba]),t)}else{let i=n===void 0?s.shift():n;typeof this[Cr]=="string"&&i!==void 0&&i!==null&&(i=this[Cr]+i),this[wa](null,ga(i,s,this[ba]),t)}}}function Up(t){let e="",r=0,n=!1,s=255,i=t.length;if(i>100)return JSON.stringify(t);for(var o=0;o<i&&s>=32;o++)s=t.charCodeAt(o),(s===34||s===92)&&(e+=t.slice(r,o)+"\\",r=o,n=!0);return n?e+=t.slice(r):e=t,s<32?JSON.stringify(t):'"'+e+'"'}function qp(t,e,r,n){if(va.hasSubscribers===!1)return Sa.call(this,t,e,r,n);let s={instance:this,arguments};return va.traceSync(Sa,s,this,t,e,r,n)}function Sa(t,e,r,n){let s=this[Ta],i=this[us],o=this[ka],a=this[Rp],c=this[xa],l=this[_a],u=this[$a],d=this[Mp],p=this[Pp],h=this[Op][r]+n;h=h+c;let f;u.log&&(t=u.log(t));let m=o[Ca],g="";for(let b in t)if(f=t[b],Object.prototype.hasOwnProperty.call(t,b)&&f!==void 0){l[b]?f=l[b](f):b===p&&l.err&&(f=l.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||cs)(f);break;default:f=(w||s)(f,i)}if(f===void 0)continue;let v=cs(b);g+=","+v+":"+f}let y="";if(e!==void 0){f=l[d]?l[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||cs)(f),y=',"'+d+'":'+f;break;default:f=(b||s)(f,i),y=',"'+d+'":'+f}}return this[Ip]&&g?h+this[jp]+g.slice(1)+"}"+y+a:h+g+y+a}function Bp(t,e){let r,n=t[xa],s=t[Ta],i=t[us],o=t[ka],a=o[Ca],c=t[_a],l=t[$a].bindings;e=l(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=c[u]?c[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Hp(t){return t.write!==t.constructor.prototype.write}function $r(t){let e=new ls(t);return e.on("error",r),!t.sync&&Fp&&(ya.register(e,Wp),e.on("close",function(){ya.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=bt,e.end=bt,e.flushSync=bt,e.destroy=bt;return}e.removeListener("error",r),e.emit("error",n)}}function Wp(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Vp(t){return function(r,n,s={},i){if(typeof s=="string")i=$r({dest:s}),s={};else if(typeof i=="string"){if(s&&s.transport)throw Error("only one of option.transport or stream can be specified");i=$r({dest:i})}else if(s instanceof ls||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof ls||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let c;s.customLevels&&(c=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Lp({caller:n,...s.transport,levels:c})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=bt),i||(Hp(process.stdout)?i=process.stdout:i=$r({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function zp(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[us])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Kp(t,e,r){return{level:t,bindings:e,log:r}}function Gp(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Aa.exports={noop:bt,buildSafeSonicBoom:$r,asChindings:Bp,asJson:qp,genLog:Np,createArgsNormalizer:Vp,stringify:zp,buildFormatters:Kp,normalizeDestFileDescriptor:Gp}});var Er=P((Eb,Ea)=>{var Jp={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Yp={ASC:"ASC",DESC:"DESC"};Ea.exports={DEFAULT_LEVELS:Jp,SORTING_ORDER:Yp}});var ps=P((Ob,Ma)=>{"use strict";var{lsCacheSym:Xp,levelValSym:fs,useOnlyCustomLevelsSym:Qp,streamSym:Zp,formattersSym:eh,hooksSym:th,levelCompSym:Oa}=yt(),{noop:rh,genLog:nt}=Ar(),{DEFAULT_LEVELS:Ae,SORTING_ORDER:Ra}=Er(),Ia={fatal:t=>{let e=nt(Ae.fatal,t);return function(...r){let n=this[Zp];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>nt(Ae.error,t),warn:t=>nt(Ae.warn,t),info:t=>nt(Ae.info,t),debug:t=>nt(Ae.debug,t),trace:t=>nt(Ae.trace,t)},ds=Object.keys(Ae).reduce((t,e)=>(t[Ae[e]]=e,t),{}),nh=Object.keys(ds).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function sh(t){let e=t[eh].level,{labels:r}=t.levels,n={};for(let s in r){let i=e(r[s],Number(s));n[s]=JSON.stringify(i).slice(0,-1)}return t[Xp]=n,t}function ih(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 oh(t){let{labels:e,values:r}=this.levels;if(typeof t=="number"){if(e[t]===void 0)throw Error("unknown level value"+t);t=e[t]}if(r[t]===void 0)throw Error("unknown level "+t);let n=this[fs],s=this[fs]=r[t],i=this[Qp],o=this[Oa],a=this[th].logMethod;for(let c in r){if(o(r[c],s)===!1){this[c]=rh;continue}this[c]=ih(c,i)?Ia[c](a):nt(r[c],a)}this.emit("level-change",t,s,e[n],n,this)}function ah(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function ch(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Oa](r,this[fs])}function lh(t,e,r){return t===Ra.DESC?e<=r:e>=r}function uh(t){return typeof t=="string"?lh.bind(null,t):t}function fh(t=null,e=!1){let r=t?Object.keys(t).reduce((i,o)=>(i[t[o]]=o,i),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),e?null:ds,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:Ae,t);return{labels:n,values:s}}function dh(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(ds).map(i=>+i),1/0).includes(t))throw Error(`default level:${t} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:Ae,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function ph(t,e){let{labels:r,values:n}=t;for(let s in e){if(s in n)throw Error("levels cannot be overridden");if(e[s]in r)throw Error("pre-existing level values cannot be used for new levels")}}function hh(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Ra).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Ma.exports={initialLsCache:nh,genLsCache:sh,levelMethods:Ia,getLevel:ah,setLevel:oh,isLevelEnabled:ch,mappings:fh,assertNoLevelCollisions:ph,assertDefaultLevelFound:dh,genLevelComparison:uh,assertLevelComparison:hh}});var hs=P((Rb,Pa)=>{"use strict";Pa.exports={version:"10.3.1"}});var Ba=P((Mb,qa)=>{"use strict";var{EventEmitter:mh}=require("node:events"),{lsCacheSym:gh,levelValSym:yh,setLevelSym:gs,getLevelSym:ja,chindingsSym:Rr,mixinSym:wh,asJsonSym:La,writeSym:bh,mixinMergeStrategySym:vh,timeSym:Sh,timeSliceIndexSym:xh,streamSym:Da,serializersSym:st,formattersSym:Wt,errorKeySym:_h,messageKeySym:kh,useOnlyCustomLevelsSym:Th,needsMetadataGsym:Ch,redactFmtSym:$h,stringifySym:Ah,formatOptsSym:Eh,stringifiersSym:Oh,msgPrefixSym:ys,hooksSym:Rh}=yt(),{getLevel:Ih,setLevel:Mh,isLevelEnabled:Ph,mappings:jh,initialLsCache:Fh,genLsCache:Lh,assertNoLevelCollisions:Dh}=ps(),{asChindings:ws,asJson:Nh,buildFormatters:ms,stringify:Fa,noop:Na}=Ar(),{version:Uh}=hs(),qh=Kn(),Bh=class{},Ua={constructor:Bh,child:Hh,bindings:Wh,setBindings:Vh,flush:Gh,isLevelEnabled:Ph,version:Uh,get level(){return this[ja]()},set level(t){this[gs](t)},get levelVal(){return this[yh]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[ys]},get[Symbol.toStringTag](){return"Pino"},[gh]:Fh,[bh]:Kh,[La]:Nh,[ja]:Ih,[gs]:Mh};Object.setPrototypeOf(Ua,mh.prototype);qa.exports=function(){return Object.create(Ua)};var Or=t=>t;function Hh(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[st],n=this[Wt],s=Object.create(this);if(e==null)return s[Wt].bindings!==Or&&(s[Wt]=ms(n.level,Or,n.log)),s[Rr]=ws(s,t),this.onChild!==Na&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[st]=Object.create(null);for(let l in r)s[st][l]=r[l];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let l=a[i];s[st][l]=r[l]}for(let l in e.serializers)s[st][l]=e.serializers[l];let c=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<c.length;o++){let l=c[o];s[st][l]=e.serializers[l]}}else s[st]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:c,log:l}=e.formatters;s[Wt]=ms(a||n.level,c||Or,l||n.log)}else s[Wt]=ms(n.level,Or,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Dh(this.levels,e.customLevels),s.levels=jh(e.customLevels,s[Th]),Lh(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=qh(s.redact,Fa),c={stringify:a[$h]};s[Ah]=Fa,s[Oh]=a,s[Eh]=c}if(typeof e.msgPrefix=="string"&&(s[ys]=(this[ys]||"")+e.msgPrefix),s[Rr]=ws(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[gs](a)}return this.onChild(s),s}function Wh(){let e=`{${this[Rr].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Vh(t){let e=ws(this,t);this[Rr]=e}function zh(t,e){return Object.assign(e,t)}function Kh(t,e,r){let n=this[Sh](),s=this[wh],i=this[_h],o=this[kh],a=this[vh]||zh,c,l=this[Rh].streamWrite;t==null?c={}:t instanceof Error?(c={[i]:t},e===void 0&&(e=t.message)):(c=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(c=a(c,s(c,r,this)));let u=this[La](c,e,r,n),d=this[Da];d[Ch]===!0&&(d.lastLevel=r,d.lastObj=c,d.lastMsg=e,d.lastTime=n.slice(this[xh]),d.lastLogger=this),d.write(l?l(u):u)}function Gh(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Da];typeof e.flush=="function"?e.flush(t||Na):t&&t()}});var za=P((xs,Va)=>{"use strict";var{hasOwnProperty:Vt}=Object.prototype,ot=Ss();ot.configure=Ss;ot.stringify=ot;ot.default=ot;xs.stringify=ot;xs.configure=Ss;Va.exports=ot;var Jh=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function He(t){return t.length<5e3&&!Jh.test(t)?`"${t}"`:JSON.stringify(t)}function bs(t,e){if(t.length>200||e)return t.sort(e);for(let r=1;r<t.length;r++){let n=t[r],s=r;for(;s!==0&&t[s-1]>n;)t[s]=t[s-1],s--;t[s]=n}return t}var Yh=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function vs(t){return Yh.call(t)!==void 0&&t.length!==0}function Ha(t,e,r){t.length<r&&(r=t.length);let n=e===","?"":" ",s=`"0":${n}${t[0]}`;for(let i=1;i<r;i++)s+=`${e}"${i}":${n}${t[i]}`;return s}function Xh(t){if(Vt.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 Qh(t){let e;if(Vt.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 Zh(t,e){let r;if(Vt.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 Wa(t,e){let r;if(Vt.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 it(t){return t===1?"1 item":`${t} items`}function em(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function tm(t){if(Vt.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function Ss(t){t={...t};let e=tm(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=Xh(t),n=Zh(t,"bigint"),s=Qh(t),i=typeof s=="function"?s:void 0,o=Wa(t,"maximumDepth"),a=Wa(t,"maximumBreadth");function c(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 He(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return r;let v="",_=",",C=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(w),y!==""&&(b+=y,v+=`
|
|
26
|
+
${b}`,_=`,
|
|
27
|
+
${b}`);let U=Math.min(w.length,a),W=0;for(;W<U-1;W++){let J=c(String(W),w,m,g,y,b);v+=J!==void 0?J:"null",v+=_}let ee=c(String(W),w,m,g,y,b);if(v+=ee!==void 0?ee:"null",w.length-1>a){let J=w.length-a-1;v+=`${_}"... ${it(J)} not stringified"`}return y!==""&&(v+=`
|
|
28
|
+
${C}`),m.pop(),`[${v}]`}let A=Object.keys(w),E=A.length;if(E===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",F="";y!==""&&(b+=y,_=`,
|
|
29
|
+
${b}`,$=" ");let q=Math.min(E,a);s&&!vs(w)&&(A=bs(A,i)),m.push(w);for(let U=0;U<q;U++){let W=A[U],ee=c(W,w,m,g,y,b);ee!==void 0&&(v+=`${F}${He(W)}:${$}${ee}`,F=_)}if(E>a){let U=E-a;v+=`${F}"...":${$}"${it(U)} not stringified"`,F=_}return y!==""&&F.length>1&&(v=`
|
|
30
|
+
${b}${v}
|
|
31
|
+
${C}`),m.pop(),`{${v}}`}case"number":return isFinite(w)?String(w):e?e(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return e?e(w):void 0}}function l(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 He(f);case"object":{if(f===null)return"null";if(m.indexOf(f)!==-1)return r;let w=b,v="",_=",";if(Array.isArray(f)){if(f.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(f),y!==""&&(b+=y,v+=`
|
|
32
|
+
${b}`,_=`,
|
|
33
|
+
${b}`);let E=Math.min(f.length,a),$=0;for(;$<E-1;$++){let q=l(String($),f[$],m,g,y,b);v+=q!==void 0?q:"null",v+=_}let F=l(String($),f[$],m,g,y,b);if(v+=F!==void 0?F:"null",f.length-1>a){let q=f.length-a-1;v+=`${_}"... ${it(q)} not stringified"`}return y!==""&&(v+=`
|
|
34
|
+
${w}`),m.pop(),`[${v}]`}m.push(f);let C="";y!==""&&(b+=y,_=`,
|
|
35
|
+
${b}`,C=" ");let A="";for(let E of g){let $=l(E,f[E],m,g,y,b);$!==void 0&&(v+=`${A}${He(E)}:${C}${$}`,A=_)}return y!==""&&A.length>1&&(v=`
|
|
36
|
+
${b}${v}
|
|
37
|
+
${w}`),m.pop(),`{${v}}`}case"number":return isFinite(f)?String(f):e?e(f):"null";case"boolean":return f===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(f);default:return e?e(f):void 0}}function u(h,f,m,g,y){switch(typeof f){case"string":return He(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
|
+
${y}`,F=`,
|
|
39
|
+
${y}`,q=Math.min(f.length,a),U=0;for(;U<q-1;U++){let ee=u(String(U),f[U],m,g,y);$+=ee!==void 0?ee:"null",$+=F}let W=u(String(U),f[U],m,g,y);if($+=W!==void 0?W:"null",f.length-1>a){let ee=f.length-a-1;$+=`${F}"... ${it(ee)} not stringified"`}return $+=`
|
|
40
|
+
${b}`,m.pop(),`[${$}]`}let w=Object.keys(f),v=w.length;if(v===0)return"{}";if(o<m.length+1)return'"[Object]"';y+=g;let _=`,
|
|
41
|
+
${y}`,C="",A="",E=Math.min(v,a);vs(f)&&(C+=Ha(f,_,a),w=w.slice(f.length),E-=f.length,A=_),s&&(w=bs(w,i)),m.push(f);for(let $=0;$<E;$++){let F=w[$],q=u(F,f[F],m,g,y);q!==void 0&&(C+=`${A}${He(F)}: ${q}`,A=_)}if(v>a){let $=v-a;C+=`${A}"...": "${it($)} not stringified"`,A=_}return A!==""&&(C=`
|
|
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(n)return String(f);default:return e?e(f):void 0}}function d(h,f,m){switch(typeof f){case"string":return He(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+=`,"... ${it($)} 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 v="",_=Math.min(w,a);y&&vs(f)&&(g+=Ha(f,",",a),b=b.slice(f.length),_-=f.length,v=","),s&&(b=bs(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+=`${v}${He(A)}:${E}`,v=",")}if(w>a){let C=w-a;g+=`${v}"...":"${it(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(n)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 c("",{"":h},[],f,g,"");if(Array.isArray(f))return l("",h,[],em(f),g,"")}if(g.length!==0)return u("",h,[],g,"")}return d("",h,[])}return p}});var Ya=P((Pb,Ja)=>{"use strict";var _s=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Ga}=Er(),rm=Ga.info;function nm(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Ga);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:c,emit:i,flushSync:o,end:l,minLevel:0,lastId:0,streams:[],clone:u,[_s]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let p,h=this.lastLevel,{streams:f}=this,m=0,g;for(let y=sm(f.length,e.dedupe);om(y,f.length,e.dedupe);y=im(y,e.dedupe))if(p=f[y],p.level<=h){if(m!==0&&m!==p.level)break;if(g=p.stream,g[_s]){let{lastTime:b,lastMsg:w,lastObj:v,lastLogger:_}=this;g.lastLevel=h,g.lastTime=b,g.lastMsg=w,g.lastObj=v,g.lastLogger=_}g.write(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 n;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=rm;let y={stream:h,level:g,levelVal:void 0,id:++n.lastId};return f.unshift(y),f.sort(Ka),this.minLevel=f[0].level,n}function c(d){let{streams:p}=this,h=p.findIndex(f=>f.id===d);return h>=0&&(p.splice(h,1),p.sort(Ka),this.minLevel=p.length>0?p[0].level:-1),n}function l(){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:s,add:a,remove:c,minLevel:d,streams:p,clone:u,emit:i,flushSync:o,[_s]:!0}}}function Ka(t,e){return t.level-e.level}function sm(t,e){return e?t-1:0}function im(t,e){return e?t-1:t+1}function om(t,e,r){return r?t>=0:t<e}Ja.exports=nm});var uc=P((jb,he)=>{"use strict";var am=require("node:os"),sc=Hn(),cm=Wn(),lm=Kn(),ic=Po(),um=Ba(),oc=yt(),{configure:fm}=za(),{assertDefaultLevelFound:dm,mappings:ac,genLsCache:pm,genLevelComparison:hm,assertLevelComparison:mm}=ps(),{DEFAULT_LEVELS:cc,SORTING_ORDER:gm}=Er(),{createArgsNormalizer:ym,asChindings:wm,buildSafeSonicBoom:Xa,buildFormatters:bm,stringify:ks,normalizeDestFileDescriptor:Qa,noop:vm}=Ar(),{version:Sm}=hs(),{chindingsSym:Za,redactFmtSym:xm,serializersSym:ec,timeSym:_m,timeSliceIndexSym:km,streamSym:Tm,stringifySym:tc,stringifySafeSym:Ts,stringifiersSym:rc,setLevelSym:Cm,endSym:$m,formatOptsSym:Am,messageKeySym:Em,errorKeySym:Om,nestedKeySym:Rm,mixinSym:Im,levelCompSym:Mm,useOnlyCustomLevelsSym:Pm,formattersSym:nc,hooksSym:jm,nestedKeyStrSym:Fm,mixinMergeStrategySym:Lm,msgPrefixSym:Dm}=oc,{epochTime:lc,nullTime:Nm}=ic,{pid:Um}=process,qm=am.hostname(),Bm=sc.err,Hm={level:"info",levelComparison:gm.ASC,levels:cc,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Um,hostname:qm},serializers:Object.assign(Object.create(null),{err:Bm}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:lc,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Wm=ym(Hm),Vm=Object.assign(Object.create(null),sc);function Cs(...t){let e={},{opts:r,stream:n}=Wm(e,cm(),...t);r.level&&typeof r.level=="string"&&cc[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:c,errorKey:l,nestedKey:u,base:d,name:p,level:h,customLevels:f,levelComparison:m,mixin:g,mixinMergeStrategy:y,useOnlyCustomLevels:b,formatters:w,hooks:v,depthLimit:_,edgeLimit:C,onChild:A,msgPrefix:E}=r,$=fm({maximumDepth:_,maximumBreadth:C}),F=bm(w.level,w.bindings,w.log),q=ks.bind({[Ts]:$}),U=s?lm(s,q):{},W=s?{stringify:U[xm]}:{stringify:q},ee="}"+(i?`\r
|
|
44
|
+
`:`
|
|
45
|
+
`),J=wm.bind(null,{[Za]:"",[ec]:o,[rc]:U,[tc]:ks,[Ts]:$,[nc]:F}),se="";d!==null&&(p===void 0?se=J(d):se=J(Object.assign({},d,{name:p})));let I=a instanceof Function?a:a?lc:Nm,L=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"`);dm(h,f,b);let ve=ac(f,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:ve,messageKey:c,errorKey:l}}),mm(m);let Dt=hm(m);return Object.assign(e,{levels:ve,[Mm]:Dt,[Pm]:b,[Tm]:n,[_m]:I,[km]:L,[tc]:ks,[Ts]:$,[rc]:U,[$m]:ee,[Am]:W,[Em]:c,[Om]:l,[Rm]:u,[Fm]:u?`,${JSON.stringify(u)}:{`:"",[ec]:o,[Im]:g,[Lm]:y,[Za]:se,[nc]:F,[jm]:v,silent:vm,onChild:A,[Dm]:E}),Object.setPrototypeOf(e,um()),pm(e),e[Cm](h),e}he.exports=Cs;he.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=Qa(t.dest||process.stdout.fd),Xa(t)):Xa({dest:Qa(t),minLength:0});he.exports.transport=as();he.exports.multistream=Ya();he.exports.levels=ac();he.exports.stdSerializers=Vm;he.exports.stdTimeFunctions=Object.assign({},ic);he.exports.symbols=oc;he.exports.version=Sm;he.exports.default=Cs;he.exports.pino=Cs});var mn=T(require("os")),lr=T(require("fs")),Nt=T(require("path"));function Uu(){let t=[Nt.resolve(__dirname,"..","package.json"),Nt.resolve(__dirname,"..","..","package.json"),Nt.resolve(process.cwd(),"package.json")];for(let e of t)try{if(lr.existsSync(e)){let r=JSON.parse(lr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var gn=Uu(),Ut=process.stdout.isTTY===!0,_i=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb",ki=process.stdout.columns||100;Ut&&process.stdout.on("resize",()=>{ki=process.stdout.columns||100});var qe=()=>Math.min(Math.max(ki-4,56),100);function Y(t,e){return!Ut||_i?t:`\x1B[${e}m${t}\x1B[0m`}var S={strong:t=>Y(t,"1;38;5;255"),muted:t=>Y(t,"38;5;241"),dim:t=>Y(t,"2;38;5;245"),border:t=>Y(t,"38;5;237"),accent:t=>Y(t,"38;5;147"),primary:t=>Y(t,"38;5;253"),secondary:t=>Y(t,"38;5;247"),info:t=>Y(t,"38;5;110"),success:t=>Y(t,"38;5;114"),warning:t=>Y(t,"38;5;179"),error:t=>Y(t,"38;5;167"),plan:t=>Y(t,"38;5;144"),code:t=>Y(t,"38;5;189"),codeLang:t=>Y(t,"38;5;110"),linenum:t=>Y(t,"38;5;239"),diffAdd:t=>Y(t,"38;5;71"),diffDel:t=>Y(t,"38;5;131"),link:t=>Y(t,"4;38;5;110")};function $e(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function qu(t,e){let r=$e(t);return t+" ".repeat(Math.max(0,e-r.length))}function hn(t,e=2,r){let n=(r??qe())-e,s=t.split(/(?<=\s)|(?=\s)/).filter(Boolean),i=[],o="";for(let a of s){let c=$e(o),l=$e(a.trimStart());c.trimEnd().length+1+l.length>n&&c.trim()?(i.push(" ".repeat(e)+o.trimStart()),o=a.trimStart()):o+=a}return o.trim()&&i.push(" ".repeat(e)+o.trimStart()),i.length?i:[""]}function Bu(t,e="\u2500"){return S.border(e.repeat(Math.max(0,t)))}function vi(t,e,r){let n=$e(t),s=Math.max(0,Math.floor((r-2-n.length)/2)),i=Math.max(0,r-2-n.length-s);return S.border("\u2502")+" ".repeat(s)+e+" ".repeat(i)+S.border("\u2502")}function cr(t,e,r){let n=$e(t),s=$e(e),i=Math.max(1,r-4-n.length-s.length);return`${S.border("\u2502")} ${t}${" ".repeat(i)}${e} ${S.border("\u2502")}`}function Si(t){return`${S.border("\u2502")}${" ".repeat(t-2)}${S.border("\u2502")}`}function Ti(t,e){let r=Math.min(qe(),76),n=e.replace(mn.homedir(),"~"),s=t.length>42?t.slice(0,40)+"\u2026":t,i=n.length>42?"\u2026"+n.slice(-40):n,o=S.border("\u256D"+"\u2500".repeat(r-2)+"\u256E"),a=S.border("\u2570"+"\u2500".repeat(r-2)+"\u256F"),c=S.border("\u251C"+"\u2500".repeat(r-2)+"\u2524"),l=S.border("\u255E"+"\u2550".repeat(r-2)+"\u2561");return["",o,Si(r),vi(" HABLAS "," "+S.accent("\u25C6")+" "+S.strong("HABLAS")+" ",r),vi("engineering runtime",S.dim("engineering runtime"),r),Si(r),l,cr(S.secondary("model "),S.accent(s),r),cr(S.secondary("workspace"),S.muted(i),r),cr(S.secondary("version "),S.muted("v"+gn),r),c,cr(S.dim("Type naturally \xB7 /help for commands \xB7 Ctrl+C to cancel"),"",r),a,""].join(`
|
|
46
|
+
`)}function Ci(t){let e=qe(),r=" "+S.accent("\u25C6")+" "+S.strong("Turn")+" "+S.muted(String(t))+" ",n=" \u25C6 Turn "+t+" ",s=Math.max(0,e-n.length-2);return`
|
|
47
|
+
`+S.border("\u2500\u2500")+r+S.border("\u2500".repeat(s))}function ur(){return`
|
|
48
|
+
`+S.accent("\u25C6")+" "+S.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 $i(t){let e=Hu[t]??"\u25CF";return`
|
|
49
|
+
`+S.muted("\u2504")+" "+S.accent(e)+" "+S.secondary(t)+" "+S.muted("\u2504")}var Wu={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 Ai(t,e){let r=Wu[t]??"\xB7",n=t.replace(/_/g," "),s=Math.min(qe()-4,76),i=r+" "+S.secondary(n),o=e?S.dim(e.slice(0,40)):"",a=$e(i)+(o?" "+e.slice(0,40):""),c=Math.max(0,s-2-a.length),l=" "+S.border("\u256D"+"\u2500".repeat(s)+"\u256E"),u=" "+S.border("\u2502")+" "+i+(o?" "+o:"")+" ".repeat(c)+" "+S.border("\u2502");return`
|
|
7
50
|
`+l+`
|
|
8
|
-
`+u}function
|
|
9
|
-
`+
|
|
10
|
-
`).filter(
|
|
11
|
-
`),
|
|
12
|
-
`+
|
|
51
|
+
`+u}function Ei(t,e,r){let n=Math.min(qe()-4,76),s=r>=1e3?(r/1e3).toFixed(1)+"s":r+"ms",i=t?S.success("\u2713"):S.error("\u2717"),o=Vu(e),a=i+" "+S.dim(s)+(o?" "+o:""),c=$e(a),l=Math.max(0,n-2-c.length),u=" "+S.border("\u2502")+" "+a+" ".repeat(l)+" "+S.border("\u2502"),d=" "+S.border("\u2570"+"\u2500".repeat(n)+"\u256F");return u+`
|
|
52
|
+
`+d}function Vu(t){if(!t?.trim())return"";let e=t.split(`
|
|
53
|
+
`).filter(n=>n.trim());if(e.length>6)return S.dim(e.length+" lines");let r=e.join(" ").replace(/\s+/g," ").trim();return r.length<=55?S.dim(r):S.dim(r.slice(0,52)+"\u2026")}function Ue(t){return t.replace(/\*\*([^*\n]+)\*\*/g,(e,r)=>S.strong(r)).replace(/__([^_\n]+)__/g,(e,r)=>S.strong(r)).replace(/\*([^*\n]+)\*/g,(e,r)=>S.accent(r)).replace(/_([^_\n]+)_/g,(e,r)=>S.accent(r)).replace(/`([^`\n]+)`/g,(e,r)=>S.code(r)).replace(/~~([^~\n]+)~~/g,(e,r)=>S.muted(r)).replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,(e,r,n)=>S.link(r)+S.muted(" ("+n+")"))}function zu(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)),n=Array(r).fill(4);for(let o of e)for(let a=0;a<o.length;a++)n[a]=Math.max(n[a],$e(o[a]).length+2);let s=S.border(" \u251C"+n.map(o=>"\u2500".repeat(o+2)).join("\u253C")+"\u2524"),i=[];return e.forEach((o,a)=>{let c=Array(r).fill("").map((u,d)=>{let p=Ue(o[d]??"");return" "+qu(p,n[d])+" "}),l=S.border(" \u2502")+c.join(S.border("\u2502"))+S.border("\u2502");i.push(l),a===0&&i.push(s)}),i}function Ku(t,e){let r=Math.max(28,qe()-8),n=String(t.length).length,s=[],i=e?" "+S.codeLang(e):"";s.push(" "+S.border("\u256D"+"\u2500".repeat(r))+i);for(let o=0;o<t.length;o++){let a=S.linenum(String(o+1).padStart(n)),c=Gu(t[o],e);s.push(" "+S.border("\u2502")+" "+a+" "+S.border("\u2502")+" "+c)}return s.push(" "+S.border("\u2570"+"\u2500".repeat(r))),s}function Gu(t,e){if(!Ut||_i)return t;let r=e.toLowerCase();return["sh","bash","zsh","shell"].includes(r)?/^\s*#/.test(t)?S.muted(t):t.replace(/^(\s*)(export|cd|echo|npm|npx|git|node|python|pip|mkdir|rm|cp|mv|ls|cat|grep|sed|awk)(\s)/,(n,s,i,o)=>s+S.accent(i)+o).replace(/(['"`])([^'"` ]*)\1/g,(n,s,i)=>S.warning(s+i+s)):["ts","tsx","js","jsx","typescript","javascript"].includes(r)?/^\s*\/\//.test(t)||/^\s*\/\*/.test(t)?S.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,n=>S.accent(n)).replace(/(['"`])([^'"` ]*)\1/g,(n,s,i)=>S.warning(s+i+s)):["py","python"].includes(r)?/^\s*#/.test(t)?S.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,n=>S.accent(n)).replace(/(['"`]{1,3})([^'"` ]*?)\1/g,n=>S.warning(n)):["json","jsonc"].includes(r)?t.replace(/"([^"]+)"(\s*:)/g,(n,s,i)=>S.info('"'+s+'"')+S.border(i)).replace(/:\s*"([^"]+)"/g,(n,s)=>": "+S.warning('"'+s+'"')).replace(/:\s*(true|false|null)/g,(n,s)=>": "+S.accent(s)).replace(/:\s*(-?\d+(\.\d+)?)/g,(n,s)=>": "+S.success(s)):S.code(t)}function fr(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=[],n=!1,s="",i=[],o=[],a=()=>{i.length&&(r.push(...Ku(i,s)),i=[],s="")},c=()=>{o.length&&(r.push(...zu(o)),o=[])},l=u=>/^\s*\|.+\|/.test(u)||/^\s*[-:]+[-:\s|]+$/.test(u);for(let u of e){let d=u.trimStart();if(d.startsWith("```")){c(),n?(a(),n=!1,s=""):(n=!0,s=d.slice(3).trim());continue}if(n){i.push(u);continue}if(l(u)){o.push(u);continue}if(c(),!u.trim()){r.push("");continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(d)){r.push(" "+Bu(Math.min(qe()-4,56)));continue}let p=/^#\s+(.+)/.exec(d);if(p){r.push(""),r.push(" "+S.strong(Ue(p[1]))),r.push(" "+S.border("\u2500".repeat(Math.min($e(p[1]).length+2,qe()-4))));continue}let h=/^##\s+(.+)/.exec(d);if(h){r.push(""),r.push(" "+S.accent("\u25C6")+" "+S.strong(Ue(h[1])));continue}let f=/^###\s+(.+)/.exec(d);if(f){r.push(""),r.push(" "+S.secondary("\u25C7")+" "+S.primary(Ue(f[1])));continue}let m=/^(\s*)([-*•+])\s+(.+)/.exec(u);if(m){let b=m[1].length,w=Ue(m[3]),v=b>0?S.muted("\u25E6"):S.accent("\xB7"),_=hn(w,b+4);r.push(" ".repeat(b+2)+v+" "+(_[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=S.accent(g[2]+"."),v=Ue(g[3]),_=hn(v,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(" "+S.border("\u258C")+" "+S.secondary(Ue(y[1])));continue}if(/^\+(?!\+\+)/.test(d)){r.push(" "+S.diffAdd(u));continue}if(/^-(?!--)/.test(d)){r.push(" "+S.diffDel(u));continue}r.push(...hn(Ue(u),2))}return c(),n&&a(),`
|
|
55
|
+
`+r.join(`
|
|
13
56
|
`)+`
|
|
14
|
-
`}function
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function
|
|
17
|
-
`)}function
|
|
18
|
-
`+
|
|
19
|
-
`}function
|
|
20
|
-
`+
|
|
21
|
-
`}function
|
|
22
|
-
`);let
|
|
57
|
+
`}function Oi(){let t=(e,r)=>" "+S.accent(e.padEnd(20))+" "+S.muted(r);return[""," "+S.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("/mcp","list/trust/reload MCP servers (~/.hablas/mcp.json)"),t("/doctor","run diagnostics"),t("/version","show version"),t("/about","product identity"),t("/exit","quit"),""," "+S.secondary("Tips")," "+S.muted("Ctrl+C cancels current work. Ctrl+C twice exits.")," "+S.muted("Hablas reads Arabic, English, and mixed input."),""].join(`
|
|
58
|
+
`)}function Ri(t){let e=t.workingDir.replace(mn.homedir(),"~"),r=t.connected?S.success("online"):S.warning("offline"),n=[["model",S.accent(t.model)],["provider",S.primary(t.provider)],["connection",r],["workspace",S.muted(e)],["messages",S.muted(String(t.messageCount))],["tokens (est)",S.muted(t.totalTokens.toLocaleString())]];return[""," "+S.strong("Runtime Status"),"",...n.map(([s,i])=>" "+S.secondary(s.padEnd(14))+" "+i),""].join(`
|
|
59
|
+
`)}function Ii(){return[""," "+S.strong("Hablas")+" "+S.dim("v"+gn)," "+S.muted("Single-agent engineering runtime for the terminal."),""," "+S.secondary("Built by")+" "+S.primary("Abdulmoin Hablas")," "+S.link("https://portfolio-monopoly63s-projects.vercel.app/"),""," "+S.secondary("Philosophy")," "+S.muted("One agent. One conversation. Real execution."),""].join(`
|
|
60
|
+
`)}function Mi(){return`
|
|
61
|
+
`+S.strong("hablas")+" "+S.accent("v"+gn)+`
|
|
62
|
+
`}function Ie(t){return`
|
|
63
|
+
`+S.error("\u2717")+" "+S.primary(t)+`
|
|
64
|
+
`}function V(t){return" "+S.warning("\u26A0")+" "+S.secondary(t)}function oe(t){return" "+S.success("\u2713")+" "+S.primary(t)}function D(t){return" "+S.muted("\xB7")+" "+S.secondary(t)}var xi=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Qe=class{frame=0;timer;active=!1;label;constructor(e){this.label=e}setLabel(e){this.label=e}start(){!Ut||this.active||(this.active=!0,this.frame=0,this.timer=setInterval(()=>{let e=Y(xi[this.frame++%xi.length],"38;5;147");process.stdout.write("\r "+e+" "+S.muted(this.label)+"\x1B[K")},80))}stop(){this.active&&(this.active=!1,this.timer&&(clearInterval(this.timer),this.timer=void 0),Ut&&process.stdout.write("\r\x1B[K"))}};var yn=null;function ji(t){yn=t}function Fi(){try{yn?.stop()}catch{}yn=null}function Pi(t,e){Fi(),process.stdout.write(`
|
|
65
|
+
`);let r=e instanceof Error?e.message:String(e);console.error(Ie(`[${t}] ${r}`)),process.env.HABLAS_DEBUG&&e instanceof Error&&e.stack&&console.error(`
|
|
23
66
|
`+e.stack.split(`
|
|
24
67
|
`).slice(1,5).join(`
|
|
25
|
-
`))}function
|
|
26
|
-
`),console.log(
|
|
27
|
-
`);
|
|
28
|
-
`);u=
|
|
29
|
-
`);a=u.pop()||"";for(let
|
|
30
|
-
`),
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
`)
|
|
68
|
+
`))}function Li(){process.on("uncaughtException",t=>{Pi("Uncaught Error",t),process.exit(1)}),process.on("unhandledRejection",t=>{Pi("Unhandled Promise",t),process.exit(1)}),process.on("SIGTERM",()=>{Fi(),process.stdout.write(`
|
|
69
|
+
`),console.log(V("Received SIGTERM \u2014 shutting down gracefully.")),process.exit(0)})}var Yi=T(Ji(),1),{program:Vw,createCommand:zw,createArgument:Kw,createOption:Gw,CommanderError:Jw,InvalidArgumentError:Yw,InvalidOptionArgumentError:Xw,Command:Xi,Argument:Qw,Option:Zw,Help:eb}=Yi.default;var Se=T(require("fs")),et=T(require("path")),Qi=T(require("os"));var mt={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}},de={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"]},Ze={name:"Mistral AI",apiUrl:"https://api.mistral.ai/v1",defaultModel:"mistral-code-agent-latest",models:["mistral-code-agent-latest","mistral-large-latest","mistral-medium-latest","mistral-small-latest","codestral-latest"]};var gt=et.join(Qi.homedir(),".hablas"),Mn=et.join(gt,"config.json");function tt(t={}){let e={};if(Se.existsSync(Mn))try{e=JSON.parse(Se.readFileSync(Mn,"utf-8"))}catch{}let r={...mt,...e,tools:{...mt.tools,...e.tools||{},runCommand:{...mt.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...mt.workspace,...e.workspace||{}},vision:{...mt.vision,...e.vision||{}}};if(process.env.HABLAS_API_URL&&(r.apiUrl=process.env.HABLAS_API_URL),process.env.HABLAS_API_KEY&&(r.apiKey=process.env.HABLAS_API_KEY),process.env.HABLAS_MODEL&&(r.model=process.env.HABLAS_MODEL),process.env.HABLAS_VISION_PRIMARY&&(r.vision.primaryModel=process.env.HABLAS_VISION_PRIMARY),process.env.HABLAS_VISION_FALLBACK&&(r.vision.fallbackModel=process.env.HABLAS_VISION_FALLBACK),process.env.HABLAS_VISION_DISABLED==="true"&&(r.vision.enabled=!1),process.env.HABLAS_PROVIDER){let n=process.env.HABLAS_PROVIDER;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}if(t.model&&(r.model=t.model),t.host&&(r.ollamaHost=t.host),t.project&&(r.workingDirectory=et.resolve(t.project)),t.provider){let n=t.provider;(n==="ollama"||n==="custom"||n==="nvidia")&&(r.provider=n)}return t.apiUrl&&(r.apiUrl=t.apiUrl),t.apiKey&&(r.apiKey=t.apiKey),r.apiUrl&&r.provider==="ollama"&&(r.provider="custom"),r}function Be(t){Se.existsSync(gt)||Se.mkdirSync(gt,{recursive:!0}),Se.writeFileSync(Mn,JSON.stringify(t,null,2),"utf-8")}function Zi(){let t=[gt,et.join(gt,"logs"),et.join(gt,"backup")];for(let e of t)Se.existsSync(e)||Se.mkdirSync(e,{recursive:!0})}var $s=T(uc()),As=T(require("path")),fc=T(require("os")),Ir=T(require("fs"));function Es(t){let e=As.join(fc.homedir(),".hablas","logs");Ir.existsSync(e)||Ir.mkdirSync(e,{recursive:!0});let r=As.join(e,`session-${Date.now()}.log`);return(0,$s.default)({level:"info"},$s.default.destination({dest:r,sync:!1}))}var Mr=T(require("fs")),zt=T(require("path"));function vt(){let t=[zt.resolve(__dirname,"..","package.json"),zt.resolve(__dirname,"..","..","package.json"),zt.resolve(process.cwd(),"package.json"),zt.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Mr.existsSync(e)){let r=JSON.parse(Mr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var gu=T(require("fs")),yu=T(require("path"));var Pr=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${c}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:c}=await s.read();if(a)break;o+=i.decode(c,{stream:!0});let l=o.split(`
|
|
70
|
+
`);o=l.pop()||"";for(let u of l)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var zm={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}},Os=[{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}],Km=[{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 me(t,e){let r=t instanceof Error?t.message:String(t),n=/API error: (\d{3})/.exec(r);if(n){let i=parseInt(n[1],10),o=zm[i];if(e){for(let a of Os)if(a.test(e))return{message:a.message,retryable:a.retryable,fatal:a.fatal,status:i}}for(let a of Os)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 Km)if(i.test(r))return{message:i.message,retryable:i.retryable,fatal:!1};let s=r+(e||"");for(let i of Os)if(i.test(s))return{message:i.message,retryable:i.retryable,fatal:i.fatal};return{message:r.length>120?r.slice(0,120)+"...":r,retryable:!1,fatal:!1}}function j(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}var Rs=12e4,Gm=6e4,jr=3,dc=1e3,Jm=15e3,Ym=6e4,Xm=20;function Is(t){return t.map(e=>{if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0){let r=e.tool_calls.filter(n=>n?.function?.name);if(r.length>0)return{role:"assistant",content:e.content||null,tool_calls:r.map((n,s)=>({id:`call_${s}`,type:"function",function:{name:n.function?.name||"",arguments:JSON.stringify(n.function?.arguments||{})}}))}}return e.role==="tool"?{role:"tool",content:e.content,tool_call_id:"call_0"}:{role:e.role,content:e.content}})}function pc(t){return t.map(e=>({type:"function",function:e.function}))}function hc(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 mc(t){return new Promise(e=>setTimeout(e,t))}function gc(t,e){return t?.name==="AbortError"?!1:e?me(new Error(`API error: ${e}`)).retryable:me(t).retryable}function yc(t,e){return me(t,e).message}function Qm(t,e){return me(t,e).fatal}var St=class{apiUrl;apiKey;model;constructor(e){this.apiUrl=e.apiUrl||"https://api.openai.com/v1",this.apiKey=e.apiKey,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}setApiUrl(e){this.apiUrl=e}getApiUrl(){return this.apiUrl}setApiKey(e){this.apiKey=e}async checkConnection(){try{let e=this.apiUrl.replace(/\/+$/,"")+"/models";return(await fetch(e,{headers:this.getHeaders(),signal:AbortSignal.timeout(15e3)})).ok}catch{return!1}}async listModels(){try{let e=[],r=!0,n,s=0;for(;r&&s<Xm;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let c=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Gm)});if(!c.ok)break;let l=await c.json();if(Array.isArray(l))e.push(...l.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(l.data&&Array.isArray(l.data)){let u=l.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),l.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else l.models&&Array.isArray(l.models)&&e.push(...l.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,n,s){let i=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",o={model:this.model,messages:Is(e),stream:!0};r.length>0&&(o.tools=pc(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:s||AbortSignal.timeout(Rs)})}catch{return await this.chatWithTools(e,r,s)}if(!a.ok){let f=await a.text().catch(()=>"");throw new Error(`API error: ${a.status} ${a.statusText} \u2014 ${f}`)}let c=a.body?.getReader();if(!c)return await this.chatWithTools(e,r,s);let l=new TextDecoder,u="",d="",p=[];for(;;){let{done:f,value:m}=await c.read();if(f)break;u+=l.decode(m,{stream:!0});let g=u.split(`
|
|
71
|
+
`);u=g.pop()||"";for(let y of g){let b=y.trim();if(!(!b||b==="data: [DONE]")&&b.startsWith("data: "))try{let v=JSON.parse(b.slice(6)).choices?.[0]?.delta;if(!v)continue;if(v.content&&(d+=v.content,n?.(v.content)),v.tool_calls)for(let _ of v.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?hc(p):void 0;return{message:{role:"assistant",content:d,tool_calls:h},done:!0,done_reason:h?"tool_calls":"stop"}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:Is(e)};r.length>0&&(i.tools=pc(r),i.tool_choice="auto");let o=null;for(let a=0;a<=jr;a++)try{let c=new AbortController,l=setTimeout(()=>c.abort(),Rs),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||c.signal};try{let d=await fetch(s,u);if(clearTimeout(l),!d.ok){let m=await d.text().catch(()=>"");if(Qm(null,m)||!gc(null,d.status))throw new Error(yc(new Error(`API error: ${d.status}`),m));if(o=new Error(yc(new Error(`API error: ${d.status}`),m)),a<jr){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(Jm*Math.pow(2,a),Ym);else y=dc*Math.pow(2,a);await mc(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?hc(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(l),d instanceof Error&&d.name==="AbortError"&&n?.aborted)throw d;if(gc(d)&&(o=d instanceof Error?d:new Error(j(d)),a<jr)){let p=dc*Math.pow(2,a);await mc(p);continue}throw d}}catch(c){if(c instanceof Error&&c.name==="AbortError")throw c;if(o=c instanceof Error?c:new Error(j(c)),a>=jr)throw o}throw o||new Error("Request failed after retries")}async*streamChat(e,r){let n=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify({model:this.model,messages:Is(e),stream:!0}),signal:r||AbortSignal.timeout(Rs)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:c,value:l}=await i.read();if(c)break;a+=o.decode(l,{stream:!0});let u=a.split(`
|
|
72
|
+
`);a=u.pop()||"";for(let 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 xt(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:de.apiUrl};return new St(e)}if(t.provider==="mistral"){let e={...t,provider:"custom",apiUrl:Ze.apiUrl};return new St(e)}return t.provider==="custom"&&t.apiUrl?new St(t):new Pr(t)}function at(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 H=T(require("fs/promises")),Us=T(require("fs")),We=T(require("path"));function je(){}je.prototype={diff:function(e,r){var n,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=s.callback;typeof s=="function"&&(i=s,s={}),this.options=s;var o=this;function a(v){return i?(setTimeout(function(){i(void 0,v)},0),!0):v}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var c=r.length,l=e.length,u=1,d=c+l;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var p=(n=s.timeout)!==null&&n!==void 0?n: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>=l&&m+1>=c)return a([{value:this.join(r),count:r.length}]);var g=-1/0,y=1/0;function b(){for(var v=Math.max(g,-u);v<=Math.min(y,u);v+=2){var _=void 0,C=f[v-1],A=f[v+1];C&&(f[v-1]=void 0);var E=!1;if(A){var $=A.oldPos-v;E=A&&0<=$&&$<c}var F=C&&C.oldPos+1<l;if(!E&&!F){f[v]=void 0;continue}if(!F||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,v),_.oldPos+1>=l&&m+1>=c)return a(Zm(o,_.lastComponent,r,e,o.useLongestToken));f[v]=_,_.oldPos+1>=l&&(y=Math.min(y,v-1)),m+1>=c&&(g=Math.max(g,v+1))}u++}if(i)(function v(){setTimeout(function(){if(u>d||Date.now()>h)return i();b()||v()},0)})();else for(;u<=d&&Date.now()<=h;){var w=b();if(w)return w}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,c=a-s,l=0;c+1<i&&a+1<o&&this.equals(r[c+1],n[a+1]);)c++,a++,l++;return l&&(e.lastComponent={count:l,previousComponent:e.lastComponent}),e.oldPos=a,c},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function Zm(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,c=i.length,l=0,u=0;a<c;a++){var d=i[a];if(d.removed){if(d.value=t.join(n.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&&s){var p=r.slice(l,l+d.count);p=p.map(function(m,g){var y=n[u+g];return y.length>m.length?y:m}),d.value=t.join(p)}else d.value=t.join(r.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}var f=i[c-1];return c>1&&typeof f.value=="string"&&(f.added||f.removed)&&t.equals("",f.value)&&(i[c-2].value+=f.value,i.pop()),i}var Qb=new je;var wc=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,bc=/\S/,vc=new je;vc.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!bc.test(t)&&!bc.test(e)};vc.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]&&wc.test(e[r])&&wc.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Ls=new je;Ls.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 n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function eg(t,e,r){return Ls.diff(t,e,r)}var tg=new je;tg.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var rg=new je;rg.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Fr(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Fr=function(e){return typeof e}:Fr=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fr(t)}function Ms(t){return ng(t)||sg(t)||ig(t)||og()}function ng(t){if(Array.isArray(t))return Ps(t)}function sg(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function ig(t,e){if(t){if(typeof t=="string")return Ps(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 Ps(t,e)}}function Ps(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function og(){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 ag=Object.prototype.toString,Kt=new je;Kt.useLongestToken=!0;Kt.tokenize=Ls.tokenize;Kt.castInput=function(t){var e=this.options,r=e.undefinedReplacement,n=e.stringifyReplacer,s=n===void 0?function(i,o){return typeof o>"u"?r:o}:n;return typeof t=="string"?t:JSON.stringify(js(t,null,null,s),s," ")};Kt.equals=function(t,e){return je.prototype.equals.call(Kt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function js(t,e,r,n,s){e=e||[],r=r||[],n&&(t=n(s,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var o;if(ag.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]=js(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Fr(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],c;for(c in t)t.hasOwnProperty(c)&&a.push(c);for(a.sort(),i=0;i<a.length;i+=1)c=a[i],o[c]=js(t[c],e,r,n,c);e.pop(),r.pop()}else o=t;return o}var Fs=new je;Fs.tokenize=function(t){return t.slice()};Fs.join=Fs.removeEmpty=function(t){return t};function cg(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=eg(r,n,o);if(!a)return;a.push({value:"",lines:[]});function c(y){return y.map(function(b){return" "+b})}for(var l=[],u=0,d=0,p=[],h=1,f=1,m=function(b){var w=a[b],v=w.lines||w.value.replace(/\n$/,"").split(`
|
|
75
|
+
`);if(w.lines=v,w.added||w.removed){var _;if(!u){var C=a[b-1];u=h,d=f,C&&(p=o.context>0?c(C.lines.slice(-o.context)):[],u-=p.length,d-=p.length)}(_=p).push.apply(_,Ms(v.map(function(ee){return(w.added?"+":"-")+ee}))),w.added?f+=v.length:h+=v.length}else{if(u)if(v.length<=o.context*2&&b<a.length-2){var A;(A=p).push.apply(A,Ms(c(v)))}else{var E,$=Math.min(v.length,o.context);(E=p).push.apply(E,Ms(c(v.slice(0,$))));var F={oldStart:u,oldLines:h-u+$,newStart:d,newLines:f-d+$,lines:p};if(b>=a.length-2&&v.length<=o.context){var q=/\n$/.test(r),U=/\n$/.test(n),W=v.length==0&&p.length>F.oldLines;!q&&W&&r.length>0&&p.splice(F.oldLines,0,"\"),(!q&&!W||!U)&&p.push("\")}l.push(F),u=0,d=0,p=[]}h+=v.length,f+=v.length}},g=0;g<a.length;g++)m(g);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:l}}function Sc(t){if(Array.isArray(t))return t.map(Sc).join(`
|
|
76
|
+
`);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var n=t.hunks[r];n.oldLines===0&&(n.oldStart-=1),n.newLines===0&&(n.newStart-=1),e.push("@@ -"+n.oldStart+","+n.oldLines+" +"+n.newStart+","+n.newLines+" @@"),e.push.apply(e,n.lines)}return e.join(`
|
|
77
|
+
`)+`
|
|
78
|
+
`}function lg(t,e,r,n,s,i,o){return Sc(cg(t,e,r,n,s,i,o))}function xc(t,e,r,n,s,i){return lg(t,t,e,r,n,s,i)}function Gt(t,e,r){return xc(t,e,r,"original","modified")}var Ee=T(require("fs/promises")),Ds=T(require("fs")),_t=T(require("path")),kc=T(require("os")),Jt=_t.join(kc.homedir(),".hablas","backup"),_c=10;async function ct(t){try{if(!Ds.existsSync(t))return;Ds.existsSync(Jt)||await Ee.mkdir(Jt,{recursive:!0});let e=await Ee.readFile(t,"utf-8"),r=_t.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=_t.join(Jt,s);await Ee.writeFile(i,e,"utf-8");let a=(await Ee.readdir(Jt)).filter(c=>c.startsWith(`${r}.`)&&c.endsWith(".bak")).sort().reverse();if(a.length>_c)for(let c of a.slice(_c))await Ee.unlink(_t.join(Jt,c))}catch{}}function Tc(t){let e=h=>We.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 H.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,v=g.slice(b-1,w),_=String(w).length,C=v.map(($,F)=>`${String(b+F).padStart(_," ")} | ${$}`),A=`[${h.path} \u2014 lines ${b}-${w} of ${y}]`,E=w<y?`
|
|
80
|
+
... [Partial read. Total lines: ${y}.]`:"";return{success:!0,output:`${A}
|
|
81
|
+
${C.join(`
|
|
82
|
+
`)}${E}`}}catch(f){return{success:!1,output:"",error:`[read_file]: ${j(f)}`}}}},{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 Us.existsSync(f)&&await ct(f),await H.mkdir(We.dirname(f),{recursive:!0}),await H.writeFile(f,h.content,"utf-8"),{success:!0,output:`Written: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[write_file]: ${j(f)}`}}}},{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 H.readFile(f,"utf-8"),g=h.old_content,y=h.new_content,b=Ns(m,g),w=g;if(b===0){let E=U=>U.replace(/\r\n/g,`
|
|
34
83
|
`).split(`
|
|
35
|
-
`).map(
|
|
36
|
-
`)
|
|
84
|
+
`).map(W=>W.trimEnd()).join(`
|
|
85
|
+
`),$=E(m),F=E(g),q=Ns($,F);q===1&&(w=F,b=q)}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 ct(f);let C=(w!==g?(E=>E.replace(/\r\n/g,`
|
|
37
86
|
`).split(`
|
|
38
|
-
`).map(
|
|
39
|
-
`))(
|
|
40
|
-
${
|
|
41
|
-
`),
|
|
42
|
-
`),
|
|
43
|
-
`);await
|
|
44
|
-
${
|
|
45
|
-
`)}}catch(
|
|
46
|
-
`,c.isDirectory()){let
|
|
47
|
-
Error: ${a.message}`}),
|
|
48
|
-
Process timed out after ${
|
|
49
|
-
`),
|
|
50
|
-
`).slice(-
|
|
51
|
-
`)),{success:!0,output:
|
|
52
|
-
PID: ${
|
|
53
|
-
Use bash_output to read output: bash_output(process_id="${c}")`}}return new Promise(c=>{let l=(0,
|
|
54
|
-
... [${
|
|
55
|
-
`),
|
|
56
|
-
... and ${
|
|
57
|
-
`),l=
|
|
58
|
-
`);for(let a of
|
|
59
|
-
`);for(let a of
|
|
60
|
-
`);for(let
|
|
61
|
-
`)}function
|
|
62
|
-
`);
|
|
63
|
-
`),"utf-8"),
|
|
87
|
+
`).map($=>$.trimEnd()).join(`
|
|
88
|
+
`))(m):m).replace(w,y);await H.writeFile(f,C,"utf-8");let A=Gt(h.path,m,C);return{success:!0,output:`Edited: ${h.path}
|
|
89
|
+
${A}`}}catch(f){return{success:!1,output:"",error:`[edit_file]: ${j(f)}`}}}},{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 H.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 ct(f);let v=g.slice(0,b-1),_=g.slice(w),C=h.new_content.split(`
|
|
91
|
+
`),A=[...v,...C,..._].join(`
|
|
92
|
+
`);await H.writeFile(f,A,"utf-8");let E=Gt(h.path,m,A),$=w-b+1,F=C.length;return{success:!0,output:`Patched: ${h.path} (replaced ${$} lines with ${F})
|
|
93
|
+
${E}`}}catch(f){return{success:!1,output:"",error:`[patch_file]: ${j(f)}`}}}},{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 H.readFile(f,"utf-8"),g=h.search,y=h.replace,b=h.is_regex;await ct(f);let w,v;if(b){let _=new RegExp(g,"g");v=(m.match(_)||[]).length,w=m.replace(_,y)}else v=Ns(m,g),w=m.split(g).join(y);return v===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await H.writeFile(f,w,"utf-8"),{success:!0,output:`Replaced ${v} occurrence(s) in ${h.path}`})}catch(f){return{success:!1,output:"",error:`[search_and_replace]: ${j(f)}`}}}},{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 H.mkdir(We.dirname(f),{recursive:!0}),Us.existsSync(f)&&await ct(f),await H.appendFile(f,h.content,"utf-8"),{success:!0,output:`Appended to: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[append_to_file]: ${j(f)}`}}}},{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 ct(f),await H.unlink(f),{success:!0,output:`Deleted: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[delete_file]: ${j(f)}`}}}},{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 H.mkdir(We.dirname(m),{recursive:!0}),await H.rename(f,m),{success:!0,output:`Moved: ${h.from} \u2192 ${h.to}`}}catch(f){return{success:!1,output:"",error:`[move_file]: ${j(f)}`}}}},{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 H.mkdir(f,{recursive:!0}),{success:!0,output:`Created directory: ${h.path}`}}catch(f){return{success:!1,output:"",error:`[create_dir]: ${j(f)}`}}}},{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 Cc(f,"",m,0)||"(empty directory)"}}catch(f){return{success:!1,output:"",error:`[list_dir]: ${j(f)}`}}}},{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 H.stat(f);return{success:!0,output:[`Path: ${h.path}`,`Size: ${fg(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]: ${j(f)}`}}}}]}function Ns(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)break;r++,n=s+e.length}return r}var ug=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Cc(t,e,r,n){if(n>=r)return"";let i=(await H.readdir(t,{withFileTypes:!0})).filter(a=>!ug.has(a.name)&&!a.name.startsWith(".")).sort((a,c)=>a.isDirectory()&&!c.isDirectory()?-1:!a.isDirectory()&&c.isDirectory()?1:a.name.localeCompare(c.name)),o="";for(let a=0;a<i.length;a++){let c=i[a],l=a===i.length-1,u=l?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=c.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${c.name}
|
|
95
|
+
`,c.isDirectory()){let p=e+(l?" ":"\u2502 ");o+=await Cc(We.join(t,c.name),p,r,n+1)}}return o}function fg(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Ec=require("child_process");var $c=require("child_process"),Lr=class{processes=new Map;config;nextId=1;constructor(e){this.config={workingDir:e.workingDir,defaultTimeout:e.defaultTimeout||3e5,maxOutputSize:e.maxOutputSize||5e5}}start(e,r){let n=`bg_${this.nextId++}`,s=r?.timeout||this.config.defaultTimeout,i=(0,$c.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
|
|
96
|
+
Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
|
|
97
|
+
Process timed out after ${s}ms`)},s),this.processes.set(n,o),n}readOutput(e,r){let n=this.processes.get(e);if(!n)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=r?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=n.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
|
|
98
|
+
`),i+=n.stderr),r?.lastLines&&(i=i.split(`
|
|
99
|
+
`).slice(-r.lastLines).join(`
|
|
100
|
+
`)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var dg=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],qs=null;function Ac(t){return qs||(qs=new Lr({workingDir:t})),qs}function Oc(t,e){return{name:"run_command",description:"Execute any shell command and return output. Set run_in_background=true for long-running processes (servers, watchers). Use bash_output to read output later.",safety:"confirm",parameters:{command:{type:"string",description:"Shell command to execute",required:!0},run_in_background:{type:"boolean",description:"Run in background for long processes (default: false)",required:!1},timeout:{type:"number",description:"Timeout in ms (default: 120000)",required:!1}},execute:async r=>{let n=r.command,s=r.run_in_background===!0,i=r.timeout||e.tools.runCommand.timeout||12e4,o=e.tools.runCommand.blocklist||[],a=[...dg,...o];if(a.length>0){for(let c of a)if(n.includes(c))return{success:!1,output:"",error:`Blocked pattern: "${c}". This command is prohibited due to security risks.`}}if(s){let c=Ac(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${c}
|
|
101
|
+
PID: ${Ac(t).getProcess(c)?.pid}
|
|
102
|
+
Use bash_output to read output: bash_output(process_id="${c}")`}}return new Promise(c=>{let l=(0,Ec.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";l.stdout?.on("data",p=>{u+=p}),l.stderr?.on("data",p=>{d+=p}),l.on("close",p=>{let f=(m,g)=>m.length>8e3?m.slice(0,8e3)+`
|
|
103
|
+
... [${g} truncated \u2014 ${m.length} chars total]`:m;c(p===0?{success:!0,output:f(u,"stdout")||"(no output)"}:{success:!1,output:f(u,"stdout"),error:f(d||`Exit code: ${p}`,"stderr")})}),l.on("error",p=>{c({success:!1,output:"",error:p.message})})})}}}var Dr=T(require("fs/promises")),Ve=T(require("path")),pg=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),hg=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function Rc(t){return{name:"search_codebase",description:"Search for a pattern across all code files in the project",safety:"safe",parameters:{query:{type:"string",description:"Search pattern (regex supported)",required:!0},path:{type:"string",description:"Subdirectory to search in (default: .)",required:!1}},execute:async e=>{try{let r=e.query,n=Ve.resolve(t,e.path||"."),s=[];if(await Ic(n,r,s,t),s.length===0)return{success:!0,output:`No matches found for: "${r}"`};let i=s.slice(0,50).join(`
|
|
104
|
+
`),o=s.length>50?`
|
|
105
|
+
... and ${s.length-50} more matches`:"";return{success:!0,output:i+o}}catch(r){return{success:!1,output:"",error:`Search failed: ${j(r)}`}}}}}async function Ic(t,e,r,n){let s=await Dr.readdir(t,{withFileTypes:!0});for(let i of s){if(pg.has(i.name)||i.name.startsWith("."))continue;let o=Ve.join(t,i.name);if(i.isDirectory())await Ic(o,e,r,n);else if(hg.has(Ve.extname(i.name)))try{let c=(await Dr.readFile(o,"utf-8")).split(`
|
|
106
|
+
`),l=Ve.relative(n,o);for(let u=0;u<c.length;u++)new RegExp(e,"i").test(c[u])&&r.push(`${l}:${u+1}: ${c[u].trim()}`)}catch{}}}var Bs=require("child_process"),ge=T(require("fs")),ze=T(require("path"));function mg(t){let e=[],r=ze.join(t,"tsconfig.json");if(!ge.existsSync(r))return e;try{(0,Bs.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
|
|
107
|
+
`);for(let a of o){let c=a.match(/^(.+?)\((\d+),\d+\):\s*(error|warning)\s+TS\d+:\s*(.+)$/);c&&e.push({file:c[1],line:parseInt(c[2],10),severity:c[3]==="error"?"error":"warning",message:c[4].trim(),source:"typescript"})}}return e}function gg(t){let e=[];if(![".eslintrc.json",".eslintrc.js",".eslintrc.yml","eslint.config.js","eslint.config.mjs"].some(n=>ge.existsSync(ze.join(t,n))))return e;try{(0,Bs.execSync)("npx eslint . --format json 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let i=n.stdout||"";try{let o=JSON.parse(i);for(let a of o)for(let c of a.messages||[])e.push({file:ze.relative(t,a.filePath),line:c.line||0,severity:c.severity===2?"error":"warning",message:`${c.message} (${c.ruleId||"unknown"})`,source:"eslint"})}catch{let o=i.split(`
|
|
108
|
+
`);for(let a of o){let c=a.match(/^\s*(\d+):(\d+)\s+(error|warning)\s+(.+?)\s+(\S+)$/);c&&e.push({file:"unknown",line:parseInt(c[1],10),severity:c[3]==="error"?"error":"warning",message:`${c[4]} (${c[5]})`,source:"eslint"})}}}return e}function yg(t,e,r){let n;try{n=ge.readFileSync(t,"utf-8")}catch{return}let s=ze.relative(e,t),i=n.split(`
|
|
109
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;/\bconsole\.(log|debug)\b/.test(a)&&!/\/\//.test(a.split("console")[0])&&r.push({file:s,line:c,severity:"info",message:"console.log/debug statement found (consider removing for production)",source:"pattern",suggestedFix:"Remove or replace with proper logging"}),/\b(TODO|FIXME|HACK|XXX)\b/.test(a)&&r.push({file:s,line:c,severity:"info",message:`Unresolved ${a.match(/\b(TODO|FIXME|HACK|XXX)\b/)?.[0]} comment`,source:"pattern"}),/catch\s*\([^)]*\)\s*\{\s*\}/.test(a)&&r.push({file:s,line:c,severity:"warning",message:"Empty catch block \u2014 errors are silently swallowed",source:"pattern",suggestedFix:"Add error handling or at least log the error"}),/:\s*any\b/.test(a)&&!a.trim().startsWith("//")&&r.push({file:s,line:c,severity:"info",message:"Usage of `any` type \u2014 consider using a specific type",source:"pattern",suggestedFix:"Replace with a proper TypeScript type"})}}function wg(t){let e=[],r=[".ts",".tsx",".js",".jsx"];function n(s,i=0){if(i>5)return;let o=["node_modules",".git","dist","build",".next","coverage"],a;try{a=ge.readdirSync(s)}catch{return}for(let c of a){if(o.includes(c))continue;let l=ze.join(s,c),u;try{u=ge.statSync(l)}catch{continue}u.isDirectory()?n(l,i+1):r.some(d=>c.endsWith(d))&&yg(l,t,e)}}return n(t),e.slice(0,20)}function bg(t){let e=[];e.push(...mg(t)),e.push(...gg(t)),e.push(...wg(t));let r={error:0,warning:1,info:2};return e.sort((n,s)=>r[n.severity]-r[s.severity]),e}function Mc(t){if(t.length===0)return" \u2713 No bugs detected";let e=[],r=t.filter(i=>i.severity==="error").length,n=t.filter(i=>i.severity==="warning").length,s=t.filter(i=>i.severity==="info").length;e.push(` Found ${t.length} issue${t.length>1?"s":""}: ${r} errors, ${n} warnings, ${s} info`),e.push("");for(let i of t.slice(0,15)){let o=i.severity==="error"?"\u2717":i.severity==="warning"?"\u26A0":"\u2139",a=i.line>0?`:${i.line}`:"";e.push(` ${o} ${i.file}${a}`),e.push(` ${i.message}`),i.suggestedFix&&e.push(` \u2192 ${i.suggestedFix}`)}return t.length>15&&e.push(` ... and ${t.length-15} more`),e.join(`
|
|
110
|
+
`)}function vg(t,e){let r=[];for(let n of t)if(n.source==="pattern"&&n.message.includes("console.log")){let s=ze.join(e,n.file);try{let o=ge.readFileSync(s,"utf-8").split(`
|
|
111
|
+
`);n.line>0&&n.line<=o.length&&(o[n.line-1]="// "+o[n.line-1],ge.writeFileSync(s,o.join(`
|
|
112
|
+
`),"utf-8"),r.push({bug:n,fixed:!0,action:"Commented out console.log"}))}catch{r.push({bug:n,fixed:!1,action:"Failed to read/write file"})}}else r.push({bug:n,fixed:!1,action:"Requires manual fix or LLM assistance"});return r}function Pc(t){return{name:"detect_bugs",description:"Scan the project for bugs using TypeScript checking, ESLint, and pattern analysis. Returns a report of found issues.",safety:"safe",parameters:{path:{type:"string",description:"Project path to scan (default: current directory)",required:!1},fix:{type:"string",description:'Set to "true" to auto-fix simple issues',required:!1}},execute:async e=>{let r=e.path||t,n=e.fix==="true"||e.fix===!0;try{let s=bg(r);if(n&&s.length>0){let o=vg(s,r).filter(c=>c.fixed).length;return{success:!0,output:`${Mc(s)}
|
|
64
113
|
|
|
65
|
-
Auto-fixed: ${
|
|
114
|
+
Auto-fixed: ${o}/${s.length} issues`}}return{success:!0,output:Mc(s)}}catch(s){return{success:!1,output:"",error:`Bug detection failed: ${s instanceof Error?s.message:String(s)}`}}}}}var jc=2*1024*1024,Fc=15e3,Lc=32e3,Sg="HablasBot/2.0 (+https://hablas.dev)";function xg(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,`
|
|
66
115
|
`),e=e.replace(/<(br|hr)\s*\/?>/gi,`
|
|
67
116
|
`),e=e.replace(/<\/?(ul|ol)>/gi,`
|
|
68
|
-
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(
|
|
69
|
-
${"#".repeat(parseInt(
|
|
70
|
-
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(
|
|
117
|
+
`),e=e.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi,(r,n,s)=>`
|
|
118
|
+
${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
|
|
119
|
+
`),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${n})`:n}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,n)=>"\n```\n"+n.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/&#(\d+);/g,(r,n)=>String.fromCharCode(parseInt(n))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
|
|
71
120
|
|
|
72
|
-
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function
|
|
121
|
+
`),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function _g(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 kg(t,e){let r=[],n=/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,s,i=new Set;for(;(s=n.exec(t))!==null;){let o=s[1].trim(),a=s[2].replace(/<[^>]+>/g,"").trim();if(!(o.startsWith("#")||o.startsWith("javascript:")||o.startsWith("mailto:"))){try{o=new URL(o,e).href}catch{continue}i.has(o)||(i.add(o),r.push({text:a||o,url:o}))}}return r}async function Dc(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Fc);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":Sg,Accept:"text/html,application/xhtml+xml,text/plain,*/*","Accept-Language":"en-US,en;q=0.9"},redirect:"follow"});if(clearTimeout(r),!n.ok)return{html:"",finalUrl:n.url||t,status:n.status};let s=n.headers.get("content-type")||"";if(!s.includes("text/")&&!s.includes("application/xhtml")&&!s.includes("application/json"))return{html:`[Binary content: ${s}]`,finalUrl:n.url||t,status:n.status};let i=n.body?.getReader();if(!i)return{html:"",finalUrl:n.url||t,status:n.status};let o=[],a=0;for(;a<jc;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=jc)try{i.cancel()}catch{}let c=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>c.decode(u,{stream:!0})).join("")+c.decode(),finalUrl:n.url||t,status:n.status}}catch(n){clearTimeout(r);let s=n instanceof Error?n:new Error(String(n));throw s.name==="AbortError"?new Error(`Timeout after ${Fc/1e3}s`):s}}function Nc(){return[{name:"scrape_url",description:"Fetch a web page and extract its readable text content. Returns clean text/markdown without HTML tags. Use this to read documentation, articles, blog posts, or any web page.",safety:"safe",parameters:{url:{type:"string",description:"The URL to scrape (must start with http:// or https://)",required:!0}},execute:async t=>{let e=t.url;if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:r,finalUrl:n,status:s}=await Dc(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=_g(r),o=xg(r);return o.length>Lc&&(o=o.slice(0,Lc)+`
|
|
73
122
|
|
|
74
|
-
[... content truncated ...]`),{success:!0,output:[`# ${
|
|
75
|
-
`)}}catch(
|
|
76
|
-
`);return{success:!0,output:`Found ${
|
|
123
|
+
[... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${n}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
|
|
124
|
+
`)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await Dc(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=kg(n,s);if(r&&(o=o.filter(c=>c.url.toLowerCase().includes(r)||c.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((c,l)=>`${l+1}. [${c.text}](${c.url})`).join(`
|
|
125
|
+
`);return{success:!0,output:`Found ${o.length} links:
|
|
77
126
|
|
|
78
|
-
${a}`}}catch(
|
|
79
|
-
`)}}catch(
|
|
127
|
+
${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var Tg=3600*1e3,kt=new Map;function Cg(t){let e=kt.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Tg?(kt.delete(t.toLowerCase().trim()),null):e.results:null}function $g(t,e){if(kt.size>200){let r=kt.keys().next().value;r!==void 0&&kt.delete(r)}kt.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Ag(t,e){let r=process.env.BRAVE_API_KEY||process.env.BRAVE_SEARCH_API_KEY;if(!r)return null;try{let n=new URLSearchParams({q:t,count:String(Math.min(e,10))}),s=await fetch(`https://api.search.brave.com/res/v1/web/search?${n}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":r},signal:AbortSignal.timeout(1e4)});return s.ok?((await s.json()).web?.results??[]).slice(0,e).map(a=>({title:a.title||"",url:a.url||"",snippet:a.description||"",source:"brave"})):null}catch{return null}}async function Eg(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let c=a[1],l=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=c.match(/uddg=([^&]+)/);if(d)try{c=decodeURIComponent(d[1])}catch{}l&&c&&!c.startsWith("/")&&i.push({title:l,url:c,snippet:u,source:"duckduckgo"})}if(i.length===0){let c=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,l=new Set;for(;(a=c.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!l.has(u)&&!u.includes("duckduckgo.com")&&(l.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Hs(t,e=5){let r=Cg(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Ag(t,e)},{name:"duckduckgo",fn:()=>Eg(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return $g(t,i),i}catch{}return[]}function Uc(){return{name:"web_search",description:"Search the web for current information. Returns titles, URLs, and snippets from search results. Use this to find documentation, answers, latest versions, news, or any information not in your training data.",safety:"safe",parameters:{query:{type:"string",description:"The search query",required:!0},max_results:{type:"number",description:"Max results to return (default: 5, max: 10)",required:!1}},execute:async t=>{let e=t.query;if(!e?.trim())return{success:!1,output:"",error:"Search query is required"};let r=Math.min(Math.max(1,t.max_results||5),10);try{let n=await Hs(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
|
|
128
|
+
`)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var Fe=T(require("fs")),Vc=T(require("path")),qc=50*1024*1024,Bc=4e4;function Hc(t){let e=t.toString("latin1"),r={},n=[],s=0,i=e.match(/\/Type\s*\/Page\b/g);s=i?i.length:0;let o=e.match(/\/Title\s*\(([^)]*)\)/);o&&(r.title=lt(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=lt(a[1]));let c=e.match(/\/Subject\s*\(([^)]*)\)/);c&&(r.subject=lt(c[1]));let l=e.match(/\/Creator\s*\(([^)]*)\)/);l&&(r.creator=lt(l[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let h=d[1],f=Wc(h);f.trim()&&n.push(f);try{let m=require("zlib"),g=Buffer.from(h,"latin1"),y=m.inflateSync(g).toString("latin1"),b=Wc(y);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
|
|
80
129
|
`).replace(/\r\n/g,`
|
|
81
130
|
`).replace(/\n{3,}/g,`
|
|
82
131
|
|
|
83
|
-
`).trim(),pages:
|
|
84
|
-
`).replace(/\\r/g,"").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\"),
|
|
85
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\\(/g,"(").replace(/\\\)/g,")").replace(/\\\\/g,"\\").replace(/\\(\d{3})/g,(e,
|
|
132
|
+
`).trim(),pages:s,metadata:r}}function Wc(t){let e=[],r=/\(([^)]*)\)\s*Tj/g,n;for(;(n=r.exec(t))!==null;)e.push(lt(n[1]));let s=/\[((?:\([^)]*\)|[^])*?)\]\s*TJ/g;for(;(n=s.exec(t))!==null;){let c=n[1].match(/\(([^)]*)\)/g);if(c){let l=c.map(u=>lt(u.slice(1,-1))).join("");e.push(l)}}let i=/\(([^)]*)\)\s*'/g;for(;(n=i.exec(t))!==null;)e.push(lt(n[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 lt(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 zc(t){let e=r=>Vc.resolve(t,r);return[{name:"read_pdf",description:"Read a PDF file and extract its text content. Returns the text from the PDF, useful for reading documentation, papers, specifications, contracts, etc. For scanned PDFs (images only), text extraction may be limited.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file (relative to working directory)",required:!0},page:{type:"number",description:"Optional: specific page number to extract (1-based)",required:!1}},execute:async r=>{let n=e(r.path);if(!Fe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};if(!n.toLowerCase().endsWith(".pdf"))return{success:!1,output:"",error:`Not a PDF file: ${r.path}`};let s=Fe.statSync(n);if(s.size>qc)return{success:!1,output:"",error:`File too large: ${(s.size/1024/1024).toFixed(1)}MB (max: ${qc/1024/1024}MB)`};try{let i=Fe.readFileSync(n),{text:o,pages:a,metadata:c}=Hc(i);if(!o||o.length<10)return{success:!0,output:`PDF: ${r.path} (${a} pages)
|
|
86
135
|
|
|
87
|
-
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let l=
|
|
136
|
+
[No extractable text found \u2014 this may be a scanned/image-only PDF. Use OCR tools for scanned documents.]`};let l=o;return l.length>Bc&&(l=l.slice(0,Bc)+`
|
|
88
137
|
|
|
89
|
-
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${
|
|
138
|
+
[... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,c.title?`Title: ${c.title}`:"",c.author?`Author: ${c.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
|
|
90
139
|
`)}
|
|
91
|
-
${l}`}}catch(
|
|
92
|
-
`)}}catch(
|
|
93
|
-
Errors/Warnings:`:"Errors:"),
|
|
94
|
-
`),error:
|
|
95
|
-
Final source: ${
|
|
96
|
-
Type: ${
|
|
97
|
-
Size: ${
|
|
140
|
+
${l}`}}catch(i){return{success:!1,output:"",error:`Failed to read PDF: ${i instanceof Error?i.message:String(i)}`}}}},{name:"pdf_metadata",description:"Get metadata from a PDF file: page count, title, author, file size. Quick way to inspect a PDF without reading its full content.",safety:"safe",parameters:{path:{type:"string",description:"Path to the PDF file",required:!0}},execute:async r=>{let n=e(r.path);if(!Fe.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=Fe.statSync(n),i=Fe.readFileSync(n),{pages:o,metadata:a}=Hc(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
|
|
141
|
+
`)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var Jc=require("child_process"),Nr=T(require("fs")),Yc=T(require("os")),Xc=T(require("path")),Qc=1e4,Kc=16e3;function Tt(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 Gc={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>Tt("tsx")?`tsx "${t}"`:Tt("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=>Tt("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>Tt("python3")||Tt("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>Tt("bash")}};async function Og(t,e,r=Qc){let n=Gc[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(Gc).join(", ")}`,exitCode:1,duration:0,language:e};if(!n.available())return{success:!1,stdout:"",stderr:`Language "${e}" is not available on this system. Install the runtime first.`,exitCode:1,duration:0,language:e};let s=Yc.tmpdir(),i=Xc.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Nr.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(c=>{let l=(0,Jc.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";l.stdout?.on("data",p=>{u+=p}),l.stderr?.on("data",p=>{d+=p}),l.on("close",p=>{let h=Date.now()-a;c({success:p===0,stdout:u.slice(0,Kc),stderr:d.slice(0,Kc/2),exitCode:p??1,duration:h,language:e})}),l.on("error",p=>{let h=Date.now()-a;c({success:!1,stdout:"",stderr:p.message,exitCode:1,duration:h,language:e})})})}finally{try{Nr.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 Zc(){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),n=Math.min(Math.max(1e3,t.timeout||Qc),3e4),s=await Og(e,r,n),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
|
|
142
|
+
Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
|
|
143
|
+
`),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Hr=T(require("fs")),ke=T(require("path"));var Ig=["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"],Mg=[/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 Ws(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 Pg=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 Ur(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(e=>e.length>1&&!Pg.has(e))}function qr(t,e){let r=[...new Set(Ur(t))].slice(0,6);return r.length>0?r.join(" "):t.trim().slice(0,60)}function Yt(t){try{let e=new URL(t).hostname.toLowerCase();return Ig.some(r=>e===r||e.endsWith("."+r))}catch{return!1}}function jg(t){return Mg.some(e=>e.test(t))}function Br(t,e,r,n,s=[]){let i=Yt(t),o=[],a=[],c=0;if(i&&(c+=20,o.push("trusted-host")),jg(t)&&(c+=15,o.push("cdn-direct")),/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(t)&&(c+=8,o.push("image-ext")),(/\/photos?\/[^/?#]+/i.test(t)||/\/images?\/[^/?#]+/i.test(t))&&(c+=6,o.push("photo-page")),s.length>0){let u=Ur([e,r,new URL(t).pathname].join(" ").replace(/[-_]/g," ")),d=new Set(u),p=s.filter(h=>d.has(h));p.length>0&&(c+=p.length*10,o.push("query-match:"+p.slice(0,3).join(",")))}let l=[e,r,t].join(" ").toLowerCase();return(n==="hero"||n==="banner")&&/wide|panorama|landscape|banner|background|wallpaper/i.test(l)&&(c+=5,o.push("kind-hero")),(n==="product"||n==="thumbnail")&&/product|closeup|detail|item|buy/i.test(l)&&(c+=5,o.push("kind-product")),(n==="icon"||n==="avatar")&&/icon|avatar|logo|portrait|profile/i.test(l)&&(c+=5,o.push("kind-icon")),/javascript|\.woff|\.eot|\.ttf|\.css/i.test(t)&&(c-=30,a.push("non-image-resource")),{score:c,positives:o,negatives:a,trusted:i}}function el(t,e){let r=qr(t,e),n=encodeURIComponent(r);return r?[{source:"unsplash",url:`https://unsplash.com/s/photos/${n}`},{source:"pexels",url:`https://www.pexels.com/search/${n}/`},{source:"pixabay",url:`https://pixabay.com/images/search/${n}/`}]:[]}function tl(t,e){let r=qr(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 Fg(t,e){try{let r=t.split(",")[0].trim().split(/\s+/)[0],n=new URL(r,e);return/^https?:$/i.test(n.protocol)?n.href:null}catch{return null}}function Ct(t,e){let r=new Set,n=[];function s(i){let o=Fg(i,e);o&&!r.has(o)&&(r.add(o),n.push(o))}for(let i of t.matchAll(/<meta[^>]+(?:property|name)=["'](?:og:image(?::secure_url)?|twitter:image(?::src)?)["'][^>]+content=["']([^"']+)["']/gi))s(i[1]);for(let i of t.matchAll(/<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["'](?:og:image|twitter:image)/gi))s(i[1]);for(let i of t.matchAll(/<script[^>]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi))try{let o=JSON.parse(i[1]),a=[o?.image,o?.logo,o?.thumbnail,o?.primaryImageOfPage];for(let c of a)typeof c=="string"?s(c):typeof c?.url=="string"?s(c.url):typeof c?.contentUrl=="string"?s(c.contentUrl):Array.isArray(c)&&c.forEach(l=>{typeof l=="string"?s(l):l?.url&&s(l.url)})}catch{}for(let i of t.matchAll(/<link[^>]+rel=["']image_src["'][^>]+href=["']([^"']+)["']/gi))s(i[1]);for(let i of t.matchAll(/<img[^>]+data-(?:src|lazy|original|lazy-src)=["']([^"']+)["']/gi))s(i[1]);for(let i of t.matchAll(/srcset=["']([^"']+)["']/gi)){let o=i[1].split(",").map(a=>{let c=a.trim().split(/\s+/);return{url:c[0],w:parseInt(c[1]??"0")||0}}).sort((a,c)=>c.w-a.w)[0];o?.url&&s(o.url)}for(let i of t.matchAll(/<img[^>]+src=["']([^"']+)["']/gi))s(i[1]);return n.filter(i=>/\/(icon|favicon|logo-|pixel|tracking|spacer|blank)\b/i.test(i)||/data:image\//i.test(i)||/\d{1,3}x\d{1,3}\.(gif|png)/i.test(i)?!1:Yt(i)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(i))}function rl(t,e){let r=new Set,n=[];for(let s of t.matchAll(/<a[^>]+href=["']([^"'#]+)["']/gi))try{let i=new URL(s[1],e),o=i.hostname.toLowerCase(),a=i.pathname;(o==="unsplash.com"&&/^\/photos\/[^/?#]+/i.test(a)||(o==="www.pexels.com"||o==="pexels.com")&&/^\/photo\/[^?#]+/i.test(a)||o==="pixabay.com"&&/^\/(?:photos|images)\/[^?#]+/i.test(a)||o==="commons.wikimedia.org"&&/^\/wiki\/File:/i.test(a))&&!r.has(i.href)&&(r.add(i.href),n.push(i.href))}catch{}return n.slice(0,20)}var nl=15*1024*1024,sl=15e3,Lg=5;function Dg(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 ke.extname(new URL(e).pathname)||".bin"}catch{return".bin"}}function il(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 Ng(t){let e=await fetch(t,{signal:AbortSignal.timeout(sl),redirect:"follow",headers:il(t)});if(!e.ok)throw new Error(`HTTP ${e.status} while downloading asset`);let r=e.headers.get("content-type")||"",n=e.url||t;if(/text\/html|application\/xhtml\+xml/i.test(r))throw new Error("HTML page returned where a direct image was expected");let s=await e.arrayBuffer(),i=Buffer.from(s);if(i.length>nl)throw new Error(`asset too large: ${Math.round(i.length/1024/1024)}MB`);return{bytes:i,contentType:r,finalUrl:n}}async function Ug(t,e="generic",r=0){if(r>2)throw new Error("asset resolution exceeded maximum HTML indirection depth");let n=await fetch(t,{signal:AbortSignal.timeout(sl),redirect:"follow",headers:il(t)});if(!n.ok)throw new Error(`HTTP ${n.status} while downloading asset`);let s=n.headers.get("content-type")||"",i=n.url||t;if(/text\/html|application\/xhtml\+xml/i.test(s)){let c=await n.text(),l=Ct(c,i).map(d=>({url:d,...Br(d,"","",e)})).sort((d,p)=>p.score-d.score).slice(0,Lg);if(l.length===0)throw new Error("HTML page did not expose a direct image candidate");let u="no candidate attempt made";for(let d of l)try{return await Ng(d.url)}catch(p){u=String(j(p))}throw new Error(`all ranked HTML image candidates failed: ${u}`)}let o=await n.arrayBuffer(),a=Buffer.from(o);if(a.length>nl)throw new Error(`asset too large: ${Math.round(a.length/1024/1024)}MB`);return{bytes:a,contentType:s,finalUrl:i}}function qg(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 ol(t){return{name:"download_asset",description:"Download an external asset such as an image or file from a URL and save it inside the project. For image pages, the tool now ranks multiple embedded image candidates and downloads the strongest working direct image instead of trusting the first HTML metadata hit blindly.",safety:"confirm",parameters:{url:{type:"string",description:"Public URL of the asset or image page",required:!0},path:{type:"string",description:"Target project-relative path, e.g. public/hero.jpg or assets/bg.webp",required:!0}},execute:async e=>{let r=String(e.url||""),n=String(e.path||"");if(!r)return{success:!1,output:"",error:"url is required"};if(!n)return{success:!1,output:"",error:"path is required"};if(!/^https?:\/\//i.test(r))return{success:!1,output:"",error:"url must start with http:// or https://"};try{let{bytes:s,contentType:i,finalUrl:o}=await Ug(r,qg(n)),a=ke.resolve(t,n),l=ke.extname(a)?a:a+Dg(i,o);return Hr.mkdirSync(ke.dirname(l),{recursive:!0}),Hr.writeFileSync(l,s),{success:!0,output:`Downloaded asset: ${ke.relative(t,l)||ke.basename(l)}
|
|
144
|
+
Final source: ${o}
|
|
145
|
+
Type: ${i||"unknown"}
|
|
146
|
+
Size: ${s.length} bytes`}}catch(s){return{success:!1,output:"",error:`download failed: ${j(s)}`}}}}}var Wr=T(require("fs"));var Vr=T(require("path"));var zs=15e3,al=5;function cl(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function ll(t,e){return t[e]|t[e+1]<<8}function Bg(t){let e=2;for(;e<t.length-9;){if(t[e]!==255){e++;continue}let r=t[e+1],n=(t[e+2]<<8)+t[e+3];if([192,193,194,195,197,198,199,201,202,203,205,206,207].includes(r))return{height:(t[e+5]<<8)+t[e+6],width:(t[e+7]<<8)+t[e+8]};e+=2+n}return{}}function 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,n=(t.readUInt16LE(28)&16383)+1;return{width:r,height:n}}return{}}function Vs(t,e){return t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?{width:cl(t,16),height:cl(t,20),ext:".png"}:t.length>=10&&t.toString("ascii",0,3)==="GIF"?{width:ll(t,6),height:ll(t,8),ext:".gif"}:t.length>=4&&t[0]===255&&t[1]===216?{...Bg(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 dl(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 ul(t){let e=await fetch(t,{signal:AbortSignal.timeout(zs),redirect:"follow",headers:dl(t)});if(!e.ok)throw new Error(`HTTP ${e.status} fetching ${t}`);let r=e.headers.get("content-type")||"",n=e.url||t,s=await e.arrayBuffer(),i=Buffer.from(s).subarray(0,2*1024*1024),o=/text\/html|application\/xhtml/i.test(r)?i.toString("utf-8"):void 0;return{status:e.status,contentType:r,bytes:i,finalUrl:n,html:o}}async function fl(t){let e=await fetch(t,{signal:AbortSignal.timeout(zs),redirect:"follow",headers:{...dl(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 Wg(t,e){let r=new URLSearchParams({action:"query",generator:"search",gsrsearch:qr(t,"generic"),gsrnamespace:"6",gsrlimit:String(Math.min(e,10)),prop:"imageinfo",iiprop:"url",iiurlwidth:"1600",format:"json",origin:"*"}),n=await fetch(`https://commons.wikimedia.org/w/api.php?${r}`,{signal:AbortSignal.timeout(zs),headers:{"User-Agent":"HablasBot/2.0",Accept:"application/json"}});if(!n.ok)throw new Error(`Wikimedia HTTP ${n.status}`);let s=await n.json();return Object.values(s?.query?.pages||{}).map(i=>({title:String(i?.title||""),url:String(i?.imageinfo?.[0]?.url||i?.imageinfo?.[0]?.thumburl||""),snippet:String(i?.title||"").replace(/^File:/i,""),source:"wikimedia"})).filter(i=>i.url.startsWith("http")).slice(0,e)}function Vg(t){return`You are an image inspection assistant. Analyse the provided image and return ONLY valid JSON.
|
|
98
147
|
|
|
99
148
|
Context from user: "${t}"
|
|
100
149
|
|
|
@@ -113,85 +162,85 @@ Rules:
|
|
|
113
162
|
- confidence: float 0.0\u20131.0
|
|
114
163
|
- suggestedUse: one of "hero", "product", "icon", "generic", "reject"
|
|
115
164
|
- issues: list any quality or relevance problems (empty array if none)
|
|
116
|
-
- Do NOT output anything outside the JSON object`}async function
|
|
165
|
+
- Do NOT output anything outside the JSON object`}async function zg(t,e,r,n){let s;if(t.provider==="nvidia")s=de.apiUrl;else if(t.provider==="mistral")s="https://api.mistral.ai/v1";else if(t.provider==="custom"&&t.apiUrl)s=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,c=await fetch(s.replace(/\/+$/,"")+"/chat/completions",{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({model:a,messages:[{role:"system",content:Vg(n)},{role:"user",content:[{type:"text",text:"Inspect this image."},{type:"image_url",image_url:{url:i}}]}],temperature:.1,max_tokens:300})});if(!c.ok)throw new Error(`Vision API HTTP ${c.status}`);let l=await c.json(),u=String(l?.choices?.[0]?.message?.content??""),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 Kg(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 pl(t,e){return[{name:"search_image_candidates",description:["Search for ranked image URL candidates from trusted stock sites (Unsplash, Pexels, Pixabay, Wikimedia).","Returns a scored list of direct image URLs ready for inspect_image.","Use kind to signal intended use: hero, product, icon, avatar, banner, thumbnail, or generic.",'query should describe what you need visually (e.g. "mountain sunset landscape", "red sports car", "smiling woman portrait").'].join(" "),safety:"safe",parameters:{query:{type:"string",description:"Visual description of the image you need",required:!0},kind:{type:"string",description:"hero | product | icon | avatar | banner | thumbnail | generic (default: generic)",required:!1},max_results:{type:"number",description:"Max candidates to return (1\u201310, default: 5)",required:!1}},execute:async r=>{let n=String(r.query||"").trim();if(!n)return{success:!1,output:"",error:"query is required"};let s=Ws(r.kind),i=Math.min(Math.max(1,Number(r.max_results??5)),10),o=Ur(n),a=new Map,c=[],l=(p,h,f,m)=>{if(a.has(p))return;let g=Br(p,h,f,s,o);a.set(p,{url:p,title:h,snippet:f,source:m,...g})};for(let p of el(n,s))try{let{finalUrl:h,html:f}=await fl(p.url),m=rl(f,h),g=0;for(let b of m.slice(0,al*2)){if(g>=al)break;try{let{finalUrl:w,html:v}=await fl(b),C=Ct(v,w)[0];C&&(l(C,p.source+" photo",n,p.source),g++)}catch{}}let y=Ct(f,h);for(let b of y.slice(0,6))l(b,p.source,n,p.source);g===0&&y.length===0&&c.push(`${p.source}: no images found`)}catch(h){c.push(`${p.source}: ${j(h)}`)}try{let p=await Wg(n,Math.max(4,i));for(let h of p)l(h.url,h.title,h.snippet,h.source)}catch(p){c.push(`wikimedia: ${j(p)}`)}if(a.size<i)for(let p of tl(n,s))try{let h=await Hs(p,Math.max(6,i));for(let f of h)l(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 "${n}".${c.length?`
|
|
117
166
|
Notes:
|
|
118
167
|
- `+c.join(`
|
|
119
|
-
- `):""}`};let
|
|
120
|
-
`)}}},{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
|
|
121
|
-
`)}}}]}var
|
|
122
|
-
`).length,
|
|
123
|
-
`)}}catch(
|
|
124
|
-
`)}}catch(
|
|
125
|
-
`)}}catch(
|
|
126
|
-
`),u=l[0]||"",
|
|
127
|
-
`)}}},{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
|
|
128
|
-
`).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
|
|
129
|
-
`)}}catch(c){let l=
|
|
130
|
-
`)}}}},{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
|
|
131
|
-
+++ ${
|
|
132
|
-
`).slice(0,40).map(
|
|
133
|
-
`)}`};if(c===
|
|
134
|
-
`).length,
|
|
135
|
-
`).length,d
|
|
136
|
-
`)}}},{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
|
|
168
|
+
- `):""}`};let d=[`Image candidates for: "${n}" (kind=${s}) \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("")}),c.length&&(d.push("Notes:"),c.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 n=String(r.source||"").trim();if(!n)return{success:!1,output:"",error:"source is required"};let s=Ws(r.kind),i=String(r.context||n).slice(0,200),o=String(r.use_vision??"true").toLowerCase()!=="false",a=[`Inspection: ${n}`,""],c="unknown",l,u,d=!1,p=!1,h=n,f=null,m=!1,g=[];try{if(/^https?:\/\//i.test(n)){let w=await ul(n);if(h=w.finalUrl,c=w.contentType,p=Yt(h),w.html){if(m=!0,g=Ct(w.html,h),g.length>0){let v=g[0];try{let _=await ul(v);h=_.finalUrl,c=_.contentType,f=_.bytes,p=Yt(h);let C=Vs(f,c);l=C.width,u=C.height,d=/^image\//i.test(c)}catch(_){a.push(` [warn] could not fetch best candidate: ${j(_)}`)}}}else{f=w.bytes,d=/^image\//i.test(c)||/\.(jpg|jpeg|png|webp|gif|svg)(\?|$)/i.test(h);let v=Vs(f,c);l=v.width,u=v.height}}else{let w=Vr.resolve(t,n);if(!Wr.existsSync(w))return{success:!1,output:"",error:`Local file not found: ${n}`};f=Wr.readFileSync(w).subarray(0,2*1024*1024);let v=Vr.extname(w).toLowerCase();c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".svg":"image/svg+xml"}[v]||"application/octet-stream",d=!0,p=!1;let _=Vs(f,c);l=_.width,u=_.height}}catch(w){return{success:!1,output:"",error:`Failed to fetch/read source: ${j(w)}`}}a.push(` final URL: ${h}`),a.push(` content-type: ${c}`),a.push(` direct image: ${d?"yes":"no (HTML page)"}`),a.push(` trusted host: ${p?"yes":"no"}`),l&&u&&a.push(` dimensions: ${l} \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=Kg(s,l,u);if(l&&u){let w=y>0;a.push(` size verdict: ${w?"\u2713 adequate for "+s:"\u2717 may be too small for "+s} (${l}\xD7${u})`)}if(o&&e.vision.enabled&&f&&/^image\//i.test(c)){a.push(""),a.push(" Vision analysis:");try{let w=await zg(e,f.subarray(0,e.vision.maxImageBytes),c,i);a.push(` model: ${w.model}`),a.push(` description: ${w.description}`),a.push(` suitable: ${w.suitable?"yes":"no"}`),a.push(` confidence: ${(w.confidence*100).toFixed(0)}%`),a.push(` suggested: ${w.suggestedUse}`),a.push(` summary: ${w.summary}`),w.issues.length>0&&a.push(` issues: ${w.issues.join("; ")}`)}catch(w){a.push(` [vision unavailable: ${j(w)}]`),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(c));return a.push(` VERDICT: ${b?"\u2713 ADOPT \u2014 direct image confirmed":"\u2717 SKIP \u2014 not a reliable direct image URL"}`),{success:!0,output:a.join(`
|
|
170
|
+
`)}}}]}var Ke=T(require("fs")),ae=T(require("path")),Gg=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage",".turbo"]),Jg=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java"]),Yg=/\b(index|main|app|server|start|entry|cli)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/i;function Xg(t,e,r){let n=[],s=ae.dirname(e),i=[/from\s+['"]([^'"]+)['"]/g,/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g,/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g];for(let a of i){let c;for(;(c=a.exec(t))!==null;){let l=c[1];if(l.startsWith(".")){let u=ae.resolve(s,l);if(!Ke.existsSync(u)){for(let d of[".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"])if(Ke.existsSync(u+d)){u=u+d;break}}Ke.existsSync(u)&&n.push(ae.relative(r,u))}}}let o=[/^from\s+\.\S*\s+import/gm,/^import\s+\./gm];for(let a of o)for(;a.exec(t)!==null;)n.push(s);return[...new Set(n)]}function Qg(t,e){let r=[];if(e==="ts"||e==="js"){let n=[/export\s+(?:default\s+)?(?:function|class|const|let|var|interface|type|enum)\s+(\w+)/g,/export\s*\{\s*([^}]+)\}/g];for(let s of n){let i;for(;(i=s.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 hl(t,e){let r=[];try{let n=Ke.readdirSync(t,{withFileTypes:!0});for(let s of n){if(Gg.has(s.name)||s.name.startsWith("."))continue;let i=ae.join(t,s.name);s.isDirectory()?r.push(...hl(i,e)):Jg.has(ae.extname(s.name))&&r.push(ae.relative(e,i))}}catch{}return r}function Zg(t){let e=[],r=new Set,n=new Set;function s(i,o){if(n.has(i)){let c=o.indexOf(i);c!==-1&&e.push(o.slice(c));return}if(r.has(i))return;r.add(i),n.add(i);let a=t.get(i);if(a)for(let c of a.imports)s(c,[...o,c]);n.delete(i)}for(let i of t.keys())s(i,[i]);return e.slice(0,5)}function Ks(t,e=300){let r=Date.now(),n=hl(t,t).slice(0,e),s=new Map;for(let a of n)try{let c=ae.join(t,a),l=Ke.readFileSync(c,"utf-8"),u=ae.extname(a).slice(1),d=["ts","tsx"].includes(u)?"ts":["js","jsx","mjs"].includes(u)?"js":u,p=l.split(`
|
|
171
|
+
`).length,h=Xg(l,c,t),f=Qg(l,d),m=Yg.test(a);s.set(a,{path:a,imports:h,exports:f,references:[],isEntryPoint:m,lines:p,language:d})}catch{}for(let[a,c]of s)for(let l of c.imports){let u=s.get(l);u&&!u.references.includes(a)&&u.references.push(a)}let i=[...s.values()].filter(a=>a.isEntryPoint||a.references.length===0&&a.imports.length>0).map(a=>a.path).slice(0,5),o=Zg(s);return{nodes:s,entryPoints:i,circularDeps:o,totalFiles:n.length,buildTime:Date.now()-r}}function ml(t){return[{name:"analyze_project",description:"Build a complete graph of the project: all files, imports, exports, entry points, and circular dependencies. Use this BEFORE making multi-file changes to understand the full impact. Returns ranked file importance.",safety:"safe",parameters:{focus:{type:"string",description:'Optional: focus on a subdirectory (e.g. "src/components")',required:!1},max_files:{type:"number",description:"Max files to analyze (default: 200)",required:!1}},execute:async s=>{try{let i=s.focus?ae.join(t,s.focus):t,o=s.max_files||200,a=Ks(i,o),c=[...a.nodes.values()].sort((u,d)=>d.references.length-u.references.length).slice(0,30),l=[`Project Graph \xB7 ${a.totalFiles} files \xB7 built in ${a.buildTime}ms`,"","\u2500\u2500 Entry Points \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...a.entryPoints.map(u=>` ${u}`),"","\u2500\u2500 Most Referenced Files (impact ranking) \u2500\u2500"];for(let u of c)u.references.length!==0&&(l.push(` ${u.path.padEnd(45)} \u2190 referenced by ${u.references.length} files`),u.exports.length&&l.push(` exports: ${u.exports.slice(0,6).join(", ")}`));if(a.circularDeps.length){l.push(""),l.push("\u2500\u2500 Circular Dependencies (\u26A0 fix before refactoring) \u2500\u2500");for(let u of a.circularDeps)l.push(` ${u.join(" \u2192 ")}`)}return l.push(""),l.push(`Total nodes: ${a.nodes.size} | Entry points: ${a.entryPoints.length} | Circular deps: ${a.circularDeps.length}`),{success:!0,output:l.join(`
|
|
172
|
+
`)}}catch(i){return{success:!1,output:"",error:`Graph build failed: ${j(i)}`}}}},{name:"find_references",description:"Find all files that import or reference a specific file or symbol. Use before renaming, moving, or deleting any file.",safety:"safe",parameters:{target:{type:"string",description:"File path or symbol name to find references for",required:!0}},execute:async s=>{try{let i=s.target,o=Ks(t,300),a=[],c=o.nodes.get(i);if(c){a.push(`File: ${i}`),a.push(`Referenced by ${c.references.length} files:`);for(let l of c.references)a.push(` ${l}`);a.push(""),a.push(`This file imports ${c.imports.length} files:`);for(let l of c.imports)a.push(` ${l}`)}else{a.push(`Symbol search: "${i}"`);let l=0;for(let[u,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"}`),l++);l||a.push(" No matches found.")}return{success:!0,output:a.join(`
|
|
173
|
+
`)}}catch(i){return{success:!1,output:"",error:`Reference search failed: ${j(i)}`}}}},{name:"impact_analysis",description:"Before changing a file, analyze the blast radius: which files will be affected and how critical the change is.",safety:"safe",parameters:{file:{type:"string",description:"File you intend to modify",required:!0}},execute:async s=>{try{let i=s.file,o=Ks(t,300),a=o.nodes.get(i);if(!a)return{success:!0,output:`File "${i}" not found in graph. It may be new.`};let c=new Set,l=[...a.references];for(;l.length;){let h=l.shift();if(!c.has(h)){c.add(h);let f=o.nodes.get(h);f&&l.push(...f.references)}}let u=c.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(c.size>a.references.length){p.push(""),p.push(`Transitive impact (${c.size} total):`);for(let h of[...c].slice(0,15))p.push(` ${h}`);c.size>15&&p.push(` ... and ${c.size-15} more`)}return p.push(""),p.push(`Exports: ${a.exports.join(", ")||"none"}`),p.push(`Imports: ${a.imports.length} files`),p.push(`Size: ${a.lines} lines`),{success:!0,output:p.join(`
|
|
174
|
+
`)}}catch(i){return{success:!1,output:"",error:`Impact analysis failed: ${j(i)}`}}}}]}var gl=require("child_process"),yl=T(require("fs")),wl=T(require("path"));function ut(t,e,r=15e3){return new Promise(n=>{(0,gl.exec)(t,{cwd:e,timeout:r,maxBuffer:4*1024*1024},(s,i,o)=>{let a=s?s.code:void 0;n({out:i||"",err:o||"",code:typeof a=="number"?a:s?1:0})})})}function Xt(t){return yl.existsSync(wl.join(t,".git"))}function bl(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(!Xt(t))return{success:!0,output:"No git repository in this workspace."};let{out:o,err:a,code:c}=await ut("git status --short --branch",t);if(c!==0)return{success:!1,output:"",error:a||"git status failed"};let l=o.trim().split(`
|
|
175
|
+
`),u=l[0]||"",d=l.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(!Xt(t))return{success:!0,output:"No git repository."};let a=o.staged?"--cached ":"",c=o.file?` -- "${o.file}"`:"",{out:l,err:u,code:d}=await ut(`git diff ${a}--stat${c}`,t);if(d!==0)return{success:!1,output:"",error:u};let{out:p}=await ut(`git diff ${a}${c}`,t);return{success:!0,output:[l.trim(),"",p.slice(0,6e3)].join(`
|
|
177
|
+
`).trim()||"No changes found."}}},{name:"git_log",description:"Show recent git commit history. Useful for understanding project evolution and finding a good rollback point.",safety:"safe",parameters:{count:{type:"number",description:"Number of commits to show (default: 10)",required:!1},file:{type:"string",description:"Show history for a specific file",required:!1}},execute:async o=>{if(!Xt(t))return{success:!0,output:"No git repository."};let a=Math.min(o.count||10,40),c=o.file?` -- "${o.file}"`:"",{out:l,err:u,code:d}=await ut(`git log --oneline --decorate -${a}${c}`,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"No commits yet."}}},{name:"git_commit",description:"Stage all changes and commit with a message. Only do this when the user explicitly asks to commit.",safety:"confirm",parameters:{message:{type:"string",description:"Commit message",required:!0},files:{type:"string",description:"Specific files to stage (default: all changes via git add -A)",required:!1}},execute:async o=>{if(!Xt(t))return{success:!1,output:"",error:"No git repository."};let a=o.message.trim();if(!a)return{success:!1,output:"",error:"Commit message is required."};let c=o.files?`git add ${o.files}`:"git add -A",{err:l,code:u}=await ut(c,t);if(u!==0)return{success:!1,output:"",error:`Stage failed: ${l}`};let{out:d,err:p,code:h}=await ut(`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(!Xt(t))return{success:!1,output:"",error:"No git repository."};let a=o.action.toLowerCase(),c="";if(a==="stash")c='git stash push -u -m "hablas-auto-stash"';else if(a==="pop")c="git stash pop";else if(a==="list")c="git stash list";else return{success:!1,output:"",error:"action must be: stash | pop | list"};let{out:l,err:u,code:d}=await ut(c,t);return d!==0?{success:!1,output:"",error:u}:{success:!0,output:l.trim()||"Done."}}}]}var Z=T(require("fs")),ye=T(require("path"));var Js=class{entries=[];sessionDir;constructor(e){this.sessionDir=ye.join(e,".hablas","rollback",`session_${Date.now()}`),Z.mkdirSync(this.sessionDir,{recursive:!0})}backup(e){let r=Z.existsSync(e);if(r){let n=ye.join(this.sessionDir,Buffer.from(e).toString("base64")+".bak");Z.copyFileSync(e,n),this.entries.push({originalPath:e,backupPath:n,existed:r})}else this.entries.push({originalPath:e,backupPath:"",existed:!1})}rollback(){let e=[],r=[],n=[];for(let s of[...this.entries].reverse())try{s.existed&&s.backupPath?(Z.mkdirSync(ye.dirname(s.originalPath),{recursive:!0}),Z.copyFileSync(s.backupPath,s.originalPath),e.push(s.originalPath)):!s.existed&&Z.existsSync(s.originalPath)&&(Z.unlinkSync(s.originalPath),r.push(s.originalPath))}catch(i){n.push(`${s.originalPath}: ${j(i)}`)}return{restored:e,deleted:r,errors:n}}getBackedUpFiles(){return this.entries.map(e=>e.originalPath)}},Gs=new Map;function vl(t){return Gs.has(t)||Gs.set(t,new Js(t)),Gs.get(t)}function Sl(t){return[{name:"atomic_write",description:"Write multiple files in a single atomic operation with automatic rollback. If ANY file fails to write, ALL previously written files are automatically restored to their original state. Use this for multi-file changes that must succeed together (e.g. rename a type across 5 files).",safety:"confirm",parameters:{files:{type:"string",description:'JSON array of {path, content} objects. Example: [{"path":"src/a.ts","content":"..."},{"path":"src/b.ts","content":"..."}]',required:!0},description:{type:"string",description:"Short description of what this atomic operation does (for logging)",required:!1}},execute:async s=>{let i;try{if(i=JSON.parse(s.files),!Array.isArray(i)||!i.every(c=>c.path&&typeof c.content=="string"))throw new Error("Invalid format \u2014 expected array of {path, content}")}catch(c){return{success:!1,output:"",error:`Invalid files JSON: ${j(c)}`}}let o=vl(t),a=[];try{for(let{path:l}of i){let u=ye.resolve(t,l);o.backup(u)}for(let{path:l,content:u}of i){let d=ye.resolve(t,l);Z.mkdirSync(ye.dirname(d),{recursive:!0}),Z.writeFileSync(d,u,"utf-8"),a.push(l)}return{success:!0,output:[`Atomic write successful${s.description?` (${s.description})`:""}`,`Written ${a.length} files:`,...a.map(l=>` \u2713 ${l}`)].join(`
|
|
178
|
+
`)}}catch(c){let l=o.rollback();return{success:!1,output:"",error:[`Atomic write FAILED at: ${j(c)}`,`Rolled back ${l.restored.length} files.`,a.length>0?`Was writing: ${a.join(", ")}`:"",l.errors.length?`Rollback errors: ${l.errors.join("; ")}`:""].filter(Boolean).join(`
|
|
179
|
+
`)}}}},{name:"diff_preview",description:"Preview what a file would look like AFTER a change, shown as a unified diff. Use before writing to verify the change is correct. Does NOT write anything.",safety:"safe",parameters:{path:{type:"string",description:"File path to preview the change for",required:!0},new_content:{type:"string",description:"The proposed new content of the file",required:!0}},execute:async s=>{let i=s.path,o=s.new_content,a=ye.resolve(t,i),c="";if(Z.existsSync(a))try{c=Z.readFileSync(a,"utf-8")}catch{}else return{success:!0,output:`[New file: ${i}]
|
|
180
|
+
+++ ${o.split(`
|
|
181
|
+
`).slice(0,40).map(f=>"+ "+f).join(`
|
|
182
|
+
`)}`};if(c===o)return{success:!0,output:`No changes \u2014 content is identical to ${i}`};let l=Gt(i,c,o),u=c.split(`
|
|
183
|
+
`).length,d=o.split(`
|
|
184
|
+
`).length,p=d-u,h=p>=0?`+${p}`:`${p}`;return{success:!0,output:[`Diff preview: ${i} (${u} \u2192 ${d} lines, ${h})`,"",l.slice(0,5e3),l.length>5e3?"... [diff truncated]":""].filter(Boolean).join(`
|
|
185
|
+
`)}}},{name:"rollback_session",description:"EMERGENCY ROLLBACK: Restore all files modified in this session to their state before any changes were made. Use when something went wrong and you need to undo everything.",safety:"dangerous",parameters:{confirm:{type:"string",description:'Type "ROLLBACK" to confirm you want to restore all files',required:!0}},execute:async s=>{if(s.confirm!=="ROLLBACK")return{success:!1,output:"",error:'Rollback cancelled. Type "ROLLBACK" as the confirm value to proceed.'};let o=vl(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 ${ye.relative(t,a)}`).join(`
|
|
137
186
|
`)].filter(Boolean).join(`
|
|
138
|
-
`)}}}]}var
|
|
139
|
-
`)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let
|
|
140
|
-
`)}}},{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
|
|
141
|
-
`)}}},{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
|
|
142
|
-
`)}}}]}var
|
|
143
|
-
`)[0]}`)}return t.total===0&&(
|
|
144
|
-
`)}function
|
|
145
|
-
`+u).trim(),
|
|
146
|
-
`+a).trim(),l=/(?:All files|TOTAL|coverage)\s*\|\s*([\d.]+)/i,u=c.match(l),
|
|
187
|
+
`)}}}]}var N=T(require("fs")),G=T(require("path")),_l=require("child_process"),ey=new Set(["node_modules",".git","dist","build",".next",".hablas","__pycache__",".cache","coverage"]),ty=500*1024,ry=20*1024*1024;function Ys(t){let e=G.join(t,".hablas","checkpoints");return N.existsSync(e)||N.mkdirSync(e,{recursive:!0}),e}function kl(t){return G.join(t,".hablas","checkpoints","_index.json")}function xl(t){let e=kl(t);if(N.existsSync(e))try{return JSON.parse(N.readFileSync(e,"utf-8"))}catch{}return{version:1,checkpoints:[]}}function ny(t,e){N.writeFileSync(kl(t),JSON.stringify(e,null,2),"utf-8")}function Qs(t,e){let r=[];try{let n=N.readdirSync(t,{withFileTypes:!0});for(let s of n){if(ey.has(s.name)||s.name.startsWith("."))continue;let i=G.join(t,s.name);if(s.isDirectory())r.push(...Qs(i,e));else try{N.statSync(i).size<=ty&&r.push(G.relative(e,i))}catch{}}}catch{}return r}function sy(t){return new Promise(e=>{(0,_l.exec)("git rev-parse --short HEAD",{cwd:t},(r,n)=>{e(r?void 0:n.trim())})})}function Xs(t){return t.toLowerCase().replace(/[^a-z0-9_-]/g,"-").replace(/-+/g,"-").slice(0,40)}function Tl(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=Xs(o),c=i.description||"",l=Ys(t),u=G.join(l,a);N.existsSync(u)&&N.rmSync(u,{recursive:!0}),N.mkdirSync(u,{recursive:!0});let d=Qs(t,t),p=await sy(t),h=0,f=[];for(let y of d){if(h>=ry)break;try{let b=G.join(t,y),w=G.join(u,y);N.mkdirSync(G.dirname(w),{recursive:!0});let v=N.readFileSync(b);N.writeFileSync(w,v),h+=v.length,f.push(y)}catch{}}let m={name:a,createdAt:new Date().toISOString(),description:c,files:f,gitSha:p,totalBytes:h};N.writeFileSync(G.join(u,"_meta.json"),JSON.stringify(m,null,2));let g=xl(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)),ny(t,g),{success:!0,output:[`Checkpoint saved: "${a}"`,`Files: ${f.length} \xB7 Size: ${(h/1024).toFixed(0)} KB`,p?`Git: ${p}`:"",c?`Note: ${c}`:""].filter(Boolean).join(`
|
|
188
|
+
`)}}},{name:"checkpoint_list",description:"List all saved checkpoints with their dates and descriptions.",safety:"safe",parameters:{},execute:async()=>{let i=xl(t);if(!i.checkpoints.length)return{success:!0,output:"No checkpoints saved yet. Use checkpoint_save to create one."};let o=["Saved Checkpoints:",""];for(let a of i.checkpoints){let c=new Date(a.createdAt).toLocaleString();o.push(` "${a.name}" \u2014 ${c}`),o.push(` ${a.files.length} files \xB7 ${(a.totalBytes/1024).toFixed(0)} KB`),a.description&&o.push(` ${a.description}`),a.gitSha&&o.push(` git: ${a.gitSha}`),o.push("")}return{success:!0,output:o.join(`
|
|
189
|
+
`)}}},{name:"checkpoint_restore",description:"Restore a named checkpoint, overwriting current files with the saved state. This is DESTRUCTIVE \u2014 current unsaved changes will be lost. Use checkpoint_list to see available names.",safety:"dangerous",parameters:{name:{type:"string",description:"Checkpoint name to restore",required:!0},confirm:{type:"string",description:'Type "RESTORE" to confirm destructive operation',required:!0}},execute:async i=>{if(i.confirm!=="RESTORE")return{success:!1,output:"",error:'Restore cancelled. Set confirm="RESTORE" to proceed.'};let o=Xs(i.name.trim()),a=Ys(t),c=G.join(a,o);if(!N.existsSync(c))return{success:!1,output:"",error:`Checkpoint "${o}" not found. Run checkpoint_list to see available names.`};let l=G.join(c,"_meta.json"),u;try{u=JSON.parse(N.readFileSync(l,"utf-8"))}catch{return{success:!1,output:"",error:"Checkpoint metadata is corrupt."}}let d=[],p=[];for(let h of u.files)try{let f=G.join(c,h),m=G.join(t,h);if(!N.existsSync(f))continue;N.mkdirSync(G.dirname(m),{recursive:!0}),N.copyFileSync(f,m),d.push(h)}catch(f){p.push(`${h}: ${j(f)}`)}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=Xs(i.name.trim()),a=Ys(t),c=G.join(a,o);if(!N.existsSync(c))return{success:!1,output:"",error:`Checkpoint "${o}" not found.`};let l=G.join(c,"_meta.json"),u;try{u=JSON.parse(N.readFileSync(l,"utf-8"))}catch{return{success:!1,output:"",error:"Corrupt checkpoint metadata."}}let d=[],p=[],h=[];for(let y of u.files){let b=G.join(c,y),w=G.join(t,y);if(!N.existsSync(w)){p.push(y);continue}try{let v=N.readFileSync(b),_=N.readFileSync(w);v.equals(_)||d.push(y)}catch{}}let f=Qs(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 $l=require("child_process"),Oe=T(require("fs")),ie=T(require("path")),Qt=[{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 Zs(t){try{let e=JSON.parse(Oe.readFileSync(ie.join(t,"package.json"),"utf-8")),r={...e.dependencies,...e.devDependencies};if(r.vitest)return Qt[0];if(r.jest||e.scripts?.test?.includes("jest"))return Qt[1];if(r.mocha)return Qt[2]}catch{}return Oe.existsSync(ie.join(t,"pytest.ini"))||Oe.existsSync(ie.join(t,"pyproject.toml"))?Qt[3]:Oe.existsSync(ie.join(t,"go.mod"))?Qt[4]:null}function iy(t,e){let r={passed:0,failed:0,skipped:0,total:0,failures:[],duration:0,raw:t};if(e==="vitest"||e==="jest"){let n=t.match(/Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+passed,\s+)?(\d+)\s+total/);n&&(r.failed=parseInt(n[1]||"0"),r.passed=parseInt(n[2]||"0"),r.total=parseInt(n[3]||"0"),r.skipped=r.total-r.passed-r.failed);let s=t.match(/Duration\s+([\d.]+)s/);s&&(r.duration=parseFloat(s[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 n=t.match(/(\d+)\s+passed(?:,\s+(\d+)\s+failed)?/);n&&(r.passed=parseInt(n[1]||"0"),r.failed=parseInt(n[2]||"0"),r.total=r.passed+r.failed);let s=t.match(/in\s+([\d.]+)s/);s&&(r.duration=parseFloat(s[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 oy(t,e){let n=[`${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){n.push(""),n.push("Failed tests:");for(let s of t.failures.slice(0,5))n.push(` \u2717 ${s.test}`),s.message&&n.push(` ${s.message.split(`
|
|
192
|
+
`)[0]}`)}return t.total===0&&(n.push(""),n.push("Raw output (could not parse structured results):"),n.push(t.raw.slice(0,800))),n.join(`
|
|
193
|
+
`)}function Cl(t,e,r=6e4){return new Promise(n=>{(0,$l.exec)(t,{cwd:e,timeout:r,maxBuffer:8*1024*1024},(s,i,o)=>{let a=s?s.code:void 0;n({out:i||"",err:o||"",code:typeof a=="number"?a:s?1:0})})})}function Al(t){return[{name:"run_tests",description:"Run the project test suite. Auto-detects Jest, Vitest, Pytest, or Go test. Parses results and shows pass/fail counts and failure details.",safety:"safe",parameters:{filter:{type:"string",description:"Run only tests matching this pattern/file (optional)",required:!1},timeout:{type:"number",description:"Timeout in seconds (default: 60)",required:!1}},execute:async s=>{let i=Zs(t);if(!i)return{success:!0,output:"No test runner detected. Install Jest, Vitest, Pytest, or use Go modules."};let o=s.filter?` ${s.filter}`:"",a=(s.timeout||60)*1e3,c=`${i.command}${o}`,{out:l,err:u}=await Cl(c,t,a),d=(l+`
|
|
194
|
+
`+u).trim(),p=iy(d,i.name),h=oy(p,i.name);return{success:p.failed===0,output:h,error:p.failed>0?`${p.failed} test(s) failing`:void 0}}},{name:"test_coverage",description:"Run tests with coverage report. Shows which files/lines are covered. Uses the project's configured test runner.",safety:"safe",parameters:{},execute:async()=>{let s=Zs(t);if(!s)return{success:!0,output:"No test runner detected."};let i=`${s.command} ${s.coverageFlag}`,{out:o,err:a}=await Cl(i,t,12e4),c=(o+`
|
|
195
|
+
`+a).trim(),l=/(?:All files|TOTAL|coverage)\s*\|\s*([\d.]+)/i,u=c.match(l),d=u?`Overall coverage: ${u[1]}%`:"Coverage data generated.",p=c.indexOf("-------"),h=p>=0?c.slice(p,p+2e3):"";return{success:!0,output:[d,h||c.slice(-1500)].filter(Boolean).join(`
|
|
147
196
|
|
|
148
|
-
`)}}},{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
|
|
149
|
-
`,"import pytest",`from ${l.replace(/\//g,".")}.${c} import ${
|
|
150
|
-
`,...
|
|
151
|
-
`,` def test_${
|
|
197
|
+
`)}}},{name:"tdd_scaffold",description:"Generate a test file scaffold for a function/module BEFORE implementing it. Used to enforce TDD workflow: write the test first, then implement.",safety:"safe",parameters:{target_file:{type:"string",description:'The file you plan to implement (e.g. "src/utils/auth.ts")',required:!0},functions:{type:"string",description:"Comma-separated list of function/class names to generate tests for",required:!0},test_framework:{type:"string",description:'Override framework: "jest" | "vitest" | "pytest" (auto-detected if omitted)',required:!1}},execute:async s=>{let i=s.target_file,o=s.functions.split(",").map(m=>m.trim()).filter(Boolean),a=ie.extname(i),c=ie.basename(i,a),l=ie.dirname(i),u=Zs(t),d=s.test_framework||u?.name||"jest",p="",h="";if(d==="pytest")h=ie.join(l,`test_${c}.py`),p=[`"""Tests for ${i} \u2014 TDD scaffold (generated by Hablas)"""
|
|
198
|
+
`,"import pytest",`from ${l.replace(/\//g,".")}.${c} import ${o.join(", ")}
|
|
199
|
+
`,...o.map(m=>[`class Test${m.charAt(0).toUpperCase()+m.slice(1)}:`,` """Tests for ${m}"""
|
|
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(`
|
|
152
201
|
`))].join(`
|
|
153
|
-
`);else{let
|
|
154
|
-
`,...
|
|
202
|
+
`);else{let m=d==="vitest";h=i.replace(a,`.test${a}`);let g=`./${c}`;p=[m?"import { describe, it, expect, beforeEach } from 'vitest';":"// @ts-nocheck",`import { ${o.join(", ")} } from '${g}';
|
|
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(`
|
|
155
204
|
`))].join(`
|
|
156
|
-
`)}let
|
|
157
|
-
`)}}}]}var
|
|
158
|
-
`).length;let
|
|
159
|
-
`)}}}}var
|
|
160
|
-
`);return`- ${
|
|
161
|
-
${
|
|
205
|
+
`)}let f=ie.resolve(t,h);return Oe.mkdirSync(ie.dirname(f),{recursive:!0}),Oe.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 $t=T(require("fs")),we=T(require("path")),ay=new Set(["node_modules",".git","dist","build",".next","__pycache__",".cache",".hablas","coverage"]),cy=new Set([".ts",".tsx",".js",".jsx",".mjs",".py",".go",".rs",".java",".md",".json",".yaml",".yml",".toml"]),ly=500,uy=8e3;function El(t){return t.toLowerCase().replace(/[^a-z0-9\u0600-\u06FF]/g," ").split(/\s+/).filter(e=>e.length>2)}function Ol(t,e){let r=0;for(let n of t)e.has(n)&&r++;return t.size>0?r/t.size:0}function fy(t,e){let r=new Set(t.toLowerCase().replace(/[/_-]/g," ").split(/\s+/).filter(n=>n.length>1));return Ol(e,r)}function dy(t,e){let n=(e-t)/(1e3*60*60*24);return n<1?1:n<7?.5:n<30?.2:.05}function py(t,e){if(e.size===0)return 0;let r=new Set(El(t.slice(0,uy)));return Ol(e,r)}function hy(t){return/\b(index|main|app|server|cli|entry)\.(ts|tsx|js|jsx|mjs|py|go|rs)$/.test(t)}function Rl(t,e,r=[]){if(r.length>=ly)return r;try{let n=$t.readdirSync(t,{withFileTypes:!0});for(let s of n){if(ay.has(s.name)||s.name.startsWith("."))continue;let i=we.join(t,s.name);if(s.isDirectory())Rl(i,e,r);else if(cy.has(we.extname(s.name)))try{let o=$t.statSync(i);if(o.size>200*1024)continue;let a=we.relative(e,i);r.push({path:a,mtime:o.mtimeMs,size:o.size,lines:0,isEntry:hy(a)})}catch{}}}catch{}return r}function my(t){let e=Date.now(),{query:r,workingDir:n,topK:s=12,recentlyTouched:i=[],importantFiles:o=[],skipContentScan:a=!1}=t,c=new Set(El(r)),l=new Set(i.map(f=>we.normalize(f))),u=new Set(o.map(f=>we.normalize(f))),d=Date.now(),p=Rl(n,n),h=[];for(let f of p){let m=[],g=0,y=fy(f.path,c)*.35;y>.1&&(g+=y,m.push(`name-match(${(y*100).toFixed(0)}%)`));let b=dy(f.mtime,d)*.2;if(b>.05&&(g+=b,m.push(`fresh(${(b*100).toFixed(0)}%)`)),l.has(we.normalize(f.path))&&(g+=.25,m.push("touched-in-session")),u.has(we.normalize(f.path))&&(g+=.15,m.push("high-centrality")),f.isEntry&&(g+=.05,m.push("entry-point")),!a&&c.size>0&&g>0)try{let w=$t.readFileSync(we.join(n,f.path),"utf-8");f.lines=w.split(`
|
|
207
|
+
`).length;let v=py(w,c)*.3;v>.05&&(g+=v,m.push(`content-match(${(v*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,s),totalCandidates:p.length,buildTimeMs:Date.now()-e}}function Il(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=my({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 n=[`Top ${r.files.length} relevant files for: "${e.query}"`,`(scanned ${r.totalCandidates} files in ${r.buildTimeMs}ms)`,""];for(let s of r.files){let i=(s.score*100).toFixed(0).padStart(3);n.push(` [${i}%] ${s.path}${s.lines?` (${s.lines}L)`:""}`),n.push(` ${s.reasons.join(" \xB7 ")}`)}return{success:!0,output:n.join(`
|
|
208
|
+
`)}}}}var Ge=class{tools=new Map;constructor(e,r){let n=Tc(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Oc(e,r)),this.tools.set("search_codebase",Rc(e)),this.tools.set("detect_bugs",Pc(e)),this.tools.set("web_search",Uc());for(let s of Nc())this.tools.set(s.name,s);for(let s of zc(e))this.tools.set(s.name,s);for(let s of Zc())this.tools.set(s.name,s);this.tools.set("download_asset",ol(e));for(let s of pl(e,r))this.tools.set(s.name,s);for(let s of ml(e))this.tools.set(s.name,s);for(let s of bl(e))this.tools.set(s.name,s);for(let s of Sl(e))this.tools.set(s.name,s);for(let s of Tl(e))this.tools.set(s.name,s);for(let s of Al(e))this.tools.set(s.name,s);this.tools.set("suggest_relevant_files",Il(e))}get(e){return this.tools.get(e)}register(e){this.tools.set(e.name,e)}unregisterWhere(e){for(let r of Array.from(this.tools.keys()))e(r)&&this.tools.delete(r)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
|
|
209
|
+
`);return`- ${r.name} [${r.safety}]: ${r.description}
|
|
210
|
+
${n}`}).join(`
|
|
162
211
|
|
|
163
|
-
`)}};var
|
|
164
|
-
... [truncated to fit context budget]`}var
|
|
165
|
-
${c}`),
|
|
166
|
-
${
|
|
212
|
+
`)}};var Ml=T(require("crypto"));function ei(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 At=class{cache=new Map;budget;usedTokens=0;accessHistory=[];constructor(e){this.budget=e.contextBudget}addFile(e,r,n){let s=this.computeHash(r),i=this.cache.get(e);if(i&&i.hash===s){i.lastUsed=Date.now(),i.accessCount++;return}let o=ei(r),a=n?.importance??this.autoImportance(e,r);this.usedTokens+o>this.budget&&this.evictToFit(o);let c={path:e,content:r,hash:s,lastUsed:Date.now(),tokenCount:o,importance:a,accessCount:i?i.accessCount+1:1,relatedFiles:i?.relatedFiles||[],summarized:!1,tags:n?.tags||this.autoTag(e)};i&&(this.usedTokens-=i.tokenCount),this.cache.set(e,c),this.usedTokens+=o,this.recordAccess(e)}hasChanged(e,r){let n=this.cache.get(e);return n?n.hash!==this.computeHash(r):!0}buildContext(e){let r=e||this.budget,n=Array.from(this.cache.values()).map(o=>({...o,score:this.computeScore(o)})).sort((o,a)=>a.score-o.score),s=0,i=[];for(let o of n){if(s+o.tokenCount>r){if(o.importance>=7){let a=r-s;if(a>200){let c=Zt(o.content,a);i.push(`--- ${o.path} (truncated, importance: ${o.importance}) ---
|
|
214
|
+
${c}`),s+=a}}continue}i.push(`--- ${o.path} ---
|
|
215
|
+
${o.content}`),s+=o.tokenCount}return i.join(`
|
|
167
216
|
|
|
168
|
-
`)}buildAgentContext(e,
|
|
217
|
+
`)}buildAgentContext(e,r){let n=r||Math.floor(this.budget*.5),i={alex:[".ts",".js",".tsx",".jsx",".py",".go",".rs",".css",".html"],bob:[".md",".json",".yaml",".yml",".toml",".xml","schema","config"],david:[".md",".csv",".json",".txt",".sql"],emma:[".md",".txt",".json"],hablas:[]}[e]||[],o=Array.from(this.cache.values()).filter(l=>i.length===0?!0:i.some(u=>l.path.includes(u))).sort((l,u)=>this.computeScore(u)-this.computeScore(l)),a=0,c=[];for(let l of o){if(a+l.tokenCount>n)break;c.push(`--- ${l.path} ---
|
|
169
218
|
${l.content}`),a+=l.tokenCount}return c.join(`
|
|
170
219
|
|
|
171
|
-
`)}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,
|
|
172
|
-
...(compressed from `+
|
|
173
|
-
...(compressed from `+
|
|
174
|
-
`)}async function
|
|
175
|
-
`)}function
|
|
176
|
-
Stack: ${
|
|
177
|
-
Summary: ${
|
|
178
|
-
Rationale: ${
|
|
179
|
-
Outcome: ${
|
|
180
|
-
`).slice(0,s)}},Gs=null;function $t(){return Gs||(Gs=new Vs),Gs}function pt(t,e,s){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.","",H("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."]),"",H("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."]),"",H("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"]),"",H("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."]),"",H("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."]),"",H("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."]),"",H("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."]),"",H("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."]),"",H("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"]),"",H("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"]),"",H("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."]),"",H("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(!s)return[];let r=$t().buildContextBlock(s,2500);return r.trim()?[H("PERSISTENT MEMORY",r),""]:[]})(),H("TASK PROFILE",Na(e)),"",H("CURRENT PROJECT CONTEXT",La(t)),"",H("REASONING PROTOCOL",Da(e))].join(`
|
|
181
|
-
`)}function
|
|
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(([s,i])=>({key:s,...i,score:this.computeScore(i)})).sort((s,i)=>s.score-i.score),n=0;for(let s of r){if(n>=e)break;s.importance>=9||(n+=s.tokenCount,this.usedTokens-=s.tokenCount,this.cache.delete(s.key))}}evict(e){this.evictToFit(e)}clear(){this.cache.clear(),this.usedTokens=0,this.accessHistory=[]}computeScore(e){let s=(Date.now()-e.lastUsed)/6e4,i=Math.exp(-s/30),o=Math.log1p(e.accessCount);return e.importance*(i+o)}autoImportance(e,r){let n=5;/\b(config|tsconfig|package\.json|\.env|Dockerfile|docker-compose)\b/i.test(e)&&(n=8),/\b(index|main|app|server)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=7),/\.(test|spec)\.(ts|js|tsx|jsx)$/i.test(e)&&(n=3);let s=ei(r);return s>2e3&&(n=Math.max(1,n-1)),s>5e3&&(n=Math.max(1,n-2)),n}autoTag(e){let r=[];return/\.(ts|tsx)$/.test(e)&&r.push("typescript"),/\.(js|jsx)$/.test(e)&&r.push("javascript"),/\.json$/.test(e)&&r.push("config"),/\.md$/.test(e)&&r.push("documentation"),/\.(css|scss|sass)$/.test(e)&&r.push("style"),/\.(test|spec)\./i.test(e)&&r.push("test"),/src\//.test(e)&&r.push("source"),r}recordAccess(e){this.accessHistory.length>50&&(this.accessHistory=this.accessHistory.slice(-50));let r=this.accessHistory[this.accessHistory.length-1];if(r&&Date.now()-this.getGroupTime(r)<3e4){if(!r.includes(e)){r.push(e);for(let n of r)if(n!==e){let s=this.cache.get(n);s&&!s.relatedFiles.includes(e)&&s.relatedFiles.push(e)}}}else this.accessHistory.push([e])}getGroupTime(e){return Date.now()}computeHash(e){return Ml.createHash("md5").update(e).digest("hex")}};var gy=0;function er(){return`msg_${Date.now()}_${++gy}`}function Et(t){return Math.ceil(t.length/4)}var Ot=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=200,n=128e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=Et(e);this.messages.push({id:er(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:s,compressed:!1,tags:["system"]}),this.totalTokens=s}getSessionId(){return this.sessionId}addUserMessage(e,r){let n=er(),s=Et(e);return this.messages.push({id:n,role:"user",content:e,timestamp:Date.now(),priority:r?.priority||"high",tokenEstimate:s,compressed:!1,tags:r?.tags||["user-input"]}),this.totalTokens+=s,this.trimIfNeeded(),n}addAssistantMessage(e,r,n){let s=er(),i=Et(e),o={id:s,role:"assistant",content:e,timestamp:Date.now(),priority:"normal",agent:n||"hablas",tokenEstimate:i,compressed:!1,tags:n?[`agent:${n}`]:["assistant"]};return r&&r.length>0&&(o.tool_calls=r,o.tags.push("has-tools")),this.messages.push(o),this.totalTokens+=i,n&&this.agentMessageCounts.set(n,(this.agentMessageCounts.get(n)||0)+1),this.trimIfNeeded(),s}addToolMessage(e,r){let n=er(),s=Et(e);return this.messages.push({id:n,role:"tool",content:e,timestamp:Date.now(),priority:e.startsWith("Error")?"high":"low",tokenEstimate:s,compressed:!1,tags:r?[`tool:${r}`]:["tool-result"]}),this.totalTokens+=s,this.trimIfNeeded(),n}getMessages(){return this.messages.map(e=>{let r={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(r.tool_calls=e.tool_calls),r})}getEnhancedMessages(){return[...this.messages]}getHistory(){return this.messages.slice(1).map(e=>({role:e.role,content:e.content,tool_calls:e.tool_calls}))}getAgentMessages(e){return this.messages.filter(r=>r.agent===e)}getAgentStats(){return new Map(this.agentMessageCounts)}getTotalTokens(){return this.totalTokens}getMessageCount(){return this.messages.length}clear(){let e=this.messages[0];this.messages=[e],this.totalTokens=e.tokenEstimate,this.agentMessageCounts.clear()}updateSystemPrompt(e){let r=Et(e),n={id:er(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]};if(this.messages.length===0){this.messages=[n],this.recalculateTokens();return}this.messages[0]=n,this.recalculateTokens(),this.trimIfNeeded()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let c=s[a.priority]-s[o.priority];return c!==0?c:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,1200)+`
|
|
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=Et(e.content),this.totalTokens-=n-e.tokenEstimate}recalculateTokens(){this.totalTokens=this.messages.reduce((e,r)=>e+r.tokenEstimate,0)}toJSON(){return JSON.stringify({sessionId:this.sessionId,messageCount:this.messages.length,totalTokens:this.totalTokens,messages:this.messages,agentStats:Object.fromEntries(this.agentMessageCounts)},null,2)}fromJSON(e){let r=JSON.parse(e);if(!r.messages||!Array.isArray(r.messages))throw new Error("Invalid session JSON data structure.");this.sessionId=r.sessionId||`session_${Date.now()}`,this.messages=r.messages,this.totalTokens=r.totalTokens||0,this.agentMessageCounts=new Map(Object.entries(r.agentStats||{})),this.recalculateTokens()}getSessionInfo(){return{id:this.sessionId,messages:this.messages.length,tokens:this.totalTokens,agents:Object.fromEntries(this.agentMessageCounts),forks:Array.from(this.forks.keys()),snapshots:this.snapshots.length}}};var It=T(require("fs")),Pl=T(require("path"));var O=T(require("fs")),R=T(require("path"));function yy(t){let e=R.join(t,"package.json");if(O.existsSync(e))try{let r=JSON.parse(O.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(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 wy(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 by(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 vy(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 Rt(t){let e=yy(t),r=wy(t),n=by(t),s=vy(t),i=O.existsSync(R.join(t,"Dockerfile"))||O.existsSync(R.join(t,"docker-compose.yml"))||O.existsSync(R.join(t,"docker-compose.yaml")),o=O.existsSync(R.join(t,".github","workflows"))||O.existsSync(R.join(t,".gitlab-ci.yml"))||O.existsSync(R.join(t,"Jenkinsfile")),a=O.existsSync(R.join(t,"__tests__"))||O.existsSync(R.join(t,"tests"))||O.existsSync(R.join(t,"test"))||O.existsSync(R.join(t,"spec")),c=O.existsSync(R.join(t,".git")),l=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)O.existsSync(R.join(t,m))&&l.push(m);let 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:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:c,gitBranch:s,envFiles:l,configFiles:d,entryPoints:h}}function zr(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 Mt(t,e){let r=[],n=Pl.join(t,"package.json");if(It.existsSync(n))try{let o=JSON.parse(It.readFileSync(n,"utf-8"));r.push(`Project: ${o.name||"unknown"}${o.version?` v${o.version}`:""}`),o.description&&r.push(`Description: ${o.description}`)}catch{}let s=Rt(t);r.push(`Framework: ${s.framework}`),r.push(`Language: ${s.language}`),r.push(`Package Manager: ${s.packageManager}`),r.push(`Git: ${s.hasGit?s.gitBranch||"present":"absent"}`);let i=Sy(t,16);return i.length>0&&r.push(`Top-level: ${i.join(", ")}`),e?.workspace?.envParsing&&s.envFiles.length>0&&r.push(`Env files: ${s.envFiles.join(", ")}`),r.push(`Directory: ${t}`),r.join(`
|
|
224
|
+
`)}function Sy(t,e){try{return It.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}var le=T(require("fs")),si=T(require("path")),Dl=T(require("os")),Nl=T(require("crypto")),tr=si.join(Dl.homedir(),".hablas"),ti=si.join(tr,"memory.json"),jl=1,Fl=2e3,xy=1600,_y=8e3;function ky(){return Nl.randomBytes(8).toString("hex")}function Ll(t){return t==="critical"?4:t==="high"?3:t==="normal"?2:1}function Ty(t,e){let r=t+".tmp."+process.pid;le.writeFileSync(r,e,"utf-8"),le.renameSync(r,t)}var ni=class{store;dirty=!1;flushTimer=null;constructor(){this.store=this.load()}load(){try{if(le.existsSync(tr)||le.mkdirSync(tr,{recursive:!0}),le.existsSync(ti)){let e=JSON.parse(le.readFileSync(ti,"utf-8"));if(e.version===jl)return e}}catch{}return{version:jl,entries:{},keyIndex:{},tagIndex:{},projectIndex:{}}}scheduleFlush(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush(),this.flushTimer=null},500))}flush(){if(this.dirty)try{le.existsSync(tr)||le.mkdirSync(tr,{recursive:!0}),Ty(ti,JSON.stringify(this.store,null,2)),this.dirty=!1}catch{}}addToIndex(e){this.store.keyIndex[e.key]=e.id;for(let r of e.tags)this.store.tagIndex[r]||(this.store.tagIndex[r]=[]),this.store.tagIndex[r].includes(e.id)||this.store.tagIndex[r].push(e.id);e.project&&(this.store.projectIndex[e.project]||(this.store.projectIndex[e.project]=[]),this.store.projectIndex[e.project].includes(e.id)||this.store.projectIndex[e.project].push(e.id))}removeFromIndex(e){delete this.store.keyIndex[e.key];for(let r of e.tags)this.store.tagIndex[r]&&(this.store.tagIndex[r]=this.store.tagIndex[r].filter(n=>n!==e.id),this.store.tagIndex[r].length||delete this.store.tagIndex[r]);e.project&&this.store.projectIndex[e.project]&&(this.store.projectIndex[e.project]=this.store.projectIndex[e.project].filter(r=>r!==e.id),this.store.projectIndex[e.project].length||delete this.store.projectIndex[e.project])}remember(e){let r=this.store.keyIndex[e.key],n=Date.now(),s=e.value.slice(0,_y);if(r&&this.store.entries[r]){let a=this.store.entries[r];return this.removeFromIndex(a),a.value=s,a.updatedAt=n,e.tags&&(a.tags=e.tags),e.priority&&(a.priority=e.priority),e.ttl!==void 0&&(a.ttl=n+e.ttl),this.addToIndex(a),this.scheduleFlush(),a.id}this.maybeEvict();let i=ky(),o={id:i,kind:e.kind,key:e.key,value:s,tags:e.tags??[],project:e.project,priority:e.priority??"normal",createdAt:n,updatedAt:n,accessCount:0,lastAccessed:n,ttl:e.ttl?n+e.ttl:void 0};return this.store.entries[i]=o,this.addToIndex(o),this.scheduleFlush(),i}recall(e){let r=this.store.keyIndex[e];if(!r)return null;let n=this.store.entries[r];return n?n.ttl&&Date.now()>n.ttl?(this.forget(e),null):(n.accessCount++,n.lastAccessed=Date.now(),this.scheduleFlush(),n):null}forget(e){let r=this.store.keyIndex[e];if(!r)return!1;let n=this.store.entries[r];return n?(this.removeFromIndex(n),delete this.store.entries[r],this.scheduleFlush(),!0):!1}search(e,r){let n=Date.now(),s=r?.limit??10,i=r?.minScore??.1,o=e.toLowerCase(),a=o.split(/\s+/).filter(l=>l.length>2),c=[];for(let l of Object.values(this.store.entries)){if(l.ttl&&n>l.ttl||r?.kind&&l.kind!==r.kind||r?.project&&l.project!==r.project)continue;let u=0,d="value",p=l.key.toLowerCase(),h=l.value.toLowerCase();if(p===o)u=1,d="key";else if(p.includes(o))u=Math.max(u,.8),d="key";else if(l.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+Ll(l.priority)*.05+Math.min(.1,l.accessCount*.01)),c.push({entry:l,score:u,matchedOn:d}))}return c.filter(l=>l.score>=i).sort((l,u)=>u.score-l.score).slice(0,s)}getProjectMemory(e){return(this.store.projectIndex[e]??[]).map(r=>this.store.entries[r]).filter(r=>!!r&&(!r.ttl||Date.now()<r.ttl))}getByKind(e,r=20){return Object.values(this.store.entries).filter(n=>n.kind===e&&(!n.ttl||Date.now()<n.ttl)).sort((n,s)=>s.updatedAt-n.updatedAt).slice(0,r)}getRecent(e=10){return Object.values(this.store.entries).filter(r=>!r.ttl||Date.now()<r.ttl).sort((r,n)=>n.lastAccessed-r.lastAccessed).slice(0,e)}getStats(){let e={total:0};for(let r of Object.values(this.store.entries))e.total++,e[r.kind]=(e[r.kind]??0)+1;return e}maybeEvict(){let e=Object.keys(this.store.entries).length;if(e<Fl)return;let r=Date.now();for(let n of Object.values(this.store.entries))n.ttl&&r>n.ttl&&(this.removeFromIndex(n),delete this.store.entries[n.id],e--);if(e>=Fl){let n=Object.values(this.store.entries).map(s=>({id:s.id,score:Ll(s.priority)*10+s.accessCount+s.lastAccessed/1e12})).sort((s,i)=>s.score-i.score);for(let{id:s}of n.slice(0,e-xy)){let i=this.store.entries[s];i&&(this.removeFromIndex(i),delete this.store.entries[s])}}}rememberProject(e,r){this.remember({kind:"project",key:`project:${e}`,priority:"high",value:`Name: ${r.name}
|
|
225
|
+
Stack: ${r.stack}${r.summary?`
|
|
226
|
+
Summary: ${r.summary}`:""}`,tags:["project",r.stack.toLowerCase().slice(0,20)],project:e})}rememberDecision(e,r,n){this.remember({kind:"decision",key:`decision:${e}:${r.slice(0,60)}`,value:`Decision: ${r}
|
|
227
|
+
Rationale: ${n}`,tags:["decision","architecture"],project:e,priority:"high"})}rememberPreference(e,r){this.remember({kind:"preference",key:`pref:${e}`,value:r,tags:["preference","user"],priority:"high"})}rememberTaskSummary(e,r,n){this.remember({kind:"task_summary",key:`task:${e}:${r.slice(0,60)}:${Date.now()}`,value:`Task: ${r}
|
|
228
|
+
Outcome: ${n}`,tags:["task","completed"],project:e,priority:"normal",ttl:720*60*60*1e3})}buildContextBlock(e,r=3e3){let n=[];if(e){let i=this.getProjectMemory(e);if(i.length>0){n.push("## Memory: this project");for(let o of i.slice(0,8))n.push(`[${o.kind}] ${o.value.replace(/\n/g," \u2014 ").slice(0,200)}`)}}let s=this.getByKind("preference",5);if(s.length>0){n.push("## Memory: user preferences");for(let i of s)n.push(`- ${i.key.replace("pref:","")}: ${i.value.slice(0,100)}`)}return n.join(`
|
|
229
|
+
`).slice(0,r)}},ri=null;function rr(){return ri||(ri=new ni),ri}function Pt(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.","",re("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."]),"",re("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."]),"",re("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"]),"",re("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."]),"",re("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."]),"",re("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."]),"",re("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."]),"",re("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."]),"",re("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"]),"",re("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"]),"",re("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."]),"",re("FINAL RESPONSE CONTRACT",["For casual turns:","- keep it short, warm, and natural","- avoid robotic phrasing","","For read-only and analysis answers:","- answer directly","- structure only as much as the task needs","- cite observed evidence in plain language when relevant","","For implementation, upgrade, refactor, frontend, asset, or repair work:","- present the final answer as a compact executive report","- use markdown headings when the work is substantial","- prefer this structure:"," - ## Completed"," - ## Changed Files and Assets"," - ## Verification"," - ## Remaining Notes","- under each section, use short bullets or a compact table when useful","- mention any added/downloaded assets explicitly","- mention what was verified explicitly","- mention what remains unverified or incomplete explicitly","- when useful, end with one compact high-value next step or recommendation","- keep the report clean and premium, not chatty and not status-theatre","","For failures:","- be explicit, technical, honest","- do not pretend the task succeeded","- if partial work happened, say exactly what succeeded and what failed","- if nothing changed, say that clearly"]),"",...(()=>{if(!r)return[];let n=rr().buildContextBlock(r,2500);return n.trim()?[re("PERSISTENT MEMORY",n),""]:[]})(),re("TASK PROFILE",Ay(e)),"",re("CURRENT PROJECT CONTEXT",$y(t)),"",re("REASONING PROTOCOL",Cy(e))].join(`
|
|
230
|
+
`)}function Cy(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(`
|
|
182
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(`
|
|
183
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(`
|
|
184
|
-
`)}function
|
|
185
|
-
`):e;return["====================",t,"====================",
|
|
186
|
-
`)}function
|
|
233
|
+
`)}function re(t,e){let r=Array.isArray(e)?e.join(`
|
|
234
|
+
`):e;return["====================",t,"====================",r].join(`
|
|
235
|
+
`)}function $y(t){return t.trim()||"No project context captured."}function Ay(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(`
|
|
187
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(`
|
|
188
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(`
|
|
189
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(`
|
|
190
|
-
`)}var
|
|
191
|
-
${
|
|
192
|
-
`),(await this.prompt(` ${
|
|
193
|
-
`).filter(Boolean).slice(-
|
|
194
|
-
`),"utf-8")}catch{}}};var
|
|
239
|
+
`)}var Ey=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|yep|nope|sure|cool|got it|noted|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك|ايوه|لا|نعم|صح|ماشي|عادي|اوك|oke|oki|👍|✅)[.!?\s]*$/i,Oy=/\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=/(اعمل|افعل|اكتب|انشئ|انشأ|إنشاء|اضف|اضافة|أضف|إضافة|عدل|عدّل|تعديل|احذف|حذف|اصلح|إصلاح|صلح|حسّن|تحسين|ارفع|رفع|نفذ|تنفيذ|شغّل|شغل|ابنِ|بناء|اصنع|ادمج|دمج|ربط|اربط|اضبط|ضبط|حوّل|تحويل|ولّد|توليد|طوّر|تطوير|نزّل|تنزيل|نشر|اطلق|اجرِ|جرّب|اختبر|فعّل|عطّل|حدّث|تحديث|كمّل|خلّص|انهِ|ابدأ|أوقف|اعد|ولد|احضر|جيب|حط|وصّل|اتصل|شارك|ابدا|طبق|اطبق|بدّل|استبدل|غيّر|أوصل)/,Iy=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent|addd|dlete|edti|wriet|insatll|confgure|refactr|debugg|buidl|genrate|complet|migarate)\b/i,My=/\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,Py=/(معمارية|تصميم|خطة|متطلبات|بحث|قارن|فهم|اشرح|وضح|ما هو|ما هي|لماذا|الفرق|مقارنة|تحليل|تقييم|دراسة|مراجعة|ملخص|نظرة عامة|توثيق|مواصفات)/,jy=/\b(read|inspect|check|show|list|find|what is|which|where|print|display|view|look at|open|see|tell me|get|retrieve)\b/i,Fy=/(اقرأ|اعرض|اظهر|فتش|شوف|وين|انظر|اطلع|اجلب|احضر|قرأ|أظهر|أعرض|بيّن|ليش|وش|إيش)/,Ul=/\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,ql=/(واجهة|خلفية|قاعدة بيانات|مكون|صفحة|نموذج|مسار|خادم|عميل|تطبيق|موقع|واجهة برمجة|مصادقة|تسجيل|مستخدم|جدول|مخطط|ملف|مجلد|مشروع|مكتبة|حزمة|إعداد|تكوين|نشر|اختبار|بناء|سجل|خطأ|أداء|ذاكرة|نسخ احتياطي)/,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,Dy=/(كمّل|تكملة|أكمل|استمر|استمرار|من السابق|المشروع الحالي|ما اكتملنا|واصل|من اللي وقفنا|اللي بدأناه|كمل|تابع|متابعة)/,Ny=/\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,Uy=/(بدون أسئلة|ما تسأل|روح عليه|مباشرة|كمّل لحالك|تلقائي|أوتوماتيك|انجزه|بدون سؤال|على طول|خلص بدون)/,Bl=/\b((current|project) version( of (this|the|current))? project|package version|what version (are we|is this)|project version)\b/i;function qy(t){let e=t.toLowerCase(),r={implementation:0,analysis:0,read:0,casual:0,continuity:!1,oneStep:!1};r.continuity=Ly.test(e)||Dy.test(t),r.oneStep=Ny.test(e)||Uy.test(t),r.continuity&&(r.implementation+=6),r.oneStep&&(r.implementation+=3),Oy.test(e)&&(r.implementation+=5),Ry.test(t)&&(r.implementation+=5),Iy.test(e)&&(r.implementation+=4),My.test(e)&&(r.analysis+=4),Py.test(t)&&(r.analysis+=4),jy.test(e)&&(r.read+=3),Fy.test(t)&&(r.read+=3),Bl.test(t)&&(r.read+=10),(Ul.test(e)||ql.test(t))&&(r.implementation+=2);let s=t.split(/\s+/).filter(Boolean).length;return s<=4&&r.implementation<=3&&(r.read+=2),t.endsWith("?")&&(r.read+=2,r.analysis+=1),s>20&&(r.implementation+=2),s>40&&(r.implementation+=2),r}function By(t){return t<=4?"XS":t<=10?"S":t<=25?"M":t<=50?"L":"XL"}function nr(t){let e=t.trim(),r=e.toLowerCase(),n=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 s=qy(e),i=Ul.test(r)||ql.test(e),o=Bl.test(e);if(s.implementation>=5||s.implementation===Math.max(s.implementation,s.analysis,s.read)&&s.implementation>=3)return{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:s.continuity,oneStepDelivery:s.oneStep,requiresProjectContext:!0,complexity:By(n),reason:s.continuity?"Continuation of in-progress work \u2014 loading existing context.":"Implementation request detected \u2014 tool-based execution required."};if(s.analysis>=4&&s.analysis>=s.implementation)return{kind:"analysis",needsTools:i,needsWrite:!1,continuity:s.continuity,oneStepDelivery:!1,requiresProjectContext:i,complexity:"M",reason:i?"Architecture/analysis with project reference \u2014 inspection needed.":"Architecture/design reasoning \u2014 text-first turn."};if(s.read>=3||e.endsWith("?")){let a=i||o;return{kind:"read",needsTools:a,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:a,complexity:"S",reason:a?o?"Project version/metadata query \u2014 requires reading package.json or manifest.":"Read/inspect request \u2014 file inspection needed.":"Direct factual question \u2014 answer from knowledge."}}return{kind:"analysis",needsTools:i,needsWrite:!1,continuity:s.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 Hl(t){let e=nr(t);return{input:t,profile:e,plan:Hy(e)}}var Vl=T(require("readline")),be=T(require("fs")),ue=T(require("path")),zl=T(require("os"));var Kr=ue.join(zl.homedir(),".hablas","history"),Gr=500,Wy=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),Vy=["read ","edit ","write ","delete ","open ","patch ","inspect ","use "],zy=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"]),Wl=["/help","/status","/model","/models","/provider","/history","/clear","/workspace","/doctor","/version","/about","/exit","/quit"],Jr=class{constructor(e=process.cwd()){this.workingDir=e;this.loadHistory(),this.rl=this.createReadline()}rl;history=[];fileCache=[];fileCacheTime=0;createReadline(){return Vl.createInterface({input:process.stdin,output:process.stdout,terminal:!0,history:[...this.history].reverse(),historySize:Gr,completer:e=>this.autocomplete(e)})}async prompt(e){return new Promise(r=>{process.stdin.isTTY&&process.stdout.write("\r\x1B[K"),this.rl.question(e,n=>{let s=n.trim();s&&(this.history.push(s),this.history=this.history.slice(-Gr),this.saveHistory()),r(n)})})}async confirm(e){return(await this.prompt(` ${S.warning("?")} ${e} ${S.muted("[Y/n]")} `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return console.log(`
|
|
240
|
+
${S.error("\u26A0")} ${e}`),console.log(` ${S.muted("Type yes to confirm this dangerous action.")}
|
|
241
|
+
`),(await this.prompt(` ${S.error("\u2192")} `)).trim().toLowerCase()==="yes"}close(){this.saveHistory(),this.rl.close()}autocomplete(e){if(e.startsWith("/")){let n=Wl.filter(s=>s.startsWith(e));return[n.length?n:Wl,e]}for(let n of Vy)if(e.toLowerCase().includes(n)){let s=e.split(n).pop()??"";if(s&&!s.includes(" "))try{let i=ue.dirname(s)||".",o=ue.basename(s),a=ue.resolve(this.workingDir,i),c=be.readdirSync(a).filter(l=>l.startsWith(o)).slice(0,8).map(l=>e.slice(0,e.lastIndexOf(s))+ue.join(i,l));if(c.length)return[c,e]}catch{}}let r=e.match(/#([\w./-]*)$/);if(r){let n=r[1],s=this.getProjectFiles(),i=s.filter(o=>o.toLowerCase().startsWith(n.toLowerCase())).map(o=>e.slice(0,e.length-r[0].length)+"#"+o);return[i.length?i:s.slice(0,20).map(o=>e.slice(0,e.length-r[0].length)+"#"+o),e]}return[[],e]}getProjectFiles(){let e=Date.now();if(this.fileCache.length>0&&e-this.fileCacheTime<1e4)return this.fileCache;let r=[];return this.scanDir(this.workingDir,"",r,3),this.fileCache=r,this.fileCacheTime=e,r}scanDir(e,r,n,s,i=0){if(!(i>=s))try{let o=be.readdirSync(e,{withFileTypes:!0});for(let a of o){if(a.name.startsWith(".")||Wy.has(a.name))continue;let c=r?`${r}/${a.name}`:a.name;if(a.isDirectory())this.scanDir(ue.join(e,a.name),c,n,s,i+1);else{let l=ue.extname(a.name).toLowerCase();(zy.has(l)||a.name==="Dockerfile"||a.name==="Makefile")&&n.push(c)}}}catch{}}loadHistory(){try{be.existsSync(Kr)&&(this.history=be.readFileSync(Kr,"utf-8").split(`
|
|
242
|
+
`).filter(Boolean).slice(-Gr))}catch{}}saveHistory(){try{let e=ue.dirname(Kr);be.existsSync(e)||be.mkdirSync(e,{recursive:!0}),be.writeFileSync(Kr,this.history.slice(-Gr).join(`
|
|
243
|
+
`),"utf-8")}catch{}}};var Ky={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Gy=`
|
|
195
244
|
## Reasoning Protocol
|
|
196
245
|
|
|
197
246
|
Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
|
|
@@ -220,26 +269,26 @@ After receiving a tool result, think again:
|
|
|
220
269
|
- One tool call per turn. Wait for the result before the next call.
|
|
221
270
|
- If a tool fails, analyze the error in <thinking> before retrying.
|
|
222
271
|
- When done, give a concise final answer WITHOUT <thinking> tags.
|
|
223
|
-
`.trim(),
|
|
272
|
+
`.trim(),Jy=`
|
|
224
273
|
## Reasoning
|
|
225
274
|
For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
|
|
226
275
|
The user will NOT see thinking blocks. One tool call per turn.
|
|
227
|
-
`.trim(),
|
|
276
|
+
`.trim(),ii=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Ky,...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}
|
|
228
277
|
|
|
229
|
-
${
|
|
278
|
+
${Jy}`:`${e}
|
|
230
279
|
|
|
231
|
-
${
|
|
280
|
+
${Gy}`}parseThinking(e){if(!e)return{thinking:"",visibleContent:"",hasThinking:!1};let r=[],n=e,s=/<thinking>([\s\S]*?)<\/thinking>/gi,i;for(;(i=s.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"");let o=/<think>([\s\S]*?)<\/think>/gi;for(;(i=o.exec(e))!==null;)r.push(i[1].trim());n=n.replace(/<think>[\s\S]*?<\/think>/gi,"");let a=/<thinking>([\s\S]*)$/i.exec(n);a&&(r.push(a[1].trim()),n=n.replace(/<thinking>[\s\S]*$/i,""));let c=/<think>([\s\S]*)$/i.exec(n);return c&&(r.push(c[1].trim()),n=n.replace(/<think>[\s\S]*$/i,"")),{thinking:r.join(`
|
|
232
281
|
|
|
233
|
-
`).trim(),visibleContent:
|
|
282
|
+
`).trim(),visibleContent:n.trim(),hasThinking:r.length>0}}startTurn(){this.turnSteps=[],this.stepCounter=0}recordStep(e){let r={...e,stepIndex:this.stepCounter++,timestamp:new Date().toISOString()};return this.turnSteps.push(r),r}recordObservation(e,r){let n=this.turnSteps[this.turnSteps.length-1];n&&(n.observation=e,r&&(n.reflection=r))}getSteps(){return this.turnSteps}isOverBudget(){return this.stepCounter>=this.config.maxSteps}remainingBudget(){return Math.max(0,this.config.maxSteps-this.stepCounter)}buildSelfEvalPrompt(e,r,n){return`
|
|
234
283
|
<self_eval>
|
|
235
284
|
You just completed this task: "${e}"
|
|
236
285
|
|
|
237
286
|
Your answer was:
|
|
238
287
|
"""
|
|
239
|
-
${
|
|
288
|
+
${r.slice(0,1500)}
|
|
240
289
|
"""
|
|
241
290
|
|
|
242
|
-
Tools used: ${
|
|
291
|
+
Tools used: ${n.length>0?n.join(", "):"none"}
|
|
243
292
|
|
|
244
293
|
Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
245
294
|
{
|
|
@@ -250,38 +299,38 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
|
|
|
250
299
|
"confidence": "<high|medium|low>"
|
|
251
300
|
}
|
|
252
301
|
</self_eval>
|
|
253
|
-
`.trim()}parseSelfEval(e){let
|
|
254
|
-
`)}getTurnSummary(){let e=this.turnSteps.length,
|
|
255
|
-
`)}getFailureCount(e){return this.failures.get(e)?.count??0}shouldAutoRetry(e){let
|
|
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 n of r){let s=e.match(n);if(s)try{let i=JSON.parse(s[1]);return this.normalizeSelfEval(i)}catch{}}return null}normalizeSelfEval(e){let r=typeof e.score=="number"?Math.max(0,Math.min(10,Math.round(e.score))):5,n=typeof e.completed=="boolean"?e.completed:r>=7,s=typeof e.rationale=="string"?e.rationale.slice(0,500):"No rationale provided",i=Array.isArray(e.issues)?e.issues.filter(a=>typeof a=="string").slice(0,5):[],o="medium";return e.confidence==="high"||e.confidence==="medium"||e.confidence==="low"?o=e.confidence:r>=8?o="high":r<=4&&(o="low"),{score:r,completed:n,rationale:s,issues:i,confidence:o}}buildBudgetWarningPrompt(){let e=this.remainingBudget();return e<=0?"[SYSTEM] You have exceeded the maximum reasoning steps. You MUST provide your final answer NOW. Do not call any more tools.":e<=3?`[SYSTEM] You have only ${e} step(s) remaining. Wrap up your work and provide a final answer soon.`:null}buildReflectionHint(e,r,n){return r?"":["<thinking>",`Tool "${e}" FAILED. Before retrying:`,"1. What went wrong? Analyze the error message carefully.","2. Can I fix the arguments and retry?","3. Is there an alternative approach?",`Error preview: ${n.slice(0,300)}`,"</thinking>"].join(`
|
|
303
|
+
`)}getTurnSummary(){let e=this.turnSteps.length,r=this.turnSteps.filter(s=>s.action).length,n=this.turnSteps.filter(s=>s.reflection).length;return`${e} steps, ${r} actions, ${n} reflections`}};function sr(t){return new ii(t)}var Yy=[{test:t=>/ENOENT|no such file|not found|does not exist/i.test(t),errorClass:"file_not_found",strategy:"read_first",explanation:"The file or directory does not exist.",suggestion:"Use list_dir to check what files exist, then retry with the correct path.",alternatives:["list_dir","search_codebase"],autoRetry:!1},{test:t=>/EACCES|permission denied/i.test(t),errorClass:"permission_denied",strategy:"graceful_fail",explanation:"Permission denied \u2014 the process lacks access rights.",suggestion:"Check file ownership or try a different path. Do NOT use sudo.",alternatives:[],autoRetry:!1},{test:t=>/EISDIR|is a directory/i.test(t),errorClass:"path_is_directory",strategy:"retry_fixed",explanation:"The path points to a directory, not a file.",suggestion:"Append the filename to the path. Use list_dir to see contents.",alternatives:["list_dir"],autoRetry:!1},{test:t=>/EEXIST|already exists/i.test(t),errorClass:"file_already_exists",strategy:"read_first",explanation:"A file or directory already exists at that path.",suggestion:"Read the existing file first, then decide whether to overwrite or edit it.",alternatives:["read_file","edit_file"],autoRetry:!1},{test:t=>/no match|not found in file|search string not found/i.test(t),errorClass:"search_no_match",strategy:"read_first",explanation:"The search string was not found in the file.",suggestion:"Read the file first to see its actual content, then use the exact text for search/replace.",alternatives:["read_file","search_codebase"],autoRetry:!1},{test:t=>/command not found|not recognized/i.test(t),errorClass:"command_not_found",strategy:"alternative_tool",explanation:"The command does not exist on this system.",suggestion:"Check if the program is installed, or use a different command that achieves the same goal.",alternatives:["run_command"],autoRetry:!1},{test:t=>/timeout|timed out|ETIMEDOUT/i.test(t),errorClass:"command_timeout",strategy:"retry_fixed",explanation:"The command took too long and was terminated.",suggestion:"Try a simpler version of the command, or increase the timeout, or run it in background.",alternatives:[],autoRetry:!1},{test:t=>/exit code|exited with|non-zero/i.test(t),errorClass:"command_exit_error",strategy:"retry_fixed",explanation:"The command executed but returned an error.",suggestion:"Read the error output carefully. Fix the root cause (missing dependency, wrong syntax, etc.).",alternatives:[],autoRetry:!1},{test:t=>/syntax error|unexpected token|parse error|SyntaxError/i.test(t),errorClass:"syntax_error",strategy:"retry_fixed",explanation:"The content has a syntax error.",suggestion:"Review the generated code for syntax issues, fix them, and retry.",alternatives:[],autoRetry:!1},{test:t=>/ECONNREFUSED|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(t),errorClass:"network_error",strategy:"retry_same",explanation:"Network connection failed.",suggestion:"This may be transient. Retry the same operation, or check connectivity.",alternatives:[],autoRetry:!0},{test:t=>/invalid argument|missing required|expected.*but got|type error/i.test(t),errorClass:"invalid_arguments",strategy:"retry_fixed",explanation:"The tool was called with invalid or missing arguments.",suggestion:"Check the tool's parameter requirements and provide correct values.",alternatives:[],autoRetry:!1},{test:t=>/ENOMEM|out of memory|resource|too large|max.*exceeded/i.test(t),errorClass:"resource_limit",strategy:"decompose_task",explanation:"Resource limit exceeded (memory, file size, etc.).",suggestion:"Break the task into smaller pieces, or process less data at once.",alternatives:[],autoRetry:!1}],oi=class{failures=new Map;maxRetriesPerTool;constructor(e=3){this.maxRetriesPerTool=e}resetTurn(){this.failures.clear()}analyze(e,r,n){let s=this.failures.get(e),i=s?s.count+1:1,o={tool:e,count:i,lastError:r,lastStrategy:"retry_same"};if(i>this.maxRetriesPerTool)return o.lastStrategy="ask_user",this.failures.set(e,o),{errorClass:"unknown",strategy:"ask_user",explanation:`Tool "${e}" has failed ${i} times in this turn.`,suggestion:`Stop retrying "${e}". Ask the user for clarification or try a completely different approach.`,alternatives:this.suggestAlternatives(e),autoRetry:!1};for(let a of Yy)if(a.test(r)){let c=s?.lastStrategy===a.strategy&&i>=2,l=c?"decompose_task":a.strategy;return o.lastStrategy=l,this.failures.set(e,o),{errorClass:a.errorClass,strategy:l,explanation:a.explanation,suggestion:c?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!c&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
|
|
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 ir(t=3){return new oi(t)}var Le=T(require("fs")),Xr=T(require("path")),Kl=T(require("os")),Yr=Xr.join(Kl.homedir(),".hablas","model-formats.json");function Xy(){try{if(Le.existsSync(Yr))return JSON.parse(Le.readFileSync(Yr,"utf-8"))}catch{}return{}}function Qy(t){try{let e=Xr.dirname(Yr);Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0}),Le.writeFileSync(Yr,JSON.stringify(t,null,2),"utf-8")}catch{}}function Gl(t,e){let r=0,n=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"&&n){s=!0;continue}if(o==='"'){n=!n;continue}if(!n&&(o==="{"&&r++,o==="}"&&(r--,r===0)))return t.slice(e,i+1)}return null}function or(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 Zy(t){return t.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function ew(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=or(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function tw(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim());if(s.parameters||s.name){let i=or(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function rw(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)<<?\/tool[-_]call\s*>>?/gi,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=Jl(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function Jl(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 n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",c={},l=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=l.exec(o))!==null;){let p=u[1].toLowerCase(),h=u[2]??u[3]??u[4];c[p]=Zy(h)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?c.content=a:n==="run_command"?c.command=d:n==="patch_file"&&(c.new_content=a)),c.start_line&&(c.start_line=parseInt(c.start_line)),c.end_line&&(c.end_line=parseInt(c.end_line)),c.depth&&(c.depth=parseInt(c.depth)),e.push({tool:n,args:c,format:"xml_prompt",rawMatch:i[0]})}}return e}function nw(t){return Jl(t)}function sw(t){let e=[],r=/```(?:json|tool_call)?\s*\n([\s\S]*?)\n```/g,n;for(;(n=r.exec(t))!==null;)try{let s=JSON.parse(n[1].trim()),i=or(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function iw(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Gl(t,n.index);if(s)try{let i=JSON.parse(s),o=or(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function ow(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=Gl(t,n.index);if(s)try{let i=JSON.parse(s),o=or(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function aw(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),c={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=l.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)),c[d]=p}e.push({tool:a,args:c,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},c=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,l;for(;(l=c.exec(t))!==null;){let u=l[1].trim(),d=l[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 ai=[{format:"xml_tool_call_wrapper",parse:rw},{format:"xml_prompt",parse:nw},{format:"xml_tags",parse:ew},{format:"xml_parameters",parse:aw},{format:"hermes",parse:tw},{format:"markdown_json",parse:sw},{format:"function_call",parse:iw},{format:"json_object",parse:ow}],li=class{registry;constructor(){this.registry=Xy()}parse(e,r,n){if(r&&Array.isArray(r)&&r.length>0){let i=r.filter(o=>o?.function?.name&&typeof o.function.name=="string");if(i.length>0){let o=i.map(a=>({function:{name:a.function.name,arguments:a.function.arguments||{}}}));return n&&this.learnFormat(n,"native"),{toolCalls:o,displayContent:(e||"").trim(),format:"native"}}}let s=e||"";if(!s.trim())return{toolCalls:[],displayContent:"",format:"unknown"};if(n){let i=this.registry[n];if(i&&i.format!=="native"){let o=ai.find(a=>a.format===i.format);if(o){let a=o.parse(s);if(a.length>0)return this.learnFormat(n,i.format),this.buildResult(a,s)}}}for(let{parse:i}of ai){let o=i(s);if(o.length>0){let a=o[0].format;return n&&this.learnFormat(n,a),this.buildResult(o,s)}}return{toolCalls:[],displayContent:this.sanitizeResidualToolMarkup(s).trim(),format:"unknown"}}mightContainToolCall(e){if(!e)return!1;let r=e.trim();return!!(/<<?tool[-_]call[\s>]/i.test(r)||/<function=/i.test(r)||r.includes("```tool_call")||r.includes("```json")&&r.includes('"name"')||/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s>]/i.test(r)||r.startsWith("{")&&(r.includes('"name"')||r.includes('"tool"'))&&(r.includes('"arguments"')||r.includes('"args"')||r.includes('"parameters"'))||r.includes('"function"')&&r.includes('"name"'))}detectFormat(e){for(let{format:r,parse:n}of ai)if(n(e).length>0)return r;return"unknown"}learnFormat(e,r){let n=this.registry[e];n&&n.format===r?(n.successCount++,n.lastUsed=new Date().toISOString()):this.registry[e]={format:r,successCount:1,lastUsed:new Date().toISOString()},Qy(this.registry)}getLearnedFormat(e){return this.registry[e]?.format??null}getLearnedFormats(){let e={};for(let[r,n]of Object.entries(this.registry))e[r]={format:n.format,successCount:n.successCount};return e}buildResult(e,r){let n=e.map(o=>({function:{name:o.tool,arguments:o.args}})),s=r,i=[...e].sort((o,a)=>a.rawMatch.length-o.rawMatch.length);for(let o of i)s=s.replace(o.rawMatch,"");return s=s.replace(/<<?thinking>>?[\s\S]*?<<?\/thinking>>?/gi,""),s=s.replace(/<<?think>>?[\s\S]*?<<?\/think>>?/gi,""),s=this.sanitizeResidualToolMarkup(s),s=s.replace(/\n{3,}/g,`
|
|
256
305
|
|
|
257
|
-
`),{toolCalls:
|
|
306
|
+
`),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}sanitizeResidualToolMarkup(e){return e.replace(/<<?tool[-_]call[\s\S]*?<<?\/tool[-_]call\s*>>?/gi,"").replace(/<function=[^>]+>/gi,"").replace(/<parameter=[^>]+>/gi,"").replace(/<\/parameter>/gi,"").replace(/```tool_call[\s\S]*?```/gi,"").replace(/<<?(?:read_file|write_file|run_command|edit_file|search_codebase|create_dir|delete_file|list_dir|append_to_file|patch_file|move_file|get_file_info|web_search|scrape_url|extract_links|read_pdf|pdf_metadata|execute_code|detect_bugs|download_asset|search_image_candidates|inspect_image)[\s\S]*?(?:<<?\/[a-z_]+>>?|\/>)/gi,"").replace(/\n{3,}/g,`
|
|
258
307
|
|
|
259
|
-
`)}},Zs=null;function fo(){return Zs||(Zs=new er),Zs}var ts=class t{buf="";inThink=!1;visibleEmitted=!1;onToken;static THINK_OPENS=["<thinking>","<think>"];static THINK_CLOSES=["</thinking>","</think>"];static PARTIAL_SCAN=12;constructor(e){this.onToken=e}push(e){this.buf+=e,this.flush_process()}flush(){if(this.inThink){this.buf="",this.inThink=!1;return}if(this.buf.trim()){let e=this.buf.replace(/<\/?think(?:ing)?>/gi,"").trim();e&&this.emit(e)}this.buf=""}get hasVisibleContent(){return this.visibleEmitted}flush_process(){for(;this.buf.length>0;){if(this.inThink){let r=this.findFirst(t.THINK_CLOSES);if(r===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let n=this.buf.indexOf(">",r)+1;this.buf=this.buf.slice(n),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let r=this.longestPartialTail();if(r>0){let n=this.buf.slice(0,this.buf.length-r);n&&this.emit(n),this.buf=this.buf.slice(this.buf.length-r);return}this.emit(this.buf),this.buf="";return}if(e>0){this.emit(this.buf.slice(0,e)),this.buf=this.buf.slice(e);continue}this.inThink=!0;let s=this.buf.indexOf(">")+1;this.buf=this.buf.slice(s>0?s:this.buf.length)}}findFirst(e){let s=-1,r=this.buf.toLowerCase();for(let n of e){let o=r.indexOf(n.toLowerCase());o!==-1&&(s===-1||o<s)&&(s=o)}return s}longestPartialTail(){let e=t.PARTIAL_SCAN,s=this.buf.slice(-e).toLowerCase(),r=0;for(let n of t.THINK_OPENS){let o=n.toLowerCase();for(let i=Math.min(o.length-1,s.length);i>0;i--)if(o.startsWith(s.slice(-i))){r=Math.max(r,i);break}}return r}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var bc=600,xc=4e3,vc=16e3,mo=2;function kc(t,e,s){let n=fo().parse(e,t,s);return{toolCalls:n.toolCalls,displayContent:n.displayContent}}function Sc(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 Tc(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 go(t,e,s,r){let n=0,o=Date.now();for(;n<=mo;){let i=await t.execute({name:e,arguments:s});if(i.success||n>=mo)return{success:i.success,output:i.output,error:i.error,duration:Date.now()-o,retries:n};n++,r.info({tool:e,retry:n,error:i.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-o,retries:n}}async function tr(t){let{identity:e,client:s,registry:r,session:n,contextManager:o,logger:i,io:a={},safetyPolicy:c,abortSignal:l,skipTools:u}=t,p=t.reactEngine??At(),d=t.errorRecovery??Rt(),f=u?[]:r.getOllamaTools(),m=s.getModel(),h=t.maxIterations??bc,y=[],w=[],k=[],v=new Map,S="",T=0,_=!1;for(;T<h;){if(T++,l?.aborted)return{output:S,toolsUsed:ge(y),toolResults:w,touchedFiles:ge(k),iterations:T,success:!1,error:"Aborted",completedNaturally:_};let G=p.buildBudgetWarningPrompt();G&&n.addUserMessage(G,{priority:"critical",tags:["system-budget"]});let B;try{if(a.onModelStart?.(w.length>0?"Deciding next step":"Thinking",e),s.streamChatWithTools){let ie=!1,ae=new ts(Se=>{ie||(a.onModelStop?.(),ie=!0),a.onStreamToken?.(Se,e)}),R=s.streamChatWithTools(n.getMessages(),f,Se=>{ae.push(Se)},l),I=await R.next();for(;!I.done;)I=await R.next();ae.flush(),B=I.value,ie||a.onModelStop?.()}else B=await s.chatWithTools(n.getMessages(),f,l),a.onModelStop?.()}catch(ie){a.onModelStop?.();let ae=ie;if(ae.name==="AbortError"||l?.aborted)return{output:S,toolsUsed:ge(y),toolResults:w,touchedFiles:ge(k),iterations:T,success:!1,error:"Aborted",completedNaturally:_};if(T<=1){let I=te(ae),Se=/rate.?limit|429|cooldown/i.test(ae?.message||""),gs=Se?2e4:2e3,hs=Se?`API provider rate limit \u2014 waiting ${gs/1e3}s before retry...`:"Transient error: "+I.message+" \u2014 retrying...";a.onNotice?.(hs,"retry"),await new Promise(je=>setTimeout(je,gs)),T--;continue}let R=te(ae);return R.fatal?(a.onError?.(R.message),{output:S,toolsUsed:ge(y),toolResults:w,touchedFiles:ge(k),iterations:T,success:!1,error:R.message,completedNaturally:_}):(a.onError?.(R.message),{output:S,toolsUsed:ge(y),toolResults:w,touchedFiles:ge(k),iterations:T,success:!1,error:R.message,completedNaturally:_})}if(!B||!B.message){a.onNotice?.("Model returned an empty response \u2014 retrying...","retry"),await new Promise(ie=>setTimeout(ie,1500));continue}let Z=B.message?.content||"",ve=B.message?.tool_calls,ke=p.parseThinking(Z);ke.hasThinking&&(p.recordStep({thought:ke.thinking}),i.debug({thinking:ke.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:Ke,displayContent:ze}=kc(ve,Z,m);if(ze&&ze.trim()&&(S=ze,await a.onAssistantText?.(ze,e)),Ke.length===0){n.addAssistantMessage(Z,void 0,e.role),_=!0;break}n.addAssistantMessage(Z,Ke,e.role);let Qo=Ke.length;for(let ie=0;ie<Qo;ie++){let ae=Ke[ie];if(!ae?.function?.name)continue;let R=ae.function.name,I=ae.function.arguments||{},Se=r.getSafetyLevel(R)??"confirm";if(!r.get(R)){a.onNotice?.("Unknown tool: "+R+" \u2014 skipping","warn"),n.addToolMessage('Error: Unknown tool "'+R+'". Available: '+r.getAll().map(W=>W.name).join(", "));continue}if(await c(R,Se,I)==="skip"){n.addToolMessage("Tool "+R+" was skipped by policy/user.");break}let hs=Sc(R,I),je=R==="read_file"?JSON.stringify({path:I.path||"",start:I.start_line||"",end:I.end_line||""}):"";if(R==="read_file"&&je&&v.has(je)){let W=v.get(je)||"";n.addToolMessage(W),p.recordObservation(W.slice(0,300),"Reused cached file read");continue}y.push(R),typeof I.path=="string"&&k.push(I.path),typeof I.from=="string"&&k.push(I.from),typeof I.to=="string"&&k.push(I.to),a.onToolStart?.(R,hs,I),a.onToolCall?.(),p.recordStep({thought:ke.hasThinking?"Executing: "+R:"",action:R,actionInput:I});let U=await go(r,R,I,i);a.onToolEnd?.(R,U.success,U.error||U.output,U.duration,I);let Pe;if(U.success)Pe=ho(R,U.output),p.recordObservation(Pe.slice(0,300)),w.push({tool:R,success:!0,summary:U.output.slice(0,150)});else{let W=U.error||"Unknown error",Ge=d.analyze(R,W,I);if(Pe=d.buildRecoveryMessage(Ge,W),p.recordObservation("FAILED: "+W,"Recovery: "+Ge.strategy+" \u2014 "+Ge.suggestion),i.info({tool:R,errorClass:Ge.errorClass,strategy:Ge.strategy},"Error recovery analysis"),w.push({tool:R,success:!1,summary:W.slice(0,150)}),Ge.autoRetry&&!p.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let Ve=await go(r,R,I,i);a.onToolEnd?.(R,Ve.success,Ve.output,Ve.duration,I),Ve.success&&(Pe=ho(R,Ve.output),p.recordObservation(Pe.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:R,success:!0,summary:Ve.output.slice(0,150)})}}if(n.addToolMessage(Pe),U.success&&R==="read_file"&&typeof I.path=="string"&&(o?.addFile(I.path,U.output),je&&v.set(je,Pe)),U.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(R)&&typeof I.path=="string")for(let W of[...v.keys()])W.includes('"path":"'+String(I.path).replace(/"/g,'\\"')+'"')&&v.delete(W);if(U.success&&R==="move_file")for(let W of[...v.keys()])(I.from&&W.includes('"path":"'+String(I.from).replace(/"/g,'\\"')+'"')||I.to&&W.includes('"path":"'+String(I.to).replace(/"/g,'\\"')+'"'))&&v.delete(W);if(i.info({tool:R,success:U.success,durationMs:U.duration,retries:U.retries},"Tool executed"),!U.success&&Tc(U.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}}p.isOverBudget()&&a.onNotice?.("Reached max reasoning steps ("+p.getConfig().maxSteps+"). Wrapping up.","warn")}return T>=h&&!_&&a.onNotice?.("Reached max iterations ("+h+"). Stopping.","warn"),i.info({summary:p.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:S,toolsUsed:ge(y),toolResults:w,touchedFiles:ge(k),iterations:T,success:!0,completedNaturally:_}}function ge(t){return[...new Set(t)]}function ho(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?St(e,vc):St(e,xc)}function yo(t){return async(e,s)=>{let r=e.replace(/_/g," ");return!t.autoMode&&t.interactive?s==="confirm"&&t.confirm?await t.confirm("Proceed with "+r+"?")?"allow":"skip":s==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+r)?"allow":"skip":"allow":!t.autoMode&&s==="dangerous"?"skip":"allow"}}async function wo(t){let{client:e,session:s,abortSignal:r,onStart:n,onChunk:o,onComplete:i}=t,a="",c=null;for(let l=0;l<2;l++)try{a="",n?.();for await(let u of e.streamChat(s.getMessages(),r)){if(r?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,o?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(s.getMessages(),[],r)).message?.content||"",a&&o?.(a)),s.addAssistantMessage(a||""),i?.(),a}catch(u){if(c=u,u?.name==="AbortError"||r?.aborted)throw u;let d=te(u);if(d.fatal)throw new Error(d.message);if(l===1)throw new Error(d.message);await new Promise(f=>setTimeout(f,1e3))}throw c||new Error("Text turn failed")}function _c(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 Ie(t){process.stdout.write(t)}function ss(t){process.stdout.write(t+`
|
|
260
|
-
`)}async function
|
|
261
|
-
`))}catch(
|
|
262
|
-
`),
|
|
263
|
-
`))},onToolStart:(m,
|
|
264
|
-
`),l=
|
|
265
|
-
`)},onToolEnd:(m,
|
|
266
|
-
`)},onNotice:(m
|
|
267
|
-
`+
|
|
268
|
-
`),
|
|
269
|
-
`))}try{
|
|
270
|
-
`)}function
|
|
308
|
+
`)}},ci=null;function Yl(){return ci||(ci=new li),ci}var Qr=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 n=this.findFirst(t.THINK_CLOSES);if(n===-1){this.buf.length>20&&(this.buf=this.buf.slice(-20));return}let s=this.buf.indexOf(">",n)+1;this.buf=this.buf.slice(s),this.inThink=!1;continue}let e=this.findFirst(t.THINK_OPENS);if(e===-1){let n=this.longestPartialTail();if(n>0){let s=this.buf.slice(0,this.buf.length-n);s&&this.emit(s),this.buf=this.buf.slice(this.buf.length-n);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,n=this.buf.toLowerCase();for(let s of e){let i=n.indexOf(s.toLowerCase());i!==-1&&(r===-1||i<r)&&(r=i)}return r}longestPartialTail(){let e=t.PARTIAL_SCAN,r=this.buf.slice(-e).toLowerCase(),n=0;for(let s of t.THINK_OPENS){let i=s.toLowerCase();for(let o=Math.min(i.length-1,r.length);o>0;o--)if(i.startsWith(r.slice(-o))){n=Math.max(n,o);break}}return n}emit(e){e&&(e.trim()&&(this.visibleEmitted=!0),this.onToken(e))}};var cw=600,lw=4e3,uw=16e3,Xl=2;function fw(t,e,r){let s=Yl().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function dw(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 pw(t){let e=(t||"").toLowerCase();return e.includes("eacces")||e.includes("permission")||e.includes("enospc")||e.includes("readonly")||e.includes("security")||e.includes("[write_file]")||e.includes("[delete_file]")||e.includes("[move_file]")||e.includes("[search_and_replace]")}async function Ql(t,e,r,n){let s=0,i=Date.now();for(;s<=Xl;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=Xl)return{success:o.success,output:o.output,error:o.error,duration:Date.now()-i,retries:s};s++,n.info({tool:e,retry:s,error:o.error},"Retrying tool"),await new Promise(a=>setTimeout(a,500))}return{success:!1,output:"",error:"Max retries exceeded",duration:Date.now()-i,retries:s}}async function ui(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:c,abortSignal:l,skipTools:u}=t,d=t.reactEngine??sr(),p=t.errorRecovery??ir(),h=u?[]:n.getOllamaTools(),f=r.getModel(),m=t.maxIterations??cw,g=[],y=[],b=[],w=new Map,v="",_=0,C=!1;for(;_<m;){if(_++,l?.aborted)return{output:v,toolsUsed:Re(g),toolResults:y,touchedFiles:Re(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};let A=d.buildBudgetWarningPrompt();A&&s.addUserMessage(A,{priority:"critical",tags:["system-budget"]});let E;try{if(a.onModelStart?.(y.length>0?"Deciding next step":"Thinking",e),r.streamChatWithTools){let J=!1,se=new Qr(ve=>{J||(a.onModelStop?.(),J=!0),a.onStreamToken?.(ve,e)}),I=r.streamChatWithTools(s.getMessages(),h,ve=>{se.push(ve)},l),L=await I.next();for(;!L.done;)L=await I.next();se.flush(),E=L.value,J||a.onModelStop?.()}else E=await r.chatWithTools(s.getMessages(),h,l),a.onModelStop?.()}catch(J){a.onModelStop?.();let se=J;if(se.name==="AbortError"||l?.aborted)return{output:v,toolsUsed:Re(g),toolResults:y,touchedFiles:Re(b),iterations:_,success:!1,error:"Aborted",completedNaturally:C};if(_<=1){let L=me(se),ve=/rate.?limit|429|cooldown/i.test(se?.message||""),Dt=ve?2e4:2e3,pn=ve?`API provider rate limit \u2014 waiting ${Dt/1e3}s before retry...`:"Transient error: "+L.message+" \u2014 retrying...";a.onNotice?.(pn,"retry"),await new Promise(Ye=>setTimeout(Ye,Dt)),_--;continue}let I=me(se);return I.fatal?(a.onError?.(I.message),{output:v,toolsUsed:Re(g),toolResults:y,touchedFiles:Re(b),iterations:_,success:!1,error:I.message,completedNaturally:C}):(a.onError?.(I.message),{output:v,toolsUsed:Re(g),toolResults:y,touchedFiles:Re(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(J=>setTimeout(J,1500));continue}let $=E.message?.content||"",F=E.message?.tool_calls,q=d.parseThinking($);q.hasThinking&&(d.recordStep({thought:q.thinking}),o.debug({thinking:q.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:U,displayContent:W}=fw(F,$,f);if(W&&W.trim()&&(v=W,await a.onAssistantText?.(W,e)),U.length===0){s.addAssistantMessage($,void 0,e.role),C=!0;break}s.addAssistantMessage($,U,e.role);let ee=U.length;for(let J=0;J<ee;J++){let se=U[J];if(!se?.function?.name)continue;let I=se.function.name,L=se.function.arguments||{},ve=n.getSafetyLevel(I)??"confirm";if(!n.get(I)){a.onNotice?.("Unknown tool: "+I+" \u2014 skipping","warn"),s.addToolMessage('Error: Unknown tool "'+I+'". Available: '+n.getAll().map(te=>te.name).join(", "));continue}if(await c(I,ve,L)==="skip"){s.addToolMessage("Tool "+I+" was skipped by policy/user.");break}let pn=dw(I,L),Ye=I==="read_file"?JSON.stringify({path:L.path||"",start:L.start_line||"",end:L.end_line||""}):"";if(I==="read_file"&&Ye&&w.has(Ye)){let te=w.get(Ye)||"";s.addToolMessage(te),d.recordObservation(te.slice(0,300),"Reused cached file read");continue}g.push(I),typeof L.path=="string"&&b.push(L.path),typeof L.from=="string"&&b.push(L.from),typeof L.to=="string"&&b.push(L.to),a.onToolStart?.(I,pn,L),a.onToolCall?.(),d.recordStep({thought:q.hasThinking?"Executing: "+I:"",action:I,actionInput:L});let Q=await Ql(n,I,L,o);a.onToolEnd?.(I,Q.success,Q.error||Q.output,Q.duration,L);let Xe;if(Q.success)Xe=Zl(I,Q.output),d.recordObservation(Xe.slice(0,300)),y.push({tool:I,success:!0,summary:Q.output.slice(0,150)});else{let te=Q.error||"Unknown error",pt=p.analyze(I,te,L);if(Xe=p.buildRecoveryMessage(pt,te),d.recordObservation("FAILED: "+te,"Recovery: "+pt.strategy+" \u2014 "+pt.suggestion),o.info({tool:I,errorClass:pt.errorClass,strategy:pt.strategy},"Error recovery analysis"),y.push({tool:I,success:!1,summary:te.slice(0,150)}),pt.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)...","retry");let ht=await Ql(n,I,L,o);a.onToolEnd?.(I,ht.success,ht.output,ht.duration,L),ht.success&&(Xe=Zl(I,ht.output),d.recordObservation(Xe.slice(0,300),"Auto-retry succeeded"),y[y.length-1]={tool:I,success:!0,summary:ht.output.slice(0,150)})}}if(s.addToolMessage(Xe),Q.success&&I==="read_file"&&typeof L.path=="string"&&(i?.addFile(L.path,Q.output),Ye&&w.set(Ye,Xe)),Q.success&&["write_file","edit_file","patch_file","search_and_replace","append_to_file","delete_file"].includes(I)&&typeof L.path=="string")for(let te of[...w.keys()])te.includes('"path":"'+String(L.path).replace(/"/g,'\\"')+'"')&&w.delete(te);if(Q.success&&I==="move_file")for(let te of[...w.keys()])(L.from&&te.includes('"path":"'+String(L.from).replace(/"/g,'\\"')+'"')||L.to&&te.includes('"path":"'+String(L.to).replace(/"/g,'\\"')+'"'))&&w.delete(te);if(o.info({tool:I,success:Q.success,durationMs:Q.duration,retries:Q.retries},"Tool executed"),!Q.success&&pw(Q.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:v,toolsUsed:Re(g),toolResults:y,touchedFiles:Re(b),iterations:_,success:!0,completedNaturally:C}}function Re(t){return[...new Set(t)]}function Zl(t,e){return t==="read_file"?e:["web_search","scrape_url","extract_links","read_pdf"].includes(t)?Zt(e,uw):Zt(e,lw)}function eu(t){return async(e,r)=>{let n=e.replace(/_/g," ");return!t.autoMode&&t.interactive?r==="confirm"&&t.confirm?await t.confirm("Proceed with "+n+"?")?"allow":"skip":r==="dangerous"&&t.confirmDangerous?await t.confirmDangerous("Dangerous: "+n)?"allow":"skip":"allow":!t.autoMode&&r==="dangerous"?"skip":"allow"}}async function tu(t){let{client:e,session:r,abortSignal:n,onStart:s,onChunk:i,onComplete:o}=t,a="",c=null;for(let l=0;l<2;l++)try{a="",s?.();for await(let u of e.streamChat(r.getMessages(),n)){if(n?.aborted)throw new DOMException("Aborted","AbortError");typeof u=="string"&&(a+=u,i?.(u))}return!a.trim()&&e.chatWithTools&&(a=(await e.chatWithTools(r.getMessages(),[],n)).message?.content||"",a&&i?.(a)),r.addAssistantMessage(a||""),o?.(),a}catch(u){if(c=u,u?.name==="AbortError"||n?.aborted)throw u;let p=me(u);if(p.fatal)throw new Error(p.message);if(l===1)throw new Error(p.message);await new Promise(h=>setTimeout(h,1e3))}throw c||new Error("Text turn failed")}function hw(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 Je(t){process.stdout.write(t)}function Zr(t){process.stdout.write(t+`
|
|
309
|
+
`)}async function en(t,e){let r=Hl(t),n=await Mt(e.workingDir,e.config);if(e.session.updateSystemPrompt(Pt(n,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 f=new Qe("Thinking");f.start();try{let m=await tu({client:e.client,session:e.session,abortSignal:e.abortSignal,onStart:()=>{},onChunk:()=>{},onComplete:()=>{}});f.stop(),m?.trim()&&(Zr(ur()),Je(fr(m)+`
|
|
310
|
+
`))}catch(m){f.stop();let g=me(m);Zr(Ie(g.message))}try{rr().flush()}catch{}return}let s=sr({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=ir(3),o="",a=[],c=new Qe("Thinking"),l="",u=()=>{o=""},d={onModelStart:f=>{u(),c.stop(),c.start()},onModelStop:()=>{c.stop()},onStreamToken:f=>{f&&(o+=f)},onAssistantText:async f=>{let m=(f||o||"").trim();u(),m&&(a.push(m),c.stop(),Je(ur()+`
|
|
311
|
+
`),Je(fr(m)+`
|
|
312
|
+
`))},onToolStart:(f,m,g)=>{u(),c.stop();let y=hw(f);y!==l&&(Je($i(y)+`
|
|
313
|
+
`),l=y),Je(Ai(f,m)+`
|
|
314
|
+
`)},onToolEnd:(f,m,g,y)=>{Je(Ei(m,g,y)+`
|
|
315
|
+
`)},onNotice:(f,m)=>{u();let g=m==="retry"?D("\u21BB "+f):D(f);Zr(g)},onError:f=>{u(),Zr(Ie(f))},onToolCall:()=>e.onToolCall?.()},p=eu({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?f=>e.input.confirm(f):void 0,confirmDangerous:e.input?f=>e.input.confirmDangerous(f):void 0}),h=await ui({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:d,safetyPolicy:p,reactEngine:s,errorRecovery:i,skipTools:!1});if(u(),r.profile.kind==="implementation"&&h.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 f=[];await ui({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:{...d,onAssistantText:async g=>{g?.trim()&&f.push(g)}},safetyPolicy:p,reactEngine:sr({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:ir(3),skipTools:!1});let m=f[f.length-1];m?.trim()&&(Je(`
|
|
316
|
+
`+ur()+`
|
|
317
|
+
`),Je(fr(m)+`
|
|
318
|
+
`))}try{rr().flush()}catch{}}var fi=T(require("fs")),ru=T(require("path")),Te=T(require("os")),nu=require("child_process");async function tn(t){let e=[],r=process.version,n=parseInt(r.slice(1).split(".")[0],10);e.push({name:"Node.js",status:n>=20?"ok":n>=18?"warn":"error",message:n>=20?`${r} (recommended)`:n>=18?`${r} (works, but 20+ recommended)`:`${r} (too old, need 20+)`});let s=ru.join(Te.homedir(),".hablas");if(e.push({name:"Config directory",status:fi.existsSync(s)?"ok":"warn",message:fi.existsSync(s)?s:"Not created yet (will be created on first use)"}),t.provider==="ollama")try{let i=await fetch(`${t.ollamaHost}/api/tags`,{signal:AbortSignal.timeout(5e3)});if(i.ok){let o=await i.json(),a=Array.isArray(o.models)?o.models.length:0;e.push({name:"Ollama",status:"ok",message:`Connected \u2014 ${a} models available`})}else e.push({name:"Ollama",status:"error",message:`HTTP ${i.status}`})}catch(i){let o=i instanceof Error?i.message:String(i);e.push({name:"Ollama",status:"error",message:o.includes("ECONNREFUSED")?"Not running \u2014 start with: ollama serve":`Connection failed: ${o}`})}else{let i=t.apiUrl||"unknown";try{let o=await fetch(`${i}/models`,{signal:AbortSignal.timeout(5e3),headers:{Authorization:"Bearer test"}});e.push({name:"API Provider",status:o.ok||o.status===401?"ok":"warn",message:`${i} \u2014 reachable`})}catch{e.push({name:"API Provider",status:"warn",message:`${i} \u2014 could not verify`})}}try{let i=Te.homedir();if(process.platform!=="win32"){let a=(0,nu.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),c=a[3]||"unknown",l=a[4]||"?";e.push({name:"Disk space",status:parseInt(l)>90?"warn":"ok",message:`${c} available (${l} used)`})}else e.push({name:"Disk space",status:"ok",message:"Check skipped on Windows"})}catch{e.push({name:"Disk space",status:"ok",message:"Could not determine"})}return e.push({name:"Active model",status:t.model?"ok":"warn",message:t.model||"No model configured"}),e.push({name:"Platform",status:"ok",message:`${Te.platform()} ${Te.arch()} \u2014 ${Te.cpus().length} cores, ${Math.round(Te.totalmem()/1024/1024/1024)}GB RAM`}),e}function rn(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let c of t){let l=`${r[c.status]}${e[c.status]}${n}`,u=c.name.padEnd(18);i.push(` ${l} ${u}${s}${c.message}${n}`)}let o=t.filter(c=>c.status==="error").length,a=t.filter(c=>c.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
|
|
319
|
+
`)}function su(t){let e={},r=[];for(let[s,i]of Object.entries(t.parameters||{}))e[s]={type:mw(i.type),description:i.description},i.required&&r.push(s);let n={type:"object",properties:e};return r.length&&(n.required=r),n}function iu(t){let e={};if(!t||typeof t!="object")return e;let r=t,n=new Set(r.required||[]);for(let[s,i]of Object.entries(r.properties||{}))e[s]={type:typeof i?.type=="string"?i.type:"string",description:i?.description||s,required:n.has(s)};return e}function mw(t){return["string","number","integer","boolean","array","object","null"].includes(t)?t:"string"}var cu="mcp__",ou=/^[a-zA-Z0-9_-]+$/,au=128;function gw(t,e){return!t.match(ou)||t.length>au||!e.match(ou)||e.length>au?null:`${cu}${t}__${e}`}function jt(t){let e=[];for(let r of t.list())for(let n of r.tools){let s=gw(r.name,n.name);s&&e.push({name:s,description:`[MCP:${r.name}] ${n.description||n.name}`,safety:r.trusted?"confirm":"dangerous",parameters:iu(n.inputSchema),execute:async i=>{let o=await t.callTool(r.name,n.name,i);return{success:o.success,output:o.output,error:o.error}}})}return e}function di(t){return t.startsWith(cu)}var De=T(require("fs")),hi=T(require("path")),lu=T(require("os")),pi=hi.join(lu.homedir(),".hablas"),nn=hi.join(pi,"mcp.json");function sn(){return nn}function on(){if(!De.existsSync(nn))return{mcpServers:{}};try{let t=JSON.parse(De.readFileSync(nn,"utf-8"));return{mcpServers:t.mcpServers&&typeof t.mcpServers=="object"?t.mcpServers:{}}}catch{return{mcpServers:{}}}}function uu(t){De.existsSync(pi)||De.mkdirSync(pi,{recursive:!0}),De.writeFileSync(nn,JSON.stringify(t,null,2),"utf-8")}function fu(t){let e=on();return t in e.mcpServers?(delete e.mcpServers[t],uu(e),!0):!1}function du(t,e){let r=on();return r.mcpServers[t]?(r.mcpServers[t].trusted=e,uu(r),!0):!1}async function pu(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Oi());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Ii());return;case"/version":console.log(Mi());return;case"/clear":e.session.clear(),console.log(oe("Session cleared."));return;case"/history":{let i=parseInt(s[0]||"8",10),o=e.session.getHistory().slice(-i);if(!o.length){console.log(D("No history yet."));return}console.log("");for(let a of o){let c=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${c.padEnd(10)} ${a.content.replace(/\s+/g," ").slice(0,140)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(Ri({model:e.client.getModel(),provider:at(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(!s.length){console.log(D(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ").trim(),o=[];try{o=await e.client.listModels()}catch{}if(o.length>0){let a=o.find(l=>l.toLowerCase()===i.toLowerCase());if(a){e.config.model=a,e.client.setModel(a),Be(e.config),console.log(oe(`Model \u2192 ${a}`));return}let c=o.filter(l=>l.toLowerCase().includes(i.toLowerCase())).slice(0,5);console.log(V(`Model "${i}" not found in the available list.`)),c.length?(console.log(D("Did you mean one of these?")),c.forEach((l,u)=>console.log(` ${u+1}. ${l}`)),console.log(D(`Run /models ${i} to see the full list`))):console.log(D("Run /models to browse available models"));return}e.config.model=i,e.client.setModel(i),Be(e.config),console.log(oe(`Model \u2192 ${i} (could not verify \u2014 offline)`));return}case"/models":{let i=[];try{i=await e.client.listModels()}catch{console.log(V("Could not fetch model list -- check your connection."));return}let o=20,a=1,c="";if(s.length){let g=s[s.length-1].toLowerCase(),y=parseInt(g,10),b=["next","n","prev","previous","p"];if(!Number.isNaN(y)&&y>0)a=y,c=s.slice(0,-1).join(" ").toLowerCase().trim();else if(b.includes(g)){console.log(D("Use page numbers to navigate: /models 2, /models 3")),console.log(D("Search by name: /models qwen"));return}else c=s.join(" ").toLowerCase().trim()}let l=c?i.filter(g=>g.toLowerCase().includes(c)):i;if(!l.length){console.log(V("No models matching: "+c)),console.log(D("Run /models to see all available models."));return}let u=Math.max(1,Math.ceil(l.length/o)),d=Math.min(Math.max(a,1),u),p=(d-1)*o,h=l.slice(p,p+o),f=e.client.getModel(),m=c?"Models + query + ":"Models";if(console.log(""),console.log(D(m+" | page "+d+"/"+u+" | "+l.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"+(c?" "+c:"")+" "+(d+1);console.log(D(g+" -- next page"))}if(d>1){let g="/models"+(c?" "+c:"")+" "+(d-1);console.log(D(g+" -- prev page"))}console.log(D("Switch model: /model <name>")),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(D(`Provider: ${at(e.config)}`)),console.log(D(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?oe("Connection OK"):Ie("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=de.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=de.defaultModel);else if(i==="custom"){if(!s[1]){console.log(V("Usage: /provider custom <url> [api-key]"));return}e.config.provider="custom",e.config.apiUrl=s[1],s[2]&&(e.config.apiKey=s[2])}else{console.log(V("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=xt(e.config);e.setClient(o),Be(e.config),console.log(oe(`Provider \u2192 ${at(e.config)}`));return}case"/doctor":{let i=await tn({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(rn(i));return}case"/workspace":{console.log(""),console.log(zr(Rt(e.workingDir))),console.log("");return}case"/memory":{if(s[0]==="clear"){e.accumulator&&e.accumulator.clear(),console.log(D("Long-context accumulator cleared (pinned entries kept)."));return}if(e.projectMemory){let o=e.projectMemory.getAll();console.log(""),console.log(oe(`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(oe(`Reasoning Accumulator \xB7 ${o.length} observations \xB7 turn #${e.accumulator.turnIndex}`));for(let a of o.slice(0,8)){let c=a.pinned?"\u{1F4CC} ":"";console.log(` ${c}[T${a.turnIndex}][${a.kind}] ${a.text.slice(0,70)}`)}}}console.log("");return}case"/diff":{let{exec:i}=await import("child_process"),o=s[0]||"",a=`git diff ${o?'"'+o+'"':""}`,c=await new Promise(l=>{i(a,{cwd:e.workingDir,maxBuffer:2*1024*1024},(u,d,p)=>{l(d||p||"No changes.")})});if(console.log(""),c.trim()){let l=c.split(`
|
|
271
320
|
`);for(let u of l.slice(0,100))u.startsWith("+")&&!u.startsWith("+++")?process.stdout.write(`\x1B[38;5;71m${u}\x1B[0m
|
|
272
321
|
`):u.startsWith("-")&&!u.startsWith("---")?process.stdout.write(`\x1B[38;5;131m${u}\x1B[0m
|
|
273
322
|
`):u.startsWith("@@")?process.stdout.write(`\x1B[38;5;110m${u}\x1B[0m
|
|
274
|
-
`):console.log(u);l.length>100&&console.log(
|
|
275
|
-
`);return{success:!
|
|
276
|
-
`),console.log(
|
|
277
|
-
`);let
|
|
278
|
-
`),console.log(
|
|
279
|
-
`);for(let{pattern:
|
|
280
|
-
`).length,u=
|
|
281
|
-
`),
|
|
282
|
-
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
|
|
283
|
-
`)}var
|
|
284
|
-
\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
|
|
285
|
-
`)}var
|
|
286
|
-
`);let
|
|
287
|
-
`);try{await
|
|
323
|
+
`):console.log(u);l.length>100&&console.log(D(`... ${l.length-100} more lines`))}else console.log(D("No changes to show."));console.log("");return}case"/checkpoint":{let i=s[0];if(!i||i==="list")console.log(D("Checkpoints: use the agent to manage checkpoints.")),console.log(D(' Tell Hablas: "save checkpoint before-refactor" or "list checkpoints"'));else if(i==="save"){let o=s[1]||"manual";console.log(D(`Telling Hablas to save checkpoint "${o}"...`)),e.session.addUserMessage(`checkpoint_save now, name="${o}", description="manual checkpoint from /checkpoint command"`,{priority:"critical",tags:["checkpoint","system-cmd"]}),console.log(D("Checkpoint request queued \u2014 continue typing to trigger it."))}return}case"/tests":{console.log(D('Running tests... tell Hablas: "run tests" for full output.'));return}case"/git":{let i=s[0];if(!i||i==="status"){let{exec:o}=await import("child_process"),a=await new Promise(c=>{o("git status --short --branch",{cwd:e.workingDir},(l,u)=>c(u))});console.log(""),console.log(a||"Not a git repo."),console.log("")}else if(i==="log"){let{exec:o}=await import("child_process"),a=await new Promise(c=>{o("git log --oneline -15",{cwd:e.workingDir},(l,u)=>c(u))});console.log(""),console.log(a||"No commits."),console.log("")}else console.log(V("Usage: /git [status|log]"));return}case"/mcp":{let i=s[0],o=sn();if(!i||i==="list"||i==="status"){let a=e.mcpManager?.list()||[],c=e.mcpManager?.getFailures()||[];console.log(""),!a.length&&!c.length&&(console.log(D(`No MCP servers connected. Configure them in ${o}`)),console.log(D('Example: { "mcpServers": { "github": { "command": "npx", "args": ["-y","@modelcontextprotocol/server-github"] } } }')));for(let l of a){console.log(oe(`${l.name} \xB7 ${l.tools.length} tool(s) \xB7 ${l.trusted?"trusted":"untrusted (confirm required)"}`));for(let u of l.tools.slice(0,10))console.log(` - ${u.name}${u.description?" \u2014 "+u.description:""}`)}for(let l of c)console.log(V(`${l.name} \xB7 failed to connect \xB7 ${l.error}`));console.log(""),console.log(D("Usage: /mcp [list|trust <name>|untrust <name>|remove <name>|reload]")),console.log("");return}if(i==="trust"||i==="untrust"){let a=s[1];if(!a){console.log(V(`Usage: /mcp ${i} <server-name>`));return}let c=du(a,i==="trust");console.log(c?oe(`"${a}" is now ${i==="trust"?"trusted (confirm-level access)":"untrusted (dangerous-level, always confirmed)"}. Reconnect with /mcp reload to apply.`):V(`No server named "${a}" in ${o}`));return}if(i==="remove"){let a=s[1];if(!a){console.log(V("Usage: /mcp remove <server-name>"));return}let c=fu(a);c&&e.registry&&e.mcpManager&&(await e.mcpManager.disconnect(a),e.registry.unregisterWhere(l=>di(l)&&l.startsWith(`mcp__${a}__`))),console.log(c?oe(`Removed "${a}"`):V(`No server named "${a}"`));return}if(i==="reload"){if(!e.mcpManager||!e.registry){console.log(V("MCP is not available in this session."));return}await e.mcpManager.disconnectAll(),e.registry.unregisterWhere(di);let{connected:a,failures:c}=await e.mcpManager.connectAll();for(let l of jt(e.mcpManager))e.registry.register(l);console.log(oe(`Reconnected: ${a.length} server(s)${c.length?`, ${c.length} failed`:""}`));return}console.log(V("Usage: /mcp [list|trust <name>|untrust <name>|remove <name>|reload]"));return}default:console.log(V(`Unknown command: ${n} \xB7 /help for reference`))}}var Ne=T(require("fs")),mi=T(require("path"));function gi(t){let e=mi.join(t,".hablas");return Ne.existsSync(e)||Ne.mkdirSync(e,{recursive:!0}),e}function hu(t){return mi.join(gi(t),"session.json")}function an(t,e){let r=hu(t);try{return Ne.existsSync(r)?(e.fromJSON(Ne.readFileSync(r,"utf-8")),!0):!1}catch{return!1}}function ar(t,e){let r=hu(t);try{Ne.writeFileSync(r,e.toJSON(),"utf-8")}catch{}}var mu=require("@modelcontextprotocol/sdk/client/index.js"),cn=require("@modelcontextprotocol/sdk/client/stdio.js");var yw=8e3,ww=1e4,bw=3e4;function yi(t,e,r){let n;return Promise.race([t,new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`${r} timed out after ${e}ms`)),e)})]).finally(()=>clearTimeout(n))}var Ft=class{servers=new Map;failures=[];async connectAll(){let e=on(),r=Object.entries(e.mcpServers).filter(([,n])=>!n.disabled);return this.failures=[],await Promise.allSettled(r.map(([n,s])=>this.connectOne(n,s))),{connected:this.list(),failures:this.failures}}async connectOne(e,r){this.servers.has(e)&&await this.disconnect(e);let n=null;try{n=new cn.StdioClientTransport({command:r.command,args:r.args||[],env:{...(0,cn.getDefaultEnvironment)(),...r.env||{}}});let s=new mu.Client({name:"hablas-cli",version:vt()},{capabilities:{}});await yi(s.connect(n),yw,`Connecting to MCP server "${e}"`);let i=await yi(s.listTools(),ww,`Listing tools for "${e}"`),o={name:e,client:s,transport:n,tools:(i.tools||[]).map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})),trusted:!!r.trusted,connectedAt:Date.now()};return this.servers.set(e,o),o}catch(s){if(n)try{await n.close()}catch{}return this.failures.push({name:e,error:s instanceof Error?s.message:String(s)}),null}}list(){return Array.from(this.servers.values())}get(e){return this.servers.get(e)}getFailures(){return this.failures}async disconnect(e){let r=this.servers.get(e);if(r){try{await r.client.close()}catch{}this.servers.delete(e)}}async disconnectAll(){await Promise.allSettled(Array.from(this.servers.keys()).map(e=>this.disconnect(e)))}async callTool(e,r,n){let s=this.servers.get(e);if(!s)return{success:!1,output:"",error:`MCP server not connected: ${e}`};try{let i=await yi(s.client.callTool({name:r,arguments:n}),bw,`Tool call "${r}" on "${e}"`),a=(Array.isArray(i.content)?i.content:[]).map(c=>c&&typeof c=="object"&&"text"in c?String(c.text):JSON.stringify(c)).join(`
|
|
324
|
+
`);return{success:!i.isError,output:a,error:i.isError?a:void 0}}catch(i){return{success:!1,output:"",error:i instanceof Error?i.message:String(i)}}}totalToolCount(){return Array.from(this.servers.values()).reduce((e,r)=>e+r.tools.length,0)}};async function wu(t,e){Zi();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=xt(t);gi(r);let s=new Ge(r,t),i=new At(t),o=await Mt(r,t),a=new Ot(Pt(o,nr("hello")),t.historySize,t.contextBudget);an(r,a);let c=new Jr(r);console.log(Ti(t.model,r));let l=new Qe("Connecting");l.start();let u=await n.checkConnection();if(l.stop(),u){let v=await n.listModels();console.log(oe(`${at(t)} \xB7 ${v.length} models available`))}else console.log(V(`offline \xB7 ${at(t)} \xB7 file inspection still works \xB7 /provider to switch`));gu.existsSync(yu.join(r,".git"))||console.log(D("no git repository detected \u2014 standalone workspace mode"));let d=new Ft,{connected:p,failures:h}=await d.connectAll();if(p.length>0){let v=p.reduce((_,C)=>_+C.tools.length,0);console.log(D(`mcp: ${p.length} server(s) \xB7 ${v} tool(s) \xB7 /mcp for details`));for(let _ of jt(d))s.register(_)}for(let v of h)console.log(V(`mcp: "${v.name}" failed to connect \u2014 ${v.error}`));console.log("");let f=0,m=0,g=Date.now(),y=0,b=null,w=null;for(ji({stop:()=>w?.stop()}),process.on("SIGINT",()=>{let v=Date.now();if(w?.stop(),w=null,b&&!b.signal.aborted){b.abort(),process.stdout.write(`
|
|
325
|
+
`),console.log(V("\u2298 turn cancelled")),y=v;return}if(v-y<2e3){process.stdout.write(`
|
|
326
|
+
`);let _=Math.round((Date.now()-g)/1e3);console.log(D(`session ended \xB7 turns=${f} \xB7 tool calls=${m} \xB7 ${_}s`)),c.close(),d.disconnectAll(),process.exit(0)}y=v,process.stdout.write(`
|
|
327
|
+
`),console.log(V("Ctrl+C again to exit"))});;){let _=(await c.prompt(" \u203A ")).trim();if(_){if(_.startsWith("/")){let C=await pu(_,{config:t,client:n,setClient:A=>{n=A},session:a,workingDir:r,mcpManager:d,registry:s});if(ar(r,a),C==="quit")break;continue}f++,console.log(Ci(f)),b=new AbortController;try{await en(_,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:c,interactive:!0,abortSignal:b.signal,onToolCall:()=>{m++}}),ar(r,a)}catch(C){let A=C;A?.name==="AbortError"||b.signal.aborted||(console.log(Ie(A?.message||"Turn failed")),e.error(C,"interactive turn failed"))}finally{b=null}}}await d.disconnectAll(),c.close()}async function bu(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=xt(e),i=new Ge(n,e),o=new At(e),a=await Mt(n,e),c=new Ot(Pt(a,nr(t)),e.historySize,e.contextBudget);an(n,c);let l=new Ft;try{await l.connectAll();for(let u of jt(l))i.register(u)}catch(u){r.warn(u,"MCP server connection failed \u2014 continuing with built-in tools only")}try{await en(t,{config:e,client:s,registry:i,contextManager:o,session:c,workingDir:n,logger:r,interactive:!1}),ar(n,c)}finally{await l.disconnectAll()}}var ln=T(require("fs")),ft=T(require("path")),vw=[{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"}],Sw=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),xw=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function _w(t,e){let r=[],n=e.split(`
|
|
328
|
+
`);for(let{pattern:s,name:i,severity:o}of vw){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let l=e.substring(0,a.index).split(`
|
|
329
|
+
`).length,u=n[l-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:l,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function kw(t,e){let r=[],n=e.split(`
|
|
330
|
+
`),s=ft.extname(t);return[".ts",".js",".tsx",".jsx"].includes(s)&&n.forEach((i,o)=>{/\beval\s*\(/.test(i)&&!i.trim().startsWith("//")&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Usage of eval() detected \u2014 potential code injection risk",suggestion:"Replace eval() with safer alternatives like JSON.parse() or Function constructor."}),/\.innerHTML\s*=/.test(i)&&r.push({severity:"medium",type:"code",file:t,line:o+1,message:"Direct innerHTML assignment \u2014 potential XSS vulnerability",suggestion:"Use textContent, or sanitize HTML with DOMPurify before assignment."}),/`.*\$\{.*\}.*(?:SELECT|INSERT|UPDATE|DELETE|DROP)/i.test(i)&&r.push({severity:"high",type:"code",file:t,line:o+1,message:"Potential SQL injection \u2014 string interpolation in SQL query",suggestion:"Use parameterized queries or an ORM instead of string interpolation."})}),r}function vu(t,e=[]){try{let r=ln.readdirSync(t,{withFileTypes:!0});for(let n of r){if(Sw.has(n.name))continue;let s=ft.join(t,n.name);if(n.isDirectory())vu(s,e);else if(n.isFile()){let i=ft.extname(n.name);xw.has(i)||e.push(s)}}}catch{}return e}function Su(t){let e=Date.now(),r=vu(t),n=[];for(let o of r)try{let a=ln.readFileSync(o,"utf-8"),c=ft.relative(t,o),l=_w(c,a);n.push(...l);let u=kw(c,a);n.push(...u)}catch{}let s=Date.now()-e,i={critical:n.filter(o=>o.severity==="critical").length,high:n.filter(o=>o.severity==="high").length,medium:n.filter(o=>o.severity==="medium").length,low:n.filter(o=>o.severity==="low").length,info:n.filter(o=>o.severity==="info").length};return{issues:n,scannedFiles:r.length,duration:s,summary:i}}function xu(t){let e=[];if(e.push(`
|
|
331
|
+
Security Scan Complete`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Files scanned: ${t.scannedFiles}`),e.push(` Duration: ${t.duration}ms`),e.push(""),t.issues.length===0)e.push(" \u2713 No security issues found!");else{e.push(` Issues found: ${t.issues.length}`),e.push(` Critical: ${t.summary.critical}`),e.push(` High: ${t.summary.high}`),e.push(` Medium: ${t.summary.medium}`),e.push(` Low: ${t.summary.low}`),e.push("");let r=t.issues.sort((n,s)=>{let i={critical:0,high:1,medium:2,low:3,info:4};return i[n.severity]-i[s.severity]}).slice(0,10);for(let n of r){let s=n.severity==="critical"?"\u{1F534}":n.severity==="high"?"\u{1F7E0}":n.severity==="medium"?"\u{1F7E1}":"\u{1F535}";e.push(` ${s} [${n.severity.toUpperCase()}] ${n.message}`),e.push(` File: ${n.file}${n.line?`:${n.line}`:""}`),e.push(` Fix: ${n.suggestion}`),e.push("")}}return e.join(`
|
|
332
|
+
`)}var Lt=T(require("fs")),wi=T(require("path")),ku=T(require("os")),Tw=wi.join(ku.homedir(),".hablas"),_u=wi.join(Tw,"analytics.json");function Tu(){try{if(Lt.existsSync(_u))return JSON.parse(Lt.readFileSync(_u,"utf-8"))}catch{}return Cw()}function Cw(){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 Cu(t){let e=[];e.push(`
|
|
333
|
+
\u{1F4CA} Developer Analytics`),e.push(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),e.push(` Sessions: ${t.totalSessions}`),e.push(` Messages: ${t.totalMessages}`),e.push(` Tokens used: ${t.totalTokensUsed.toLocaleString()}`),e.push(` Tool calls: ${t.totalToolCalls}`),e.push(` Files modified: ${t.totalFilesModified}`),e.push(` Lines written: ${t.totalLinesWritten.toLocaleString()}`),e.push(` Bugs fixed: ${t.totalBugsFixed}`),e.push(` Commits: ${t.totalCommits}`),e.push(""),e.push(` \u{1F525} Streak: ${t.streak} days (best: ${t.longestStreak})`),e.push("");let r=Object.entries(t.agentUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(r.length>0){e.push(" Top Agents:");for(let[s,i]of r)e.push(` @${s}: ${i} uses`);e.push("")}let n=Object.entries(t.commandUsage).sort((s,i)=>i[1]-s[1]).slice(0,5);if(n.length>0){e.push(" Top Commands:");for(let[s,i]of n)e.push(` ${s}: ${i} calls`)}return e.join(`
|
|
334
|
+
`)}var Au=T(require("readline"));var X="\x1B[36m",dt="\x1B[32m",Ce="\x1B[33m",M="\x1B[2m",ce="\x1B[1m",k="\x1B[0m",$u="\x1B[35m";function K(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function $w(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}function Aw(){return["fpY1CFJYuQ6D8J3gRbboHAQiMBhqjWg4"].join("")}var un={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas 1 \u2014 NVIDIA"},fn={provider:"mistral",apiUrl:"https://api.mistral.ai/v1",model:"mistral-code-agent-latest",name:"Hablas 2 \u2014 Mistral"};async function Eu(t){let e=Au.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${ce}${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${k}`),console.log(`${ce}${X} hablas \u2014 Setup Wizard${k}`),console.log(`${M} Configure your AI provider and model${k}`),console.log(`${ce}${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${k}`),console.log(),console.log(`${ce} Choose your setup:${k}`),console.log(),console.log(` ${$u}${ce}1${k}. ${ce}Hablas Integrated Engines${k} ${dt}(instant \u2014 no setup needed)${k}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${k}`),console.log(),console.log(` ${X}${ce}2${k}. ${ce}Custom Provider${k} ${M}(bring your own API key)${k}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${k}`),console.log(),(await K(e,` ${M}Your choice (1-2):${k} `)).trim()){case"1":{console.log(),console.log(`${ce} Choose your Hablas Integrated Engine:${k}`),console.log(),console.log(` ${$u}${ce}1${k}. ${ce}Hablas 1 \u2014 NVIDIA${k} ${dt}(recommended)${k}`),console.log(` ${M}stepfun-ai/step-3.7-flash \u2014 Powerful & fast${k}`),console.log(),console.log(` ${X}${ce}2${k}. ${ce}Hablas 2 \u2014 Mistral${k}`),console.log(` ${M}mistral-code-agent-latest \u2014 Excellent coding model${k}`),console.log();let n=(await K(e,` ${M}Your choice (1-2):${k} `)).trim();if(n==="1")t.provider=un.provider,t.apiUrl=un.apiUrl,t.apiKey=$w(),t.model=un.model,Be(t),console.log(),console.log(`${dt} \u2713 Hablas 1 \u2014 NVIDIA activated!${k}`),console.log(`${M} Model: ${un.model}${k}`);else if(n==="2")t.provider=fn.provider,t.apiUrl=fn.apiUrl,t.apiKey=Aw(),t.model=fn.model,Be(t),console.log(),console.log(`${dt} \u2713 Hablas 2 \u2014 Mistral activated!${k}`),console.log(`${M} Model: ${fn.model}${k}`);else{console.log(`${Ce} \u26A0 Invalid choice${k}`),e.close();return}break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${k}`),console.log(` ${X}a${k}. Ollama (local, free, private)`),console.log(` ${X}b${k}. OpenAI API`),console.log(` ${X}c${k}. Groq (fast, free tier)`),console.log(` ${X}d${k}. OpenRouter (many models)`),console.log(` ${X}e${k}. Together AI`),console.log(` ${X}f${k}. DeepSeek`),console.log(` ${X}g${k}. Custom OpenAI-compatible API`),console.log(` ${X}h${k}. NVIDIA NIM (powerful cloud models)`),console.log(` ${X}i${k}. Mistral AI ${dt}(free tier available)${k}`),console.log(),(await K(e,` ${M}Your choice (a-h):${k} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await K(e,` ${M}Ollama host [http://localhost:11434]:${k} `)).trim(),i=(await K(e,` ${M}Model [qwen2.5-coder:7b]:${k} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await K(e,` ${M}OpenAI API Key (sk-...):${k} `)).trim(),i=(await K(e,` ${M}Model [gpt-4o]:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.openai.com/v1",t.apiKey=s,t.model=i||"gpt-4o";break}case"c":{let s=(await K(e,` ${M}Groq API Key (gsk_...):${k} `)).trim(),i=(await K(e,` ${M}Model [llama-3.3-70b-versatile]:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.groq.com/openai/v1",t.apiKey=s,t.model=i||"llama-3.3-70b-versatile";break}case"d":{let s=(await K(e,` ${M}OpenRouter API Key (sk-or-...):${k} `)).trim(),i=(await K(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://openrouter.ai/api/v1",t.apiKey=s,t.model=i||"anthropic/claude-3.5-sonnet";break}case"e":{let s=(await K(e,` ${M}Together API Key:${k} `)).trim(),i=(await K(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.together.xyz/v1",t.apiKey=s,t.model=i||"meta-llama/Llama-3.3-70B-Instruct-Turbo";break}case"f":{let s=(await K(e,` ${M}DeepSeek API Key:${k} `)).trim(),i=(await K(e,` ${M}Model [deepseek-chat]:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl="https://api.deepseek.com/v1",t.apiKey=s,t.model=i||"deepseek-chat";break}case"g":{let s=(await K(e,` ${M}API base URL:${k} `)).trim(),i=(await K(e,` ${M}API key (optional):${k} `)).trim(),o=(await K(e,` ${M}Model ID:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 URL is required \u2014 cancelled${k}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await K(e,` ${M}NVIDIA API Key (nvapi-...):${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),console.log(`${M} Get your key at: https://build.nvidia.com/${k}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${k}`),de.models.forEach((a,c)=>{console.log(` ${X}${c+1}${k}. ${a}`)}),console.log();let i=(await K(e,` ${M}Model number [1]:${k} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=de.apiUrl,t.apiKey=s,t.model=de.models[o]||de.defaultModel;break}case"i":{let s=(await K(e,` ${M}Mistral API Key:${k} `)).trim();if(!s){console.log(`${Ce} \u26A0 No key provided \u2014 cancelled${k}`),console.log(`${M} Get your key at: https://console.mistral.ai/api-keys/${k}`),e.close();return}console.log(),console.log(`${M} Available Mistral models:${k}`),Ze.models.forEach((a,c)=>{console.log(` ${X}${c+1}${k}. ${a}`)}),console.log();let i=(await K(e,` ${M}Model number [1]:${k} `)).trim(),o=parseInt(i,10)-1;t.provider="mistral",t.apiUrl=Ze.apiUrl,t.apiKey=s,t.model=Ze.models[o]||Ze.defaultModel;break}default:console.log(`${Ce} \u26A0 Invalid choice${k}`),e.close();return}Be(t),console.log(),console.log(`${dt} \u2713 Custom provider configured successfully${k}`),console.log(`${M} Provider: ${t.provider}${k}`),console.log(`${M} Model: ${t.model}${k}`);break}default:console.log(`${Ce} \u26A0 Invalid choice \u2014 please select 1 or 2${k}`),e.close();return}console.log(),console.log(`${ce}${dt} \u2713 Setup complete!${k}`),console.log(`${M} Use ${X}hablas${k}${M} for interactive mode or ${X}hablas run "..."${k}${M} for one-shot execution.${k}`),console.log(),e.close()}var Ou=require("@modelcontextprotocol/sdk/server/index.js"),Ru=require("@modelcontextprotocol/sdk/server/stdio.js"),dn=require("@modelcontextprotocol/sdk/types.js");var Ew=6e4;function Ow(t,e,r){let n;return Promise.race([t,new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`${r} timed out after ${e}ms`)),e)})]).finally(()=>clearTimeout(n))}async function Iu(t,e){let r=new Ge(t,e),n=r.getAll().length,s=new Ou.Server({name:"hablas",version:vt()},{capabilities:{tools:{}},instructions:`Hablas MCP server exposing ${n} engineering tools. Use tools/list to discover available tools and tools/call to execute them.`});s.setRequestHandler(dn.ListToolsRequestSchema,async()=>({tools:r.getAll().map(a=>({name:a.name,description:a.description,inputSchema:su(a)}))})),s.setRequestHandler(dn.CallToolRequestSchema,async a=>{let{name:c,arguments:l}=a.params,u=r.get(c);if(!u)return{content:[{type:"text",text:`Unknown tool: ${c}. Use tools/list to see available tools.`}],isError:!0};try{let d=await Ow(u.execute(l??{}),Ew,`Tool "${c}"`);return{content:[{type:"text",text:d.output||d.error||"(no output)"}],isError:!d.success}}catch(d){return{content:[{type:"text",text:`Tool execution failed: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}});let i=new Ru.StdioServerTransport;await s.connect(i),process.stderr.write(`[hablas mcp-serve] ready \u2014 exposing ${n} tools over stdio (project: ${t})
|
|
335
|
+
`);let o=async a=>{process.stderr.write(`[hablas mcp-serve] received ${a}, shutting down...
|
|
336
|
+
`);try{await s.close()}catch{}process.exit(0)};process.on("SIGINT",()=>void o("SIGINT")),process.on("SIGTERM",()=>void o("SIGTERM"))}Li();var Mu=vt(),ne=new Xi;ne.name("hablas").description(`Hablas CLI v${Mu} \u2014 single-agent engineering runtime for the terminal.`).version(Mu).option("-m, --model <model>","Model to use").option("-p, --project <path>","Working directory").option("--host <url>","Ollama host URL").option("--provider <type>","LLM provider: ollama | custom | nvidia").option("--api-url <url>","Custom API base URL").option("--api-key <key>","API key for custom or nvidia provider").option("--auto","Auto mode \u2014 skip tool confirmations where allowed").option("--timeout <ms>","Request timeout in milliseconds","120000").option("--setup","Run setup wizard");ne.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=ne.opts(),r=tt({model:e.model,host:e.host,project:e.project,provider:e.provider,apiUrl:e.apiUrl,apiKey:e.apiKey});e.auto&&(r.autoMode=!0),e.timeout&&(r.timeout=parseInt(e.timeout,10));let n=Es(r);await bu(t,r,n)});ne.command("doctor").description("Run system diagnostics").action(async()=>{let t=ne.opts(),e=tt({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await tn({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(rn(r))});ne.command("info").description("Show workspace information").action(async()=>{let t=ne.opts(),e=tt({project:t.project});console.log(""),console.log(zr(Rt(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});ne.command("security").description("Run a security scan on the current project").action(async()=>{let t=ne.opts(),e=tt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(xu(Su(r)))});ne.command("stats").description("Show local usage statistics").action(async()=>{console.log(Cu(Tu()))});ne.command("mcp-serve").description("Expose Hablas' tools as an MCP server over stdio (for Claude Desktop, Cursor, etc.)").action(async()=>{let t=ne.opts(),e=tt({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;await Iu(r,e)});ne.command("mcp").description("Show MCP client config path and connected server status").action(async()=>{console.log(`MCP config file: ${sn()}`),console.log('Add servers under "mcpServers" (same shape as Claude Desktop / Cursor configs).'),console.log("Use the interactive session's /mcp command to inspect live connections.")});ne.action(async()=>{let t=ne.opts(),e=tt({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 Eu(e);return}let r=Es(e);await wu(e,r)});ne.parse();
|