hablas-ai 2.0.2 → 2.0.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 CHANGED
@@ -20,55 +20,55 @@ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
20
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 q.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()}`,q.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new dl(this.options),r=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&r(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!r(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let r=`error: missing required argument '${e}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(e){let r=`error: option '${e.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let r=`error: required option '${e.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,r){let n=o=>{let a=o.attributeName(),l=this.getOptionValue(a),f=this.options.find(d=>d.negate&&a===d.attributeName()),u=this.options.find(d=>!d.negate&&a===d.attributeName());return f&&(f.presetArg===void 0&&l===!1||f.presetArg!==void 0&&l===f.presetArg)?f:u||o},s=o=>{let a=n(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},i=`error: ${s(e)} cannot be used with ${s(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let r="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(a=>a.long).map(a=>a.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);r=Gn(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=Gn(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
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=>ul(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=ae.basename(e,ae.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=q.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
22
22
  Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof r=="function"?o=r({error:i.error,command:i.command}):o=r,o&&i.write(`${o}
23
- `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Jn(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})}Xn.Command=vr});var ts=I(J=>{var{Argument:Zn}=xt(),{Command:kr}=Yn(),{CommanderError:pl,InvalidArgumentError:Qn}=st(),{Help:hl}=mr(),{Option:es}=br();J.program=new kr;J.createCommand=t=>new kr(t);J.createOption=(t,e)=>new es(t,e);J.createArgument=(t,e)=>new Zn(t,e);J.Command=kr;J.Option=es;J.Argument=Zn;J.Help=hl;J.CommanderError=pl;J.InvalidArgumentError=Qn;J.InvalidOptionArgumentError=Qn});var Tr=I((Yh,ls)=>{"use strict";var ot=t=>t&&typeof t.message=="string",$r=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ot(r)?r:void 0}else return ot(e)?e:void 0},os=(t,e)=>{if(!ot(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
- causes have become circular...`;let n=$r(t);return n?(e.add(t),r+`
25
- caused by: `+os(n,e)):r},ml=t=>os(t,new Set),as=(t,e,r)=>{if(!ot(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=$r(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+as(s,e,i)}else return n},gl=t=>as(t,new Set);ls.exports={isErrorLike:ot,getErrorCause:$r,stackWithCauses:ml,messageWithCauses:gl}});var Ar=I((Zh,us)=>{"use strict";var yl=Symbol("circular-ref-tag"),vt=Symbol("pino-raw-err-ref"),cs=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[vt]},set:function(t){this[vt]=t}}});Object.defineProperty(cs,vt,{writable:!0,value:{}});us.exports={pinoErrProto:cs,pinoErrorSymbols:{seen:yl,rawSymbol:vt}}});var ps=I((Qh,ds)=>{"use strict";ds.exports=Or;var{messageWithCauses:wl,stackWithCauses:bl,isErrorLike:fs}=Tr(),{pinoErrProto:Sl,pinoErrorSymbols:_l}=Ar(),{seen:Er}=_l,{toString:xl}=Object.prototype;function Or(t){if(!fs(t))return t;t[Er]=void 0;let e=Object.create(Sl);e.type=xl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=wl(t),e.stack=bl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Or(r)));for(let r in t)if(e[r]===void 0){let n=t[r];fs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Er)&&(e[r]=Or(n)):e[r]=n}return delete t[Er],e.raw=t,e}});var ms=I((em,hs)=>{"use strict";hs.exports=Ct;var{isErrorLike:Rr}=Tr(),{pinoErrProto:vl,pinoErrorSymbols:kl}=Ar(),{seen:kt}=kl,{toString:Cl}=Object.prototype;function Ct(t){if(!Rr(t))return t;t[kt]=void 0;let e=Object.create(vl);e.type=Cl.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=>Ct(r))),Rr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,kt)&&(e.cause=Ct(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Rr(n)?Object.prototype.hasOwnProperty.call(n,kt)||(e[r]=Ct(n)):e[r]=n}return delete t[kt],e.raw=t,e}});var bs=I((tm,ws)=>{"use strict";ws.exports={mapHttpRequest:$l,reqSerializer:ys};var Ir=Symbol("pino-raw-req-ref"),gs=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[Ir]},set:function(t){this[Ir]=t}}});Object.defineProperty(gs,Ir,{writable:!0,value:{}});function ys(t){let e=t.info||t.socket,r=Object.create(gs);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 $l(t){return{req:ys(t)}}});var vs=I((rm,xs)=>{"use strict";xs.exports={mapHttpResponse:Tl,resSerializer:_s};var Pr=Symbol("pino-raw-res-ref"),Ss=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Pr]},set:function(t){this[Pr]=t}}});Object.defineProperty(Ss,Pr,{writable:!0,value:{}});function _s(t){let e=Object.create(Ss);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function Tl(t){return{res:_s(t)}}});var Fr=I((nm,ks)=>{"use strict";var Mr=ps(),Al=ms(),$t=bs(),Tt=vs();ks.exports={err:Mr,errWithCause:Al,mapHttpRequest:$t.mapHttpRequest,mapHttpResponse:Tt.mapHttpResponse,req:$t.reqSerializer,res:Tt.resSerializer,wrapErrorSerializer:function(e){return e===Mr?e:function(n){return e(Mr(n))}},wrapRequestSerializer:function(e){return e===$t.reqSerializer?e:function(n){return e($t.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===Tt.resSerializer?e:function(n){return e(Tt.resSerializer(n))}}}});var Lr=I((sm,Cs)=>{"use strict";function El(t,e){return e}Cs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=El;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 Rs=I((im,Os)=>{"use strict";function Dr(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]=Dr(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]=Dr(t[r]));return e}return t}function $s(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 Ts(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 As(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 At=Symbol("PATH_NOT_FOUND");function Ol(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return At;r=r[n]}return r}function Rl(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 Il(t,e,r,n=!1){for(let s of e){let i=$s(s);if(i.includes("*"))Es(t,i,r,s,n);else if(n)As(t,i);else{let o=Ol(t,i);if(o===At)continue;let a=typeof r=="function"?r(o,i):r;Ts(t,i,a)}}}function Es(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let f=[...o,l.toString()],u=typeof r=="function"?r(a[l],f):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&l.push(f);for(let f of l)delete a[f]}else for(let l in a){let f=[...o,l],u=typeof r=="function"?r(a[l],f):r;a[l]=u}}else Pl(t,e,r,i,n,s)}function Pl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function f(u,d){if(d===o.length){if(Array.isArray(u))for(let h=0;h<u.length;h++)l[d]=h.toString(),f(u[h],d+1);else if(typeof u=="object"&&u!==null)for(let h in u)l[d]=h,f(u[h],d+1)}else if(d<o.length){let h=o[d];u&&typeof u=="object"&&u!==null&&h in u&&(l[d]=h,f(u[h],d+1))}else if(a.includes("*"))Es(u,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,d),...c];return r(p,m)}:r,s,i);else if(i)As(u,a);else{let h=typeof r=="function"?r(Rl(u,a),[...l.slice(0,d),...a]):r;Ts(u,a,h)}}if(o.length===0)f(t,0);else{let u=t;for(let d=0;d<o.length;d++){let h=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[h],l[d]=h}u!=null&&f(u,o.length)}}function Ml(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=$s(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 Fl(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let f=l.toString();s.has(f)||s.has("*")?a[l]=r(n[l],s.get(f)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function Ll(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 Dl(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Ll(e)}function jl(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Dl(e);let o=Ml(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let f=Fl(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Il(f,e,d,i),n===!1?(f.restore=function(){return Dr(u)},f):typeof n=="function"?n(f):JSON.stringify(f)}}Os.exports=jl});var Ne=I((om,Is)=>{"use strict";var Nl=Symbol("pino.setLevel"),ql=Symbol("pino.getLevel"),Ul=Symbol("pino.levelVal"),Bl=Symbol("pino.levelComp"),Hl=Symbol("pino.useLevelLabels"),Wl=Symbol("pino.useOnlyCustomLevels"),Vl=Symbol("pino.mixin"),zl=Symbol("pino.lsCache"),Kl=Symbol("pino.chindings"),Gl=Symbol("pino.asJson"),Jl=Symbol("pino.write"),Xl=Symbol("pino.redactFmt"),Yl=Symbol("pino.time"),Zl=Symbol("pino.timeSliceIndex"),Ql=Symbol("pino.stream"),ec=Symbol("pino.stringify"),tc=Symbol("pino.stringifySafe"),rc=Symbol("pino.stringifiers"),nc=Symbol("pino.end"),sc=Symbol("pino.formatOpts"),ic=Symbol("pino.messageKey"),oc=Symbol("pino.errorKey"),ac=Symbol("pino.nestedKey"),lc=Symbol("pino.nestedKeyStr"),cc=Symbol("pino.mixinMergeStrategy"),uc=Symbol("pino.msgPrefix"),fc=Symbol("pino.wildcardFirst"),dc=Symbol.for("pino.serializers"),pc=Symbol.for("pino.formatters"),hc=Symbol.for("pino.hooks"),mc=Symbol.for("pino.metadata");Is.exports={setLevelSym:Nl,getLevelSym:ql,levelValSym:Ul,levelCompSym:Bl,useLevelLabelsSym:Hl,mixinSym:Vl,lsCacheSym:zl,chindingsSym:Kl,asJsonSym:Gl,writeSym:Jl,serializersSym:dc,redactFmtSym:Xl,timeSym:Yl,timeSliceIndexSym:Zl,streamSym:Ql,stringifySym:ec,stringifySafeSym:tc,stringifiersSym:rc,endSym:nc,formatOptsSym:sc,messageKeySym:ic,errorKeySym:oc,nestedKeySym:ac,wildcardFirstSym:fc,needsMetadataGsym:mc,useOnlyCustomLevelsSym:Wl,formattersSym:pc,hooksSym:hc,nestedKeyStrSym:lc,mixinMergeStrategySym:cc,msgPrefixSym:uc}});var Nr=I((am,Ls)=>{"use strict";var Ps=Rs(),{redactFmtSym:gc,wildcardFirstSym:Et}=Ne(),jr=/[^.[\]]+|\[([^[\]]*?)\]/g,Ms="[Redacted]",Fs=!1;function yc(t,e){let{paths:r,censor:n,remove:s}=wc(t),i=r.reduce((l,f)=>{jr.lastIndex=0;let u=jr.exec(f),d=jr.exec(f),h=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(h==="*"&&(h=Et),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,c=`${f.substr(p,f.length-1)}`;return l[h]=l[h]||[],h!==Et&&l[h].length===0&&l[h].push(...l[Et]||[]),h===Et&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[gc]:Ps({paths:r,censor:n,serialize:e,strict:Fs,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,f)=>{if(i[f]===null)l[f]=u=>a(u,[f]);else{let u=typeof n=="function"?(d,h)=>n(d,[f,...h]):n;l[f]=Ps({paths:i[f],censor:u,serialize:e,strict:Fs,remove:s})}return l},o)}function wc(t){if(Array.isArray(t))return t={paths:t,censor:Ms},t;let{paths:e,censor:r=Ms,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}}Ls.exports=yc});var Ns=I((lm,js)=>{"use strict";var bc=()=>"",Sc=()=>`,"time":${Date.now()}`,_c=()=>`,"time":${Math.round(Date.now()/1e3)}`,xc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,vc=1000000n,Ds=1000000000n,kc=BigInt(Date.now())*vc,Cc=process.hrtime.bigint(),$c=()=>{let t=process.hrtime.bigint()-Cc,e=kc+t,r=e/Ds,n=e%Ds,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${f}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};js.exports={nullTime:bc,epochTime:Sc,unixTime:_c,isoTime:xc,isoTimeNano:$c}});var Us=I((cm,qs)=>{"use strict";function Tc(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}qs.exports=Ac;function Ac(t,e,r){var n=r&&r.stringify||Tc,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var f="",u=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(f+=t.slice(d,p));var c=typeof e[u];if(c==="string"){f+="'"+e[u]+"'",d=p+2,p++;break}if(c==="function"){f+=e[u].name||"<anonymous>",d=p+2,p++;break}f+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(f+=t.slice(d,p)),f+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(f+=t.slice(d,p)),f+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<h&&(f+=t.slice(d)),f)}});var Ur=I((um,qr)=>{"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));qr.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(););};qr.exports=t}});var Js=I((fm,Gs)=>{"use strict";var D=require("fs"),Ec=require("events"),Oc=require("util").inherits,Bs=require("path"),Hr=Ur(),Rc=require("assert"),Ot=100,Rt=Buffer.allocUnsafe(0),Ic=16*1024,Hs="buffer",Ws="utf8",[Pc,Mc]=(process.versions.node||"0.0").split(".").map(Number),Fc=Pc>=22&&Mc>=7;function Vs(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&&D.mkdirSync(Bs.dirname(t),{recursive:!0});let i=D.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?D.mkdir(Bs.dirname(t),{recursive:!0},i=>{if(i)return r(i);D.open(t,n,s,r)}):D.open(t,n,s,r)}function te(t){if(!(this instanceof te))return new te(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:f,retryEAGAIN:u,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Ic,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=f||!1;let c,m;if(h===Hs)this._writingBuf=Rt,this.write=jc,this.flush=qc,this.flushSync=Bc,this._actualWrite=Wc,c=()=>D.writeSync(this.fd,this._writingBuf),m=()=>D.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Ws)this._writingBuf="",this.write=Dc,this.flush=Nc,this.flushSync=Uc,this._actualWrite=Hc,c=()=>Buffer.isBuffer(this._writingBuf)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?D.write(this.fd,this._writingBuf,this.release):D.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ws}" and "${Hs}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Vs(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=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Hr(Ot),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,Ot);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Br(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),k=Br(this._writingBuf,this._len,S);this._len=k.len,this._writingBuf=k.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&D.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,It(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Lc,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Br(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 Lc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Oc(te,Ec);function zs(t,e){return t.length===0?Rt:t.length===1?t[0]:Buffer.concat(t,e)}function Dc(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 jc(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 Ks(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{D.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 Nc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function qc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.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&&D.close(e,r=>{if(r)return this.emit("error",r)})}),Vs(this.file,this)};te.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():It(this)))};function Uc(){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)?D.writeSync(this.fd,t):D.writeSync(this.fd,t,"utf8"),r=Br(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;Hr(Ot)}}try{D.fsyncSync(this.fd)}catch{}}function Bc(){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=Rt);let t=Rt;for(;this._bufs.length||t.length;){t.length<=0&&(t=zs(this._bufs[0],this._lens[0]));try{let e=D.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;Hr(Ot)}}}te.prototype.destroy=function(){this.destroyed||It(this)};function Hc(){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)?D.writeSync(this.fd,this._writingBuf):D.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else D.write(this.fd,this._writingBuf,t)}function Wc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:zs(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=D.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Fc&&(this._writingBuf=Buffer.from(this._writingBuf)),D.write(this.fd,this._writingBuf,t)}function It(t){if(t.fd===-1){t.once("ready",It.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Rc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{D.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?D.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")}}te.SonicBoom=te;te.default=te;Gs.exports=te});var Wr=I((dm,ei)=>{"use strict";var re={exit:[],beforeExit:[]},Xs={exit:Kc,beforeExit:Gc},qe;function Vc(){qe===void 0&&(qe=new FinalizationRegistry(Jc))}function zc(t){re[t].length>0||process.on(t,Xs[t])}function Ys(t){re[t].length>0||(process.removeListener(t,Xs[t]),re.exit.length===0&&re.beforeExit.length===0&&(qe=void 0))}function Kc(){Zs("exit")}function Gc(){Zs("beforeExit")}function Zs(t){for(let e of re[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}re[t]=[]}function Jc(t){for(let e of["exit","beforeExit"]){let r=re[e].indexOf(t);re[e].splice(r,r+1),Ys(e)}}function Qs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");zc(t);let n=new WeakRef(e);n.fn=r,Vc(),qe.register(e,n),re[t].push(n)}function Xc(t,e){Qs("exit",t,e)}function Yc(t,e){Qs("beforeExit",t,e)}function Zc(t){if(qe!==void 0){qe.unregister(t);for(let e of["exit","beforeExit"])re[e]=re[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ys(e)}}ei.exports={register:Xc,registerBeforeExit:Yc,unregister:Zc}});var ti=I((pm,Qc)=>{Qc.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 ni=I((hm,ri)=>{"use strict";function eu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,a,l);f.async?f.value.then(o):setImmediate(o)};o()}function tu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,r,l);f.async?f.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ri.exports={wait:eu,waitDiff:tu}});var ii=I((mm,si)=>{"use strict";si.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var yi=I((gm,gi)=>{"use strict";var{version:ru}=ti(),{EventEmitter:nu}=require("events"),{Worker:su}=require("worker_threads"),{join:iu}=require("path"),{pathToFileURL:ou}=require("url"),{wait:au}=ni(),{WRITE_INDEX:le,READ_INDEX:xe,SEQ_INDEX:Vr}=ii(),lu=require("buffer"),cu=require("assert"),g=Symbol("kImpl"),uu=lu.constants.MAX_STRING_LENGTH;function oi(){}function Jr(t,e){Atomics.add(t[g].state,Vr,1),e(),Atomics.add(t[g].state,Vr,1),Atomics.notify(t[g].state,Vr)}function ai(t){Jr(t,()=>{Atomics.store(t[g].state,xe,0),Atomics.store(t[g].state,le,0)})}var at=class{constructor(e){this._value=e}deref(){return this._value}},Pt=class{register(){}unregister(){}},fu=process.env.NODE_V8_COVERAGE?Pt:global.FinalizationRegistry||Pt,du=process.env.NODE_V8_COVERAGE?at:global.WeakRef||at,li=new fu(t=>{t.exited||t.terminate()});function pu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||iu(__dirname,"lib","worker.js"),o=new su(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:ou(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:ru},...n}}});return o.stream=new at(t),o.on("message",hu),o.on("exit",fi),li.register(t,o),o}function ci(t){cu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ui(t){for(;;){let e=Atomics.load(t[g].state,le),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t);return}hi(t,r,oi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Mt(t,()=>{t.destroyed||(ai(t),ui(t))});return}X(t,new Error("overwritten"));return}}function hu(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 du(e),Mt(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":X(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"){X(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:X(e,new Error("this should not happen: "+t.code))}}function fi(t){let e=this.stream.deref();e!==void 0&&(li.unregister(e),e.worker.exited=!0,e.worker.off("exit",fi),X(e,t!==0?new Error("the worker thread exited"):null))}var Kr=class extends nu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=pu(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[g].destroyed)return Gr(this,new Error("the worker has exited")),!1;if(this[g].ending)return Gr(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=uu)try{zr(this),this[g].flushing=!0}catch(n){return X(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return zr(this),!0}catch(n){return X(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ui,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,le)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Xr(this))}flush(e){e=typeof e=="function"?e:oi,di(this,r=>{if(r){process.nextTick(e,r);return}pi(this,e)})}flushSync(){this[g].destroyed||(zr(this),mi(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function di(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(di,t,e);return}Mt(t,e)}function Mt(t,e){let r=Atomics.load(t[g].state,le);au(t[g].state,xe,r,1/0,(n,s)=>{if(n){X(t,n),e(n);return}if(s!=="ok"){Mt(t,e);return}e()})}function pi(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),pi(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[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),X(t,n),process.nextTick(e,n)}}function mu(t,e){let r=t[g].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 Gr(t,e){setImmediate(()=>{t.emit("error",e)})}function X(t,e){t[g].destroyed||(t[g].destroyed=!0,mu(t,e),e&&(t[g].errored=e,Gr(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function hi(t,e,r){let s=Atomics.load(t[g].state,le),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return Jr(t,()=>{Atomics.store(t[g].state,le,s)}),r(),!0}function Xr(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,xe);Jr(t,()=>{Atomics.store(t[g].state,le,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,xe,e,1e3),e=Atomics.load(t[g].state,xe),e===-2){X(t,new Error("end() failed"));return}if(++r===10){X(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){X(t,e)}}}function zr(t){let e=()=>{t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,le),n=t[g].data.length-r;if(n===0){mi(t),ai(t);continue}else if(n<0)throw new Error("overwritten");hi(t,n,e)}}function mi(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,le),r=0;for(;;){let n=Atomics.load(t[g].state,xe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,xe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}gi.exports=Kr});var Qr=I((ym,Si)=>{"use strict";var{createRequire:gu}=require("module"),{existsSync:yu}=require("node:fs"),wu=Lr(),{join:Yr,isAbsolute:bi,sep:bu}=require("node:path"),{fileURLToPath:Su}=require("node:url"),_u=Ur(),Zr=Wr(),xu=yi();function vu(t){Zr.register(t,Au),Zr.registerBeforeExit(t,Eu),t.on("close",function(){Zr.unregister(t)})}function ku(){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 Cu(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&&wi(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(wi(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function wi(t){let e=$u(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Su(r)}catch{return!1}return bi(r)&&!yu(r)}function $u(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function Tu(t,e,r,n,s){if(!r.execArgv&&ku()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Cu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new xu({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&&vu(i)}function a(){i.closed||(i.flushSync(),_u(100),i.end())}return i}function Au(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Eu(t){t.flushSync()}function Ou(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=wu(),sync:a=!1}=t,l={...t.options},f=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"]||Yr(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(d=u["pino-worker"]||Yr(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return Tu(p(d),l,i,a,h);function p(c){if(c=u[c]||c,bi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Yr(__dirname,"..","file.js");let m;for(let y of f)try{let w=y==="node:repl"?process.cwd()+bu:y;m=gu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Si.exports=Ou});var Dt=I((wm,Pi)=>{"use strict";var Ru=require("node:diagnostics_channel"),_i=Us(),{mapHttpRequest:Iu,mapHttpResponse:Pu}=Fr(),tn=Js(),xi=Wr(),{lsCacheSym:Mu,chindingsSym:Ti,writeSym:vi,serializersSym:Ai,formatOptsSym:ki,endSym:Fu,stringifiersSym:Ei,stringifySym:Oi,stringifySafeSym:rn,wildcardFirstSym:Ri,nestedKeySym:Lu,formattersSym:Ii,messageKeySym:Du,errorKeySym:ju,nestedKeyStrSym:Nu,msgPrefixSym:Ft}=Ne(),{isMainThread:qu}=require("worker_threads"),Uu=Qr(),[Bu]=process.versions.node.split(".").map(t=>Number(t)),Ci=Ru.tracingChannel("pino_asJson"),en=Bu>=25?t=>JSON.stringify(t):Wu;function Ue(){}function Hu(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=Iu(n):typeof n.setHeader=="function"&&(n=Pu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](n,_i(i,o,this[ki]),t)}else{let i=n===void 0?s.shift():n;typeof this[Ft]=="string"&&i!==void 0&&i!==null&&(i=this[Ft]+i),this[vi](null,_i(i,s,this[ki]),t)}}}function Wu(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 Vu(t,e,r,n){if(Ci.hasSubscribers===!1)return $i.call(this,t,e,r,n);let s={instance:this,arguments};return Ci.traceSync($i,s,this,t,e,r,n)}function $i(t,e,r,n){let s=this[Oi],i=this[rn],o=this[Ei],a=this[Fu],l=this[Ti],f=this[Ai],u=this[Ii],d=this[Du],h=this[ju],p=this[Mu][r]+n;p=p+l;let c;u.log&&(t=u.log(t));let m=o[Ri],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){f[b]?c=f[b](c):b===h&&f.err&&(c=f.err(c));let _=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":_&&(c=_(c));break;case"string":c=(_||en)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=en(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=f[d]?f[d](e):e;let b=o[d]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+d+'":'+c;break;case"string":c=(b||en)(c),w=',"'+d+'":'+c;break;default:c=(b||s)(c,i),w=',"'+d+'":'+c}}return this[Lu]&&y?p+this[Nu]+y.slice(1)+"}"+w+a:p+y+w+a}function zu(t,e){let r,n=t[Ti],s=t[Oi],i=t[rn],o=t[Ei],a=o[Ri],l=t[Ai],f=t[Ii].bindings;e=f(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Ku(t){return t.write!==t.constructor.prototype.write}function Lt(t){let e=new tn(t);return e.on("error",r),!t.sync&&qu&&(xi.register(e,Gu),e.on("close",function(){xi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ue,e.end=Ue,e.flushSync=Ue,e.destroy=Ue;return}e.removeListener("error",r),e.emit("error",n)}}function Gu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Ju(t){return function(r,n,s={},i){if(typeof s=="string")i=Lt({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=Lt({dest:i})}else if(s instanceof tn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof tn||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Uu({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=Ue),i||(Ku(process.stdout)?i=process.stdout:i=Lt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Xu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[rn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Yu(t,e,r){return{level:t,bindings:e,log:r}}function Zu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Pi.exports={noop:Ue,buildSafeSonicBoom:Lt,asChindings:zu,asJson:Vu,genLog:Hu,createArgsNormalizer:Ju,stringify:Xu,buildFormatters:Yu,normalizeDestFileDescriptor:Zu}});var jt=I((bm,Mi)=>{var Qu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ef={ASC:"ASC",DESC:"DESC"};Mi.exports={DEFAULT_LEVELS:Qu,SORTING_ORDER:ef}});var on=I((Sm,ji)=>{"use strict";var{lsCacheSym:tf,levelValSym:nn,useOnlyCustomLevelsSym:rf,streamSym:nf,formattersSym:sf,hooksSym:of,levelCompSym:Fi}=Ne(),{noop:af,genLog:ve}=Dt(),{DEFAULT_LEVELS:ie,SORTING_ORDER:Li}=jt(),Di={fatal:t=>{let e=ve(ie.fatal,t);return function(...r){let n=this[nf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ve(ie.error,t),warn:t=>ve(ie.warn,t),info:t=>ve(ie.info,t),debug:t=>ve(ie.debug,t),trace:t=>ve(ie.trace,t)},sn=Object.keys(ie).reduce((t,e)=>(t[ie[e]]=e,t),{}),lf=Object.keys(sn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function cf(t){let e=t[sf].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[tf]=n,t}function uf(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 ff(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[nn],s=this[nn]=r[t],i=this[rf],o=this[Fi],a=this[of].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=af;continue}this[l]=uf(l,i)?Di[l](a):ve(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function df(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function pf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Fi](r,this[nn])}function hf(t,e,r){return t===Li.DESC?e<=r:e>=r}function mf(t){return typeof t=="string"?hf.bind(null,t):t}function gf(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:sn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ie,t);return{labels:n,values:s}}function yf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(sn).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:ie,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function wf(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 bf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Li).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ji.exports={initialLsCache:lf,genLsCache:cf,levelMethods:Di,getLevel:df,setLevel:ff,isLevelEnabled:pf,mappings:gf,assertNoLevelCollisions:wf,assertDefaultLevelFound:yf,genLevelComparison:mf,assertLevelComparison:bf}});var an=I((_m,Ni)=>{"use strict";Ni.exports={version:"10.3.1"}});var Ki=I((vm,zi)=>{"use strict";var{EventEmitter:Sf}=require("node:events"),{lsCacheSym:_f,levelValSym:xf,setLevelSym:cn,getLevelSym:qi,chindingsSym:qt,mixinSym:vf,asJsonSym:Bi,writeSym:kf,mixinMergeStrategySym:Cf,timeSym:$f,timeSliceIndexSym:Tf,streamSym:Hi,serializersSym:ke,formattersSym:lt,errorKeySym:Af,messageKeySym:Ef,useOnlyCustomLevelsSym:Of,needsMetadataGsym:Rf,redactFmtSym:If,stringifySym:Pf,formatOptsSym:Mf,stringifiersSym:Ff,msgPrefixSym:un,hooksSym:Lf}=Ne(),{getLevel:Df,setLevel:jf,isLevelEnabled:Nf,mappings:qf,initialLsCache:Uf,genLsCache:Bf,assertNoLevelCollisions:Hf}=on(),{asChindings:fn,asJson:Wf,buildFormatters:ln,stringify:Ui,noop:Wi}=Dt(),{version:Vf}=an(),zf=Nr(),Kf=class{},Vi={constructor:Kf,child:Gf,bindings:Jf,setBindings:Xf,flush:Qf,isLevelEnabled:Nf,version:Vf,get level(){return this[qi]()},set level(t){this[cn](t)},get levelVal(){return this[xf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[un]},get[Symbol.toStringTag](){return"Pino"},[_f]:Uf,[kf]:Zf,[Bi]:Wf,[qi]:Df,[cn]:jf};Object.setPrototypeOf(Vi,Sf.prototype);zi.exports=function(){return Object.create(Vi)};var Nt=t=>t;function Gf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[ke],n=this[lt],s=Object.create(this);if(e==null)return s[lt].bindings!==Nt&&(s[lt]=ln(n.level,Nt,n.log)),s[qt]=fn(s,t),this.onChild!==Wi&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[ke]=Object.create(null);for(let f in r)s[ke][f]=r[f];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let f=a[i];s[ke][f]=r[f]}for(let f in e.serializers)s[ke][f]=e.serializers[f];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let f=l[o];s[ke][f]=e.serializers[f]}}else s[ke]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:f}=e.formatters;s[lt]=ln(a||n.level,l||Nt,f||n.log)}else s[lt]=ln(n.level,Nt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Hf(this.levels,e.customLevels),s.levels=qf(e.customLevels,s[Of]),Bf(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=zf(s.redact,Ui),l={stringify:a[If]};s[Pf]=Ui,s[Ff]=a,s[Mf]=l}if(typeof e.msgPrefix=="string"&&(s[un]=(this[un]||"")+e.msgPrefix),s[qt]=fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[cn](a)}return this.onChild(s),s}function Jf(){let e=`{${this[qt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Xf(t){let e=fn(this,t);this[qt]=e}function Yf(t,e){return Object.assign(e,t)}function Zf(t,e,r){let n=this[$f](),s=this[vf],i=this[Af],o=this[Ef],a=this[Cf]||Yf,l,f=this[Lf].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Bi](l,e,r,n),d=this[Hi];d[Rf]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[Tf]),d.lastLogger=this),d.write(f?f(u):u)}function Qf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Hi];typeof e.flush=="function"?e.flush(t||Wi):t&&t()}});var Yi=I((mn,Xi)=>{"use strict";var{hasOwnProperty:ct}=Object.prototype,$e=hn();$e.configure=hn;$e.stringify=$e;$e.default=$e;mn.stringify=$e;mn.configure=hn;Xi.exports=$e;var ed=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function me(t){return t.length<5e3&&!ed.test(t)?`"${t}"`:JSON.stringify(t)}function dn(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 td=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function pn(t){return td.call(t)!==void 0&&t.length!==0}function Gi(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 rd(t){if(ct.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function nd(t){let e;if(ct.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function sd(t,e){let r;if(ct.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ji(t,e){let r;if(ct.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ce(t){return t===1?"1 item":`${t} items`}function id(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function od(t){if(ct.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function hn(t){t={...t};let e=od(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=rd(t),n=sd(t,"bigint"),s=nd(t),i=typeof s=="function"?s:void 0,o=Ji(t,"maximumDepth"),a=Ji(t,"maximumBreadth");function l(p,c,m,y,w,b){let _=c[p];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(p)),_=y.call(c,p,_),typeof _){case"string":return me(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",k=",",R=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
23
+ `)}),this}_outputHelpIfRequested(e){let r=this._getHelpOption();r&&e.find(s=>r.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Jn(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})}Xn.Command=vr});var ts=I(J=>{var{Argument:Zn}=xt(),{Command:kr}=Yn(),{CommanderError:pl,InvalidArgumentError:Qn}=st(),{Help:hl}=mr(),{Option:es}=br();J.program=new kr;J.createCommand=t=>new kr(t);J.createOption=(t,e)=>new es(t,e);J.createArgument=(t,e)=>new Zn(t,e);J.Command=kr;J.Option=es;J.Argument=Zn;J.Help=hl;J.CommanderError=pl;J.InvalidArgumentError=Qn;J.InvalidOptionArgumentError=Qn});var $r=I((Yh,ls)=>{"use strict";var ot=t=>t&&typeof t.message=="string",Tr=t=>{if(!t)return;let e=t.cause;if(typeof e=="function"){let r=t.cause();return ot(r)?r:void 0}else return ot(e)?e:void 0},os=(t,e)=>{if(!ot(t))return"";let r=t.stack||"";if(e.has(t))return r+`
24
+ causes have become circular...`;let n=Tr(t);return n?(e.add(t),r+`
25
+ caused by: `+os(n,e)):r},ml=t=>os(t,new Set),as=(t,e,r)=>{if(!ot(t))return"";let n=r?"":t.message||"";if(e.has(t))return n+": ...";let s=Tr(t);if(s){e.add(t);let i=typeof t.cause=="function";return n+(i?"":": ")+as(s,e,i)}else return n},gl=t=>as(t,new Set);ls.exports={isErrorLike:ot,getErrorCause:Tr,stackWithCauses:ml,messageWithCauses:gl}});var Ar=I((Zh,us)=>{"use strict";var yl=Symbol("circular-ref-tag"),vt=Symbol("pino-raw-err-ref"),cs=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[vt]},set:function(t){this[vt]=t}}});Object.defineProperty(cs,vt,{writable:!0,value:{}});us.exports={pinoErrProto:cs,pinoErrorSymbols:{seen:yl,rawSymbol:vt}}});var ps=I((Qh,ds)=>{"use strict";ds.exports=Or;var{messageWithCauses:wl,stackWithCauses:bl,isErrorLike:fs}=$r(),{pinoErrProto:Sl,pinoErrorSymbols:_l}=Ar(),{seen:Er}=_l,{toString:xl}=Object.prototype;function Or(t){if(!fs(t))return t;t[Er]=void 0;let e=Object.create(Sl);e.type=xl.call(t.constructor)==="[object Function]"?t.constructor.name:t.name,e.message=wl(t),e.stack=bl(t),Array.isArray(t.errors)&&(e.aggregateErrors=t.errors.map(r=>Or(r)));for(let r in t)if(e[r]===void 0){let n=t[r];fs(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Er)&&(e[r]=Or(n)):e[r]=n}return delete t[Er],e.raw=t,e}});var ms=I((em,hs)=>{"use strict";hs.exports=Ct;var{isErrorLike:Rr}=$r(),{pinoErrProto:vl,pinoErrorSymbols:kl}=Ar(),{seen:kt}=kl,{toString:Cl}=Object.prototype;function Ct(t){if(!Rr(t))return t;t[kt]=void 0;let e=Object.create(vl);e.type=Cl.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=>Ct(r))),Rr(t.cause)&&!Object.prototype.hasOwnProperty.call(t.cause,kt)&&(e.cause=Ct(t.cause));for(let r in t)if(e[r]===void 0){let n=t[r];Rr(n)?Object.prototype.hasOwnProperty.call(n,kt)||(e[r]=Ct(n)):e[r]=n}return delete t[kt],e.raw=t,e}});var bs=I((tm,ws)=>{"use strict";ws.exports={mapHttpRequest:Tl,reqSerializer:ys};var Ir=Symbol("pino-raw-req-ref"),gs=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[Ir]},set:function(t){this[Ir]=t}}});Object.defineProperty(gs,Ir,{writable:!0,value:{}});function ys(t){let e=t.info||t.socket,r=Object.create(gs);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 Tl(t){return{req:ys(t)}}});var vs=I((rm,xs)=>{"use strict";xs.exports={mapHttpResponse:$l,resSerializer:_s};var Pr=Symbol("pino-raw-res-ref"),Ss=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Pr]},set:function(t){this[Pr]=t}}});Object.defineProperty(Ss,Pr,{writable:!0,value:{}});function _s(t){let e=Object.create(Ss);return e.statusCode=t.headersSent?t.statusCode:null,e.headers=t.getHeaders?t.getHeaders():t._headers,e.raw=t,e}function $l(t){return{res:_s(t)}}});var Mr=I((nm,ks)=>{"use strict";var Fr=ps(),Al=ms(),Tt=bs(),$t=vs();ks.exports={err:Fr,errWithCause:Al,mapHttpRequest:Tt.mapHttpRequest,mapHttpResponse:$t.mapHttpResponse,req:Tt.reqSerializer,res:$t.resSerializer,wrapErrorSerializer:function(e){return e===Fr?e:function(n){return e(Fr(n))}},wrapRequestSerializer:function(e){return e===Tt.reqSerializer?e:function(n){return e(Tt.reqSerializer(n))}},wrapResponseSerializer:function(e){return e===$t.resSerializer?e:function(n){return e($t.resSerializer(n))}}}});var Dr=I((sm,Cs)=>{"use strict";function El(t,e){return e}Cs.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=El;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 Rs=I((im,Os)=>{"use strict";function Lr(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]=Lr(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]=Lr(t[r]));return e}return t}function Ts(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 $s(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 As(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 At=Symbol("PATH_NOT_FOUND");function Ol(t,e){let r=t;for(let n of e){if(r==null||typeof r!="object"||r===null||!(n in r))return At;r=r[n]}return r}function Rl(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 Il(t,e,r,n=!1){for(let s of e){let i=Ts(s);if(i.includes("*"))Es(t,i,r,s,n);else if(n)As(t,i);else{let o=Ol(t,i);if(o===At)continue;let a=typeof r=="function"?r(o,i):r;$s(t,i,a)}}}function Es(t,e,r,n,s=!1){let i=e.indexOf("*");if(i===e.length-1){let o=e.slice(0,-1),a=t;for(let l of o){if(a==null||typeof a!="object"||a===null)return;a=a[l]}if(Array.isArray(a))if(s)for(let l=0;l<a.length;l++)a[l]=void 0;else for(let l=0;l<a.length;l++){let f=[...o,l.toString()],u=typeof r=="function"?r(a[l],f):r;a[l]=u}else if(typeof a=="object"&&a!==null)if(s){let l=[];for(let f in a)Object.prototype.hasOwnProperty.call(a,f)&&l.push(f);for(let f of l)delete a[f]}else for(let l in a){let f=[...o,l],u=typeof r=="function"?r(a[l],f):r;a[l]=u}}else Pl(t,e,r,i,n,s)}function Pl(t,e,r,n,s,i=!1){let o=e.slice(0,n),a=e.slice(n+1),l=[];function f(u,d){if(d===o.length){if(Array.isArray(u))for(let h=0;h<u.length;h++)l[d]=h.toString(),f(u[h],d+1);else if(typeof u=="object"&&u!==null)for(let h in u)l[d]=h,f(u[h],d+1)}else if(d<o.length){let h=o[d];u&&typeof u=="object"&&u!==null&&h in u&&(l[d]=h,f(u[h],d+1))}else if(a.includes("*"))Es(u,a,typeof r=="function"?(p,c)=>{let m=[...l.slice(0,d),...c];return r(p,m)}:r,s,i);else if(i)As(u,a);else{let h=typeof r=="function"?r(Rl(u,a),[...l.slice(0,d),...a]):r;$s(u,a,h)}}if(o.length===0)f(t,0);else{let u=t;for(let d=0;d<o.length;d++){let h=o[d];if(u==null||typeof u!="object"||u===null)return;u=u[h],l[d]=h}u!=null&&f(u,o.length)}}function Fl(t){if(t.length===0)return null;let e=new Map;for(let r of t){let n=Ts(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 Ml(t,e){if(!e)return t;function r(n,s,i=0){if(!s||s.size===0||n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(Array.isArray(n)){let a=[];for(let l=0;l<n.length;l++){let f=l.toString();s.has(f)||s.has("*")?a[l]=r(n[l],s.get(f)||s.get("*")):a[l]=n[l]}return a}let o=Object.create(Object.getPrototypeOf(n));for(let a in n)Object.prototype.hasOwnProperty.call(n,a)&&(s.has(a)||s.has("*")?o[a]=r(n[a],s.get(a)||s.get("*")):o[a]=n[a]);return o}return r(t,e)}function Dl(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 Ll(t){if(!Array.isArray(t))throw new TypeError("paths must be an array");for(let e of t)Dl(e)}function jl(t={}){let{paths:e=[],censor:r="[REDACTED]",serialize:n=JSON.stringify,strict:s=!0,remove:i=!1}=t;Ll(e);let o=Fl(e);return function(l){if(s&&(l===null||typeof l!="object")&&(l==null||typeof l!="object"))return n?n(l):l;let f=Ml(l,o),u=l,d=r;return typeof r=="function"&&(d=r),Il(f,e,d,i),n===!1?(f.restore=function(){return Lr(u)},f):typeof n=="function"?n(f):JSON.stringify(f)}}Os.exports=jl});var Ne=I((om,Is)=>{"use strict";var Nl=Symbol("pino.setLevel"),ql=Symbol("pino.getLevel"),Ul=Symbol("pino.levelVal"),Bl=Symbol("pino.levelComp"),Hl=Symbol("pino.useLevelLabels"),Wl=Symbol("pino.useOnlyCustomLevels"),Vl=Symbol("pino.mixin"),zl=Symbol("pino.lsCache"),Kl=Symbol("pino.chindings"),Gl=Symbol("pino.asJson"),Jl=Symbol("pino.write"),Xl=Symbol("pino.redactFmt"),Yl=Symbol("pino.time"),Zl=Symbol("pino.timeSliceIndex"),Ql=Symbol("pino.stream"),ec=Symbol("pino.stringify"),tc=Symbol("pino.stringifySafe"),rc=Symbol("pino.stringifiers"),nc=Symbol("pino.end"),sc=Symbol("pino.formatOpts"),ic=Symbol("pino.messageKey"),oc=Symbol("pino.errorKey"),ac=Symbol("pino.nestedKey"),lc=Symbol("pino.nestedKeyStr"),cc=Symbol("pino.mixinMergeStrategy"),uc=Symbol("pino.msgPrefix"),fc=Symbol("pino.wildcardFirst"),dc=Symbol.for("pino.serializers"),pc=Symbol.for("pino.formatters"),hc=Symbol.for("pino.hooks"),mc=Symbol.for("pino.metadata");Is.exports={setLevelSym:Nl,getLevelSym:ql,levelValSym:Ul,levelCompSym:Bl,useLevelLabelsSym:Hl,mixinSym:Vl,lsCacheSym:zl,chindingsSym:Kl,asJsonSym:Gl,writeSym:Jl,serializersSym:dc,redactFmtSym:Xl,timeSym:Yl,timeSliceIndexSym:Zl,streamSym:Ql,stringifySym:ec,stringifySafeSym:tc,stringifiersSym:rc,endSym:nc,formatOptsSym:sc,messageKeySym:ic,errorKeySym:oc,nestedKeySym:ac,wildcardFirstSym:fc,needsMetadataGsym:mc,useOnlyCustomLevelsSym:Wl,formattersSym:pc,hooksSym:hc,nestedKeyStrSym:lc,mixinMergeStrategySym:cc,msgPrefixSym:uc}});var Nr=I((am,Ds)=>{"use strict";var Ps=Rs(),{redactFmtSym:gc,wildcardFirstSym:Et}=Ne(),jr=/[^.[\]]+|\[([^[\]]*?)\]/g,Fs="[Redacted]",Ms=!1;function yc(t,e){let{paths:r,censor:n,remove:s}=wc(t),i=r.reduce((l,f)=>{jr.lastIndex=0;let u=jr.exec(f),d=jr.exec(f),h=u[1]!==void 0?u[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):u[0];if(h==="*"&&(h=Et),d===null)return l[h]=null,l;if(l[h]===null)return l;let{index:p}=d,c=`${f.substr(p,f.length-1)}`;return l[h]=l[h]||[],h!==Et&&l[h].length===0&&l[h].push(...l[Et]||[]),h===Et&&Object.keys(l).forEach(function(m){l[m]&&l[m].push(c)}),l[h].push(c),l},{}),o={[gc]:Ps({paths:r,censor:n,serialize:e,strict:Ms,remove:s})},a=(...l)=>e(typeof n=="function"?n(...l):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((l,f)=>{if(i[f]===null)l[f]=u=>a(u,[f]);else{let u=typeof n=="function"?(d,h)=>n(d,[f,...h]):n;l[f]=Ps({paths:i[f],censor:u,serialize:e,strict:Ms,remove:s})}return l},o)}function wc(t){if(Array.isArray(t))return t={paths:t,censor:Fs},t;let{paths:e,censor:r=Fs,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}}Ds.exports=yc});var Ns=I((lm,js)=>{"use strict";var bc=()=>"",Sc=()=>`,"time":${Date.now()}`,_c=()=>`,"time":${Math.round(Date.now()/1e3)}`,xc=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,vc=1000000n,Ls=1000000000n,kc=BigInt(Date.now())*vc,Cc=process.hrtime.bigint(),Tc=()=>{let t=process.hrtime.bigint()-Cc,e=kc+t,r=e/Ls,n=e%Ls,s=Number(r*1000n+n/1000000n),i=new Date(s),o=i.getUTCFullYear(),a=(i.getUTCMonth()+1).toString().padStart(2,"0"),l=i.getUTCDate().toString().padStart(2,"0"),f=i.getUTCHours().toString().padStart(2,"0"),u=i.getUTCMinutes().toString().padStart(2,"0"),d=i.getUTCSeconds().toString().padStart(2,"0");return`,"time":"${o}-${a}-${l}T${f}:${u}:${d}.${n.toString().padStart(9,"0")}Z"`};js.exports={nullTime:bc,epochTime:Sc,unixTime:_c,isoTime:xc,isoTimeNano:Tc}});var Us=I((cm,qs)=>{"use strict";function $c(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}qs.exports=Ac;function Ac(t,e,r){var n=r&&r.stringify||$c,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=n(t);for(var a=1;a<i;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var l=e.length;if(l===0)return t;for(var f="",u=1-s,d=-1,h=t&&t.length||0,p=0;p<h;){if(t.charCodeAt(p)===37&&p+1<h){switch(d=d>-1?d:0,t.charCodeAt(p+1)){case 100:case 102:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Number(e[u]),d=p+2,p++;break;case 105:if(u>=l||e[u]==null)break;d<p&&(f+=t.slice(d,p)),f+=Math.floor(Number(e[u])),d=p+2,p++;break;case 79:case 111:case 106:if(u>=l||e[u]===void 0)break;d<p&&(f+=t.slice(d,p));var c=typeof e[u];if(c==="string"){f+="'"+e[u]+"'",d=p+2,p++;break}if(c==="function"){f+=e[u].name||"<anonymous>",d=p+2,p++;break}f+=n(e[u]),d=p+2,p++;break;case 115:if(u>=l)break;d<p&&(f+=t.slice(d,p)),f+=String(e[u]),d=p+2,p++;break;case 37:d<p&&(f+=t.slice(d,p)),f+="%",d=p+2,p++,u--;break}++u}++p}return d===-1?t:(d<h&&(f+=t.slice(d)),f)}});var Ur=I((um,qr)=>{"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));qr.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(););};qr.exports=t}});var Js=I((fm,Gs)=>{"use strict";var L=require("fs"),Ec=require("events"),Oc=require("util").inherits,Bs=require("path"),Hr=Ur(),Rc=require("assert"),Ot=100,Rt=Buffer.allocUnsafe(0),Ic=16*1024,Hs="buffer",Ws="utf8",[Pc,Fc]=(process.versions.node||"0.0").split(".").map(Number),Mc=Pc>=22&&Fc>=7;function Vs(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&&L.mkdirSync(Bs.dirname(t),{recursive:!0});let i=L.openSync(t,n,s);r(null,i)}catch(i){throw r(i),i}else e.mkdir?L.mkdir(Bs.dirname(t),{recursive:!0},i=>{if(i)return r(i);L.open(t,n,s,r)}):L.open(t,n,s,r)}function te(t){if(!(this instanceof te))return new te(t);let{fd:e,dest:r,minLength:n,maxLength:s,maxWrite:i,periodicFlush:o,sync:a,append:l=!0,mkdir:f,retryEAGAIN:u,fsync:d,contentMode:h,mode:p}=t||{};e=e||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=s||0,this.maxWrite=i||Ic,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=a||!1,this.writable=!0,this._fsync=d||!1,this.append=l||!1,this.mode=p,this.retryEAGAIN=u||(()=>!0),this.mkdir=f||!1;let c,m;if(h===Hs)this._writingBuf=Rt,this.write=jc,this.flush=qc,this.flushSync=Bc,this._actualWrite=Wc,c=()=>L.writeSync(this.fd,this._writingBuf),m=()=>L.write(this.fd,this._writingBuf,this.release);else if(h===void 0||h===Ws)this._writingBuf="",this.write=Lc,this.flush=Nc,this.flushSync=Uc,this._actualWrite=Hc,c=()=>Buffer.isBuffer(this._writingBuf)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>Buffer.isBuffer(this._writingBuf)?L.write(this.fd,this._writingBuf,this.release):L.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Ws}" and "${Hs}", but passed ${h}`);if(typeof e=="number")this.fd=e,process.nextTick(()=>this.emit("ready"));else if(typeof e=="string")Vs(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=(y,w)=>{if(y){if((y.code==="EAGAIN"||y.code==="EBUSY")&&this.retryEAGAIN(y,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Hr(Ot),this.release(void 0,0)}catch(S){this.release(S)}else setTimeout(m,Ot);else this._writing=!1,this.emit("error",y);return}this.emit("write",w);let b=Br(this._writingBuf,this._len,w);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let S=c(),k=Br(this._writingBuf,this._len,S);this._len=k.len,this._writingBuf=k.writingBuf}while(this._writingBuf.length)}catch(S){this.release(S);return}}this._fsync&&L.fsyncSync(this.fd);let _=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):_>this.minLength?this._actualWrite():this._ending?_>0?this._actualWrite():(this._writing=!1,It(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Dc,this)):this.emit("drain"))},this.on("newListener",function(y){y==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Br(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 Dc(t){t.listenerCount("drain")>0&&(t._asyncDrainScheduled=!1,t.emit("drain"))}Oc(te,Ec);function zs(t,e){return t.length===0?Rt:t.length===1?t[0]:Buffer.concat(t,e)}function Lc(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 jc(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 Ks(t){this._flushPending=!0;let e=()=>{if(this._fsync)this._flushPending=!1,t();else try{L.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 Nc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function qc(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&&Ks.call(this,t),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}te.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&&L.close(e,r=>{if(r)return this.emit("error",r)})}),Vs(this.file,this)};te.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():It(this)))};function Uc(){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)?L.writeSync(this.fd,t):L.writeSync(this.fd,t,"utf8"),r=Br(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;Hr(Ot)}}try{L.fsyncSync(this.fd)}catch{}}function Bc(){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=Rt);let t=Rt;for(;this._bufs.length||t.length;){t.length<=0&&(t=zs(this._bufs[0],this._lens[0]));try{let e=L.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;Hr(Ot)}}}te.prototype.destroy=function(){this.destroyed||It(this)};function Hc(){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)?L.writeSync(this.fd,this._writingBuf):L.writeSync(this.fd,this._writingBuf,"utf8");t(null,e)}catch(e){t(e)}else L.write(this.fd,this._writingBuf,t)}function Wc(){let t=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:zs(this._bufs.shift(),this._lens.shift()),this.sync)try{let e=L.writeSync(this.fd,this._writingBuf);t(null,e)}catch(e){t(e)}else Mc&&(this._writingBuf=Buffer.from(this._writingBuf)),L.write(this.fd,this._writingBuf,t)}function It(t){if(t.fd===-1){t.once("ready",It.bind(null,t));return}t._periodicFlushTimer!==void 0&&clearInterval(t._periodicFlushTimer),t.destroyed=!0,t._bufs=[],t._lens=[],Rc(typeof t.fd=="number",`sonic.fd must be a number, got ${typeof t.fd}`);try{L.fsync(t.fd,e)}catch{}function e(){t.fd!==1&&t.fd!==2?L.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")}}te.SonicBoom=te;te.default=te;Gs.exports=te});var Wr=I((dm,ei)=>{"use strict";var re={exit:[],beforeExit:[]},Xs={exit:Kc,beforeExit:Gc},qe;function Vc(){qe===void 0&&(qe=new FinalizationRegistry(Jc))}function zc(t){re[t].length>0||process.on(t,Xs[t])}function Ys(t){re[t].length>0||(process.removeListener(t,Xs[t]),re.exit.length===0&&re.beforeExit.length===0&&(qe=void 0))}function Kc(){Zs("exit")}function Gc(){Zs("beforeExit")}function Zs(t){for(let e of re[t]){let r=e.deref(),n=e.fn;r!==void 0&&n(r,t)}re[t]=[]}function Jc(t){for(let e of["exit","beforeExit"]){let r=re[e].indexOf(t);re[e].splice(r,r+1),Ys(e)}}function Qs(t,e,r){if(e===void 0)throw new Error("the object can't be undefined");zc(t);let n=new WeakRef(e);n.fn=r,Vc(),qe.register(e,n),re[t].push(n)}function Xc(t,e){Qs("exit",t,e)}function Yc(t,e){Qs("beforeExit",t,e)}function Zc(t){if(qe!==void 0){qe.unregister(t);for(let e of["exit","beforeExit"])re[e]=re[e].filter(r=>{let n=r.deref();return n&&n!==t}),Ys(e)}}ei.exports={register:Xc,registerBeforeExit:Yc,unregister:Zc}});var ti=I((pm,Qc)=>{Qc.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 ni=I((hm,ri)=>{"use strict";function eu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{let a=Atomics.load(t,e);if(a===r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,a,l);f.async?f.value.then(o):setImmediate(o)};o()}function tu(t,e,r,n,s){let i=n===1/0?1/0:Date.now()+n,o=()=>{if(Atomics.load(t,e)!==r){s(null,"ok");return}if(i!==1/0&&Date.now()>i){s(null,"timed-out");return}let l=i===1/0?1e4:Math.min(1e4,Math.max(1,i-Date.now())),f=Atomics.waitAsync(t,e,r,l);f.async?f.value.then(u=>{if(u==="ok"){s(null,"ok");return}o()}):setImmediate(o)};o()}ri.exports={wait:eu,waitDiff:tu}});var ii=I((mm,si)=>{"use strict";si.exports={WRITE_INDEX:4,READ_INDEX:8,SEQ_INDEX:2}});var yi=I((gm,gi)=>{"use strict";var{version:ru}=ti(),{EventEmitter:nu}=require("events"),{Worker:su}=require("worker_threads"),{join:iu}=require("path"),{pathToFileURL:ou}=require("url"),{wait:au}=ni(),{WRITE_INDEX:le,READ_INDEX:xe,SEQ_INDEX:Vr}=ii(),lu=require("buffer"),cu=require("assert"),g=Symbol("kImpl"),uu=lu.constants.MAX_STRING_LENGTH;function oi(){}function Jr(t,e){Atomics.add(t[g].state,Vr,1),e(),Atomics.add(t[g].state,Vr,1),Atomics.notify(t[g].state,Vr)}function ai(t){Jr(t,()=>{Atomics.store(t[g].state,xe,0),Atomics.store(t[g].state,le,0)})}var at=class{constructor(e){this._value=e}deref(){return this._value}},Pt=class{register(){}unregister(){}},fu=process.env.NODE_V8_COVERAGE?Pt:global.FinalizationRegistry||Pt,du=process.env.NODE_V8_COVERAGE?at:global.WeakRef||at,li=new fu(t=>{t.exited||t.terminate()});function pu(t,e){let{filename:r,workerData:n}=e,i=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||iu(__dirname,"lib","worker.js"),o=new su(i,{...e.workerOpts,name:e.workerOpts?.name||"thread-stream",trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:ou(r).href,dataBuf:t[g].dataBuf,stateBuf:t[g].stateBuf,workerData:{$context:{threadStreamVersion:ru},...n}}});return o.stream=new at(t),o.on("message",hu),o.on("exit",fi),li.register(t,o),o}function ci(t){cu(!t[g].sync),t[g].needDrain&&(t[g].needDrain=!1,t.emit("drain"))}function ui(t){for(;;){let e=Atomics.load(t[g].state,le),r=t[g].data.length-e;if(r>0){if(t[g].bufLen===0){t[g].flushing=!1,t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t);return}hi(t,r,oi);continue}if(r===0){if(e===0&&t[g].bufLen===0)return;Ft(t,()=>{t.destroyed||(ai(t),ui(t))});return}X(t,new Error("overwritten"));return}}function hu(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 du(e),Ft(e,()=>{e[g].ready=!0,e.emit("ready")});break;case"ERROR":X(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"){X(e,new Error("this should not happen: "+t.code));break}let r=e[g].flushCallbacks.get(t.id);r&&(e[g].flushCallbacks.delete(t.id),process.nextTick(r));break}case"WARNING":process.emitWarning(t.err);break;default:X(e,new Error("this should not happen: "+t.code))}}function fi(t){let e=this.stream.deref();e!==void 0&&(li.unregister(e),e.worker.exited=!0,e.worker.off("exit",fi),X(e,t!==0?new Error("the worker thread exited"):null))}var Kr=class extends nu{constructor(e={}){if(super(),e.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[g]={},this[g].stateBuf=new SharedArrayBuffer(128),this[g].state=new Int32Array(this[g].stateBuf),this[g].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[g].data=Buffer.from(this[g].dataBuf),this[g].sync=e.sync||!1,this[g].ending=!1,this[g].ended=!1,this[g].needDrain=!1,this[g].destroyed=!1,this[g].flushing=!1,this[g].ready=!1,this[g].finished=!1,this[g].errored=null,this[g].closed=!1,this[g].buf=[],this[g].bufHead=0,this[g].bufLen=0,this[g].flushCallbacks=new Map,this[g].nextFlushId=0,this.worker=pu(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[g].destroyed)return Gr(this,new Error("the worker has exited")),!1;if(this[g].ending)return Gr(this,new Error("the worker is ending")),!1;if(this[g].flushing&&this[g].bufLen+r.length>=uu)try{zr(this),this[g].flushing=!0}catch(n){return X(this,n),!1}if(this[g].buf.push(r),this[g].bufLen+=r.length,this[g].sync)try{return zr(this),!0}catch(n){return X(this,n),!1}return this[g].flushing||(this[g].flushing=!0,setImmediate(ui,this)),this[g].needDrain=this[g].data.length-this[g].bufLen-Atomics.load(this[g].state,le)<=0,!this[g].needDrain}end(){this[g].destroyed||(this[g].ending=!0,Xr(this))}flush(e){e=typeof e=="function"?e:oi,di(this,r=>{if(r){process.nextTick(e,r);return}pi(this,e)})}flushSync(){this[g].destroyed||(zr(this),mi(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[g].ready}get destroyed(){return this[g].destroyed}get closed(){return this[g].closed}get writable(){return!this[g].destroyed&&!this[g].ending}get writableEnded(){return this[g].ending}get writableFinished(){return this[g].finished}get writableNeedDrain(){return this[g].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[g].errored}};function di(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].sync&&(t[g].flushing||t[g].bufLen>0)){setImmediate(di,t,e);return}Ft(t,e)}function Ft(t,e){let r=Atomics.load(t[g].state,le);au(t[g].state,xe,r,1/0,(n,s)=>{if(n){X(t,n),e(n);return}if(s!=="ok"){Ft(t,e);return}e()})}function pi(t,e){if(t[g].destroyed){process.nextTick(e,new Error("the worker has exited"));return}if(!t[g].ready){let n=()=>{i(),pi(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[g].nextFlushId;t[g].flushCallbacks.set(r,e);try{t.worker.postMessage({code:"FLUSH",context:"thread-stream",id:r})}catch(n){t[g].flushCallbacks.delete(r),X(t,n),process.nextTick(e,n)}}function mu(t,e){let r=t[g].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 Gr(t,e){setImmediate(()=>{t.emit("error",e)})}function X(t,e){t[g].destroyed||(t[g].destroyed=!0,mu(t,e),e&&(t[g].errored=e,Gr(t,e)),t.worker.exited?setImmediate(()=>{t[g].closed=!0,t.emit("close")}):t.worker.terminate().catch(()=>{}).then(()=>{t[g].closed=!0,t.emit("close")}))}function hi(t,e,r){let s=Atomics.load(t[g].state,le),i=e;for(;i>0&&t[g].bufLen!==0;){let o=t[g].bufHead,a=t[g].buf[o];if(a.length<=i){a.copy(t[g].data,s),s+=a.length,i-=a.length,t[g].bufLen-=a.length,t[g].bufHead=o+1,t[g].bufHead===t[g].buf.length?(t[g].buf.length=0,t[g].bufHead=0):t[g].bufHead>=1024&&t[g].bufHead*2>=t[g].buf.length&&(t[g].buf.splice(0,t[g].bufHead),t[g].bufHead=0);continue}a.copy(t[g].data,s,0,i),t[g].buf[o]=a.subarray(i),t[g].bufLen-=i,s+=i,i=0}return Jr(t,()=>{Atomics.store(t[g].state,le,s)}),r(),!0}function Xr(t){if(!(t[g].ended||!t[g].ending||t[g].flushing)){t[g].ended=!0;try{t.flushSync();let e=Atomics.load(t[g].state,xe);Jr(t,()=>{Atomics.store(t[g].state,le,-1)});let r=0;for(;e!==-1;){if(Atomics.wait(t[g].state,xe,e,1e3),e=Atomics.load(t[g].state,xe),e===-2){X(t,new Error("end() failed"));return}if(++r===10){X(t,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{t[g].finished=!0,t.emit("finish")})}catch(e){X(t,e)}}}function zr(t){let e=()=>{t[g].ending?Xr(t):t[g].needDrain&&process.nextTick(ci,t)};for(t[g].flushing=!1;t[g].bufLen!==0;){let r=Atomics.load(t[g].state,le),n=t[g].data.length-r;if(n===0){mi(t),ai(t);continue}else if(n<0)throw new Error("overwritten");hi(t,n,e)}}function mi(t){if(t[g].flushing)throw new Error("unable to flush while flushing");let e=Atomics.load(t[g].state,le),r=0;for(;;){let n=Atomics.load(t[g].state,xe);if(n===-2)throw Error("_flushSync failed");if(n!==e)Atomics.wait(t[g].state,xe,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}gi.exports=Kr});var Qr=I((ym,Si)=>{"use strict";var{createRequire:gu}=require("module"),{existsSync:yu}=require("node:fs"),wu=Dr(),{join:Yr,isAbsolute:bi,sep:bu}=require("node:path"),{fileURLToPath:Su}=require("node:url"),_u=Ur(),Zr=Wr(),xu=yi();function vu(t){Zr.register(t,Au),Zr.registerBeforeExit(t,Eu),t.on("close",function(){Zr.unregister(t)})}function ku(){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 Cu(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&&wi(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(wi(o)){n=!0;continue}}r.push(i)}return n?r.join(" "):t}function wi(t){let e=Tu(t);if(!e)return!1;let r=e;if(r.startsWith("file://"))try{r=Su(r)}catch{return!1}return bi(r)&&!yu(r)}function Tu(t){let e=t[0],r=t[t.length-1];return e==='"'&&r==='"'||e==="'"&&r==="'"?t.slice(1,-1):t}function $u(t,e,r,n,s){if(!r.execArgv&&ku()&&require.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let l=Cu(process.env.NODE_OPTIONS);l!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:l}})}r={...r,name:s};let i=new xu({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&&vu(i)}function a(){i.closed||(i.flushSync(),_u(100),i.end())}return i}function Au(t){t.ref(),t.flushSync(),t.end(),t.once("close",function(){t.unref()})}function Eu(t){t.flushSync()}function Ou(t){let{pipeline:e,targets:r,levels:n,dedupe:s,worker:i={},caller:o=wu(),sync:a=!1}=t,l={...t.options},f=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"]||Yr(__dirname,"worker.js"),l.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),l.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(m=>({...m,level:c.level,target:p(m.target)})))):e&&(d=u["pino-worker"]||Yr(__dirname,"worker.js"),l.pipelines=[e.map(c=>({...c,target:p(c.target)}))]),n&&(l.levels=n),s&&(l.dedupe=s),l.pinoWillSendConfig=!0;let h=r||e?"pino.transport":d;return $u(p(d),l,i,a,h);function p(c){if(c=u[c]||c,bi(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return Yr(__dirname,"..","file.js");let m;for(let y of f)try{let w=y==="node:repl"?process.cwd()+bu:y;m=gu(w).resolve(c);break}catch{continue}if(!m)throw new Error(`unable to determine transport target for "${c}"`);return m}}Si.exports=Ou});var Lt=I((wm,Pi)=>{"use strict";var Ru=require("node:diagnostics_channel"),_i=Us(),{mapHttpRequest:Iu,mapHttpResponse:Pu}=Mr(),tn=Js(),xi=Wr(),{lsCacheSym:Fu,chindingsSym:$i,writeSym:vi,serializersSym:Ai,formatOptsSym:ki,endSym:Mu,stringifiersSym:Ei,stringifySym:Oi,stringifySafeSym:rn,wildcardFirstSym:Ri,nestedKeySym:Du,formattersSym:Ii,messageKeySym:Lu,errorKeySym:ju,nestedKeyStrSym:Nu,msgPrefixSym:Mt}=Ne(),{isMainThread:qu}=require("worker_threads"),Uu=Qr(),[Bu]=process.versions.node.split(".").map(t=>Number(t)),Ci=Ru.tracingChannel("pino_asJson"),en=Bu>=25?t=>JSON.stringify(t):Wu;function Ue(){}function Hu(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=Iu(n):typeof n.setHeader=="function"&&(n=Pu(n)));let o;i===null&&s.length===0?o=[null]:(i=s.shift(),o=s),typeof this[Mt]=="string"&&i!==void 0&&i!==null&&(i=this[Mt]+i),this[vi](n,_i(i,o,this[ki]),t)}else{let i=n===void 0?s.shift():n;typeof this[Mt]=="string"&&i!==void 0&&i!==null&&(i=this[Mt]+i),this[vi](null,_i(i,s,this[ki]),t)}}}function Wu(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 Vu(t,e,r,n){if(Ci.hasSubscribers===!1)return Ti.call(this,t,e,r,n);let s={instance:this,arguments};return Ci.traceSync(Ti,s,this,t,e,r,n)}function Ti(t,e,r,n){let s=this[Oi],i=this[rn],o=this[Ei],a=this[Mu],l=this[$i],f=this[Ai],u=this[Ii],d=this[Lu],h=this[ju],p=this[Fu][r]+n;p=p+l;let c;u.log&&(t=u.log(t));let m=o[Ri],y="";for(let b in t)if(c=t[b],Object.prototype.hasOwnProperty.call(t,b)&&c!==void 0){f[b]?c=f[b](c):b===h&&f.err&&(c=f.err(c));let _=o[b]||m;switch(typeof c){case"undefined":case"function":continue;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":_&&(c=_(c));break;case"string":c=(_||en)(c);break;default:c=(_||s)(c,i)}if(c===void 0)continue;let S=en(b);y+=","+S+":"+c}let w="";if(e!==void 0){c=f[d]?f[d](e):e;let b=o[d]||m;switch(typeof c){case"function":break;case"number":Number.isFinite(c)===!1&&(c=null);case"boolean":b&&(c=b(c)),w=',"'+d+'":'+c;break;case"string":c=(b||en)(c),w=',"'+d+'":'+c;break;default:c=(b||s)(c,i),w=',"'+d+'":'+c}}return this[Du]&&y?p+this[Nu]+y.slice(1)+"}"+w+a:p+y+w+a}function zu(t,e){let r,n=t[$i],s=t[Oi],i=t[rn],o=t[Ei],a=o[Ri],l=t[Ai],f=t[Ii].bindings;e=f(e);for(let u in e)if(r=e[u],((u.length<5||u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels")&&e.hasOwnProperty(u)&&r!==void 0)===!0){if(r=l[u]?l[u](r):r,r=(o[u]||a||s)(r,i),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Ku(t){return t.write!==t.constructor.prototype.write}function Dt(t){let e=new tn(t);return e.on("error",r),!t.sync&&qu&&(xi.register(e,Gu),e.on("close",function(){xi.unregister(e)})),e;function r(n){if(n.code==="EPIPE"){e.write=Ue,e.end=Ue,e.flushSync=Ue,e.destroy=Ue;return}e.removeListener("error",r),e.emit("error",n)}}function Gu(t,e){t.destroyed||(e==="beforeExit"?(t.flush(),t.on("drain",function(){t.end()})):t.flushSync())}function Ju(t){return function(r,n,s={},i){if(typeof s=="string")i=Dt({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=Dt({dest:i})}else if(s instanceof tn||s.writable||s._writableState)i=s,s={};else if(s.transport){if(s.transport instanceof tn||s.transport.writable||s.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(s.transport.targets&&s.transport.targets.length&&s.formatters&&typeof s.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let l;s.customLevels&&(l=s.useOnlyCustomLevels?s.customLevels:Object.assign({},s.levels,s.customLevels)),i=Uu({caller:n,...s.transport,levels:l})}if(s=Object.assign({},t,s),s.serializers=Object.assign({},t.serializers,s.serializers),s.formatters=Object.assign({},t.formatters,s.formatters),s.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:o,onChild:a}=s;return o===!1&&(s.level="silent"),a||(s.onChild=Ue),i||(Ku(process.stdout)?i=process.stdout:i=Dt({fd:process.stdout.fd||1})),{opts:s,stream:i}}}function Xu(t,e){try{return JSON.stringify(t)}catch{try{return(e||this[rn])(t)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Yu(t,e,r){return{level:t,bindings:e,log:r}}function Zu(t){let e=Number(t);return typeof t=="string"&&Number.isFinite(e)?e:t===void 0?1:t}Pi.exports={noop:Ue,buildSafeSonicBoom:Dt,asChindings:zu,asJson:Vu,genLog:Hu,createArgsNormalizer:Ju,stringify:Xu,buildFormatters:Yu,normalizeDestFileDescriptor:Zu}});var jt=I((bm,Fi)=>{var Qu={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},ef={ASC:"ASC",DESC:"DESC"};Fi.exports={DEFAULT_LEVELS:Qu,SORTING_ORDER:ef}});var on=I((Sm,ji)=>{"use strict";var{lsCacheSym:tf,levelValSym:nn,useOnlyCustomLevelsSym:rf,streamSym:nf,formattersSym:sf,hooksSym:of,levelCompSym:Mi}=Ne(),{noop:af,genLog:ve}=Lt(),{DEFAULT_LEVELS:ie,SORTING_ORDER:Di}=jt(),Li={fatal:t=>{let e=ve(ie.fatal,t);return function(...r){let n=this[nf];if(e.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:t=>ve(ie.error,t),warn:t=>ve(ie.warn,t),info:t=>ve(ie.info,t),debug:t=>ve(ie.debug,t),trace:t=>ve(ie.trace,t)},sn=Object.keys(ie).reduce((t,e)=>(t[ie[e]]=e,t),{}),lf=Object.keys(sn).reduce((t,e)=>(t[e]='{"level":'+Number(e),t),{});function cf(t){let e=t[sf].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[tf]=n,t}function uf(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 ff(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[nn],s=this[nn]=r[t],i=this[rf],o=this[Mi],a=this[of].logMethod;for(let l in r){if(o(r[l],s)===!1){this[l]=af;continue}this[l]=uf(l,i)?Li[l](a):ve(r[l],a)}this.emit("level-change",t,s,e[n],n,this)}function df(t){let{levels:e,levelVal:r}=this;return e&&e.labels?e.labels[r]:""}function pf(t){let{values:e}=this.levels,r=e[t];return r!==void 0&&this[Mi](r,this[nn])}function hf(t,e,r){return t===Di.DESC?e<=r:e>=r}function mf(t){return typeof t=="string"?hf.bind(null,t):t}function gf(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:sn,r),s=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),e?null:ie,t);return{labels:n,values:s}}function yf(t,e,r){if(typeof t=="number"){if(![].concat(Object.keys(e||{}).map(i=>e[i]),r?[]:Object.keys(sn).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:ie,e);if(!(t in n))throw Error(`default level:${t} must be included in custom levels`)}function wf(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 bf(t){if(typeof t!="function"&&!(typeof t=="string"&&Object.values(Di).includes(t)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}ji.exports={initialLsCache:lf,genLsCache:cf,levelMethods:Li,getLevel:df,setLevel:ff,isLevelEnabled:pf,mappings:gf,assertNoLevelCollisions:wf,assertDefaultLevelFound:yf,genLevelComparison:mf,assertLevelComparison:bf}});var an=I((_m,Ni)=>{"use strict";Ni.exports={version:"10.3.1"}});var Ki=I((vm,zi)=>{"use strict";var{EventEmitter:Sf}=require("node:events"),{lsCacheSym:_f,levelValSym:xf,setLevelSym:cn,getLevelSym:qi,chindingsSym:qt,mixinSym:vf,asJsonSym:Bi,writeSym:kf,mixinMergeStrategySym:Cf,timeSym:Tf,timeSliceIndexSym:$f,streamSym:Hi,serializersSym:ke,formattersSym:lt,errorKeySym:Af,messageKeySym:Ef,useOnlyCustomLevelsSym:Of,needsMetadataGsym:Rf,redactFmtSym:If,stringifySym:Pf,formatOptsSym:Ff,stringifiersSym:Mf,msgPrefixSym:un,hooksSym:Df}=Ne(),{getLevel:Lf,setLevel:jf,isLevelEnabled:Nf,mappings:qf,initialLsCache:Uf,genLsCache:Bf,assertNoLevelCollisions:Hf}=on(),{asChindings:fn,asJson:Wf,buildFormatters:ln,stringify:Ui,noop:Wi}=Lt(),{version:Vf}=an(),zf=Nr(),Kf=class{},Vi={constructor:Kf,child:Gf,bindings:Jf,setBindings:Xf,flush:Qf,isLevelEnabled:Nf,version:Vf,get level(){return this[qi]()},set level(t){this[cn](t)},get levelVal(){return this[xf]},set levelVal(t){throw Error("levelVal is read-only")},get msgPrefix(){return this[un]},get[Symbol.toStringTag](){return"Pino"},[_f]:Uf,[kf]:Zf,[Bi]:Wf,[qi]:Lf,[cn]:jf};Object.setPrototypeOf(Vi,Sf.prototype);zi.exports=function(){return Object.create(Vi)};var Nt=t=>t;function Gf(t,e){if(!t)throw Error("missing bindings for child Pino");let r=this[ke],n=this[lt],s=Object.create(this);if(e==null)return s[lt].bindings!==Nt&&(s[lt]=ln(n.level,Nt,n.log)),s[qt]=fn(s,t),this.onChild!==Wi&&this.onChild(s),s;if(e.hasOwnProperty("serializers")===!0){s[ke]=Object.create(null);for(let f in r)s[ke][f]=r[f];let a=Object.getOwnPropertySymbols(r);for(var i=0;i<a.length;i++){let f=a[i];s[ke][f]=r[f]}for(let f in e.serializers)s[ke][f]=e.serializers[f];let l=Object.getOwnPropertySymbols(e.serializers);for(var o=0;o<l.length;o++){let f=l[o];s[ke][f]=e.serializers[f]}}else s[ke]=r;if(e.hasOwnProperty("formatters")){let{level:a,bindings:l,log:f}=e.formatters;s[lt]=ln(a||n.level,l||Nt,f||n.log)}else s[lt]=ln(n.level,Nt,n.log);if(e.hasOwnProperty("customLevels")===!0&&(Hf(this.levels,e.customLevels),s.levels=qf(e.customLevels,s[Of]),Bf(s)),typeof e.redact=="object"&&e.redact!==null||Array.isArray(e.redact)){s.redact=e.redact;let a=zf(s.redact,Ui),l={stringify:a[If]};s[Pf]=Ui,s[Mf]=a,s[Ff]=l}if(typeof e.msgPrefix=="string"&&(s[un]=(this[un]||"")+e.msgPrefix),s[qt]=fn(s,t),e.level!==void 0&&e.level!==this.level||e.hasOwnProperty("customLevels")){let a=e.level||this.level;s[cn](a)}return this.onChild(s),s}function Jf(){let e=`{${this[qt].substr(1)}}`,r=JSON.parse(e);return delete r.pid,delete r.hostname,r}function Xf(t){let e=fn(this,t);this[qt]=e}function Yf(t,e){return Object.assign(e,t)}function Zf(t,e,r){let n=this[Tf](),s=this[vf],i=this[Af],o=this[Ef],a=this[Cf]||Yf,l,f=this[Df].streamWrite;t==null?l={}:t instanceof Error?(l={[i]:t},e===void 0&&(e=t.message)):(l=t,e===void 0&&t[o]===void 0&&t[i]&&(e=t[i].message)),s&&(l=a(l,s(l,r,this)));let u=this[Bi](l,e,r,n),d=this[Hi];d[Rf]===!0&&(d.lastLevel=r,d.lastObj=l,d.lastMsg=e,d.lastTime=n.slice(this[$f]),d.lastLogger=this),d.write(f?f(u):u)}function Qf(t){if(t!=null&&typeof t!="function")throw Error("callback must be a function");let e=this[Hi];typeof e.flush=="function"?e.flush(t||Wi):t&&t()}});var Yi=I((mn,Xi)=>{"use strict";var{hasOwnProperty:ct}=Object.prototype,Te=hn();Te.configure=hn;Te.stringify=Te;Te.default=Te;mn.stringify=Te;mn.configure=hn;Xi.exports=Te;var ed=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function me(t){return t.length<5e3&&!ed.test(t)?`"${t}"`:JSON.stringify(t)}function dn(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 td=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function pn(t){return td.call(t)!==void 0&&t.length!==0}function Gi(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 rd(t){if(ct.call(t,"circularValue")){let e=t.circularValue;if(typeof e=="string")return`"${e}"`;if(e==null)return e;if(e===Error||e===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}function nd(t){let e;if(ct.call(t,"deterministic")&&(e=t.deterministic,typeof e!="boolean"&&typeof e!="function"))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return e===void 0?!0:e}function sd(t,e){let r;if(ct.call(t,e)&&(r=t[e],typeof r!="boolean"))throw new TypeError(`The "${e}" argument must be of type boolean`);return r===void 0?!0:r}function Ji(t,e){let r;if(ct.call(t,e)){if(r=t[e],typeof r!="number")throw new TypeError(`The "${e}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${e}" argument must be an integer`);if(r<1)throw new RangeError(`The "${e}" argument must be >= 1`)}return r===void 0?1/0:r}function Ce(t){return t===1?"1 item":`${t} items`}function id(t){let e=new Set;for(let r of t)(typeof r=="string"||typeof r=="number")&&e.add(String(r));return e}function od(t){if(ct.call(t,"strict")){let e=t.strict;if(typeof e!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(e)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function hn(t){t={...t};let e=od(t);e&&(t.bigint===void 0&&(t.bigint=!1),"circularValue"in t||(t.circularValue=Error));let r=rd(t),n=sd(t,"bigint"),s=nd(t),i=typeof s=="function"?s:void 0,o=Ji(t,"maximumDepth"),a=Ji(t,"maximumBreadth");function l(p,c,m,y,w,b){let _=c[p];switch(typeof _=="object"&&_!==null&&typeof _.toJSON=="function"&&(_=_.toJSON(p)),_=y.call(c,p,_),typeof _){case"string":return me(_);case"object":{if(_===null)return"null";if(m.indexOf(_)!==-1)return r;let S="",k=",",R=b;if(Array.isArray(_)){if(_.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(_),w!==""&&(b+=w,S+=`
26
26
  ${b}`,k=`,
27
- ${b}`);let L=Math.min(_.length,a),H=0;for(;H<L-1;H++){let W=l(String(H),_,m,y,w,b);S+=W!==void 0?W:"null",S+=k}let U=l(String(H),_,m,y,w,b);if(S+=U!==void 0?U:"null",_.length-1>a){let W=_.length-a-1;S+=`${k}"... ${Ce(W)} not stringified"`}return w!==""&&(S+=`
28
- ${R}`),m.pop(),`[${S}]`}let T=Object.keys(_),O=T.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let $="",P="";w!==""&&(b+=w,k=`,
29
- ${b}`,$=" ");let N=Math.min(O,a);s&&!pn(_)&&(T=dn(T,i)),m.push(_);for(let L=0;L<N;L++){let H=T[L],U=l(H,_,m,y,w,b);U!==void 0&&(S+=`${P}${me(H)}:${$}${U}`,P=k)}if(O>a){let L=O-a;S+=`${P}"...":${$}"${Ce(L)} not stringified"`,P=k}return w!==""&&P.length>1&&(S=`
27
+ ${b}`);let D=Math.min(_.length,a),H=0;for(;H<D-1;H++){let W=l(String(H),_,m,y,w,b);S+=W!==void 0?W:"null",S+=k}let U=l(String(H),_,m,y,w,b);if(S+=U!==void 0?U:"null",_.length-1>a){let W=_.length-a-1;S+=`${k}"... ${Ce(W)} not stringified"`}return w!==""&&(S+=`
28
+ ${R}`),m.pop(),`[${S}]`}let $=Object.keys(_),O=$.length;if(O===0)return"{}";if(o<m.length+1)return'"[Object]"';let T="",P="";w!==""&&(b+=w,k=`,
29
+ ${b}`,T=" ");let N=Math.min(O,a);s&&!pn(_)&&($=dn($,i)),m.push(_);for(let D=0;D<N;D++){let H=$[D],U=l(H,_,m,y,w,b);U!==void 0&&(S+=`${P}${me(H)}:${T}${U}`,P=k)}if(O>a){let D=O-a;S+=`${P}"...":${T}"${Ce(D)} not stringified"`,P=k}return w!==""&&P.length>1&&(S=`
30
30
  ${b}${S}
31
31
  ${R}`),m.pop(),`{${S}}`}case"number":return isFinite(_)?String(_):e?e(_):"null";case"boolean":return _===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(_);default:return e?e(_):void 0}}function f(p,c,m,y,w,b){switch(typeof c=="object"&&c!==null&&typeof c.toJSON=="function"&&(c=c.toJSON(p)),typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(m.indexOf(c)!==-1)return r;let _=b,S="",k=",";if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w!==""&&(b+=w,S+=`
32
32
  ${b}`,k=`,
33
- ${b}`);let O=Math.min(c.length,a),$=0;for(;$<O-1;$++){let N=f(String($),c[$],m,y,w,b);S+=N!==void 0?N:"null",S+=k}let P=f(String($),c[$],m,y,w,b);if(S+=P!==void 0?P:"null",c.length-1>a){let N=c.length-a-1;S+=`${k}"... ${Ce(N)} not stringified"`}return w!==""&&(S+=`
33
+ ${b}`);let O=Math.min(c.length,a),T=0;for(;T<O-1;T++){let N=f(String(T),c[T],m,y,w,b);S+=N!==void 0?N:"null",S+=k}let P=f(String(T),c[T],m,y,w,b);if(S+=P!==void 0?P:"null",c.length-1>a){let N=c.length-a-1;S+=`${k}"... ${Ce(N)} not stringified"`}return w!==""&&(S+=`
34
34
  ${_}`),m.pop(),`[${S}]`}m.push(c);let R="";w!==""&&(b+=w,k=`,
35
- ${b}`,R=" ");let T="";for(let O of y){let $=f(O,c[O],m,y,w,b);$!==void 0&&(S+=`${T}${me(O)}:${R}${$}`,T=k)}return w!==""&&T.length>1&&(S=`
35
+ ${b}`,R=" ");let $="";for(let O of y){let T=f(O,c[O],m,y,w,b);T!==void 0&&(S+=`${$}${me(O)}:${R}${T}`,$=k)}return w!==""&&$.length>1&&(S=`
36
36
  ${b}${S}
37
- ${_}`),m.pop(),`{${S}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function u(p,c,m,y,w){switch(typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return u(p,c,m,y,w);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=w;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w+=y;let $=`
37
+ ${_}`),m.pop(),`{${S}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function u(p,c,m,y,w){switch(typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return u(p,c,m,y,w);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let b=w;if(Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c),w+=y;let T=`
38
38
  ${w}`,P=`,
39
- ${w}`,N=Math.min(c.length,a),L=0;for(;L<N-1;L++){let U=u(String(L),c[L],m,y,w);$+=U!==void 0?U:"null",$+=P}let H=u(String(L),c[L],m,y,w);if($+=H!==void 0?H:"null",c.length-1>a){let U=c.length-a-1;$+=`${P}"... ${Ce(U)} not stringified"`}return $+=`
40
- ${b}`,m.pop(),`[${$}]`}let _=Object.keys(c),S=_.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';w+=y;let k=`,
41
- ${w}`,R="",T="",O=Math.min(S,a);pn(c)&&(R+=Gi(c,k,a),_=_.slice(c.length),O-=c.length,T=k),s&&(_=dn(_,i)),m.push(c);for(let $=0;$<O;$++){let P=_[$],N=u(P,c[P],m,y,w);N!==void 0&&(R+=`${T}${me(P)}: ${N}`,T=k)}if(S>a){let $=S-a;R+=`${T}"...": "${Ce($)} not stringified"`,T=k}return T!==""&&(R=`
39
+ ${w}`,N=Math.min(c.length,a),D=0;for(;D<N-1;D++){let U=u(String(D),c[D],m,y,w);T+=U!==void 0?U:"null",T+=P}let H=u(String(D),c[D],m,y,w);if(T+=H!==void 0?H:"null",c.length-1>a){let U=c.length-a-1;T+=`${P}"... ${Ce(U)} not stringified"`}return T+=`
40
+ ${b}`,m.pop(),`[${T}]`}let _=Object.keys(c),S=_.length;if(S===0)return"{}";if(o<m.length+1)return'"[Object]"';w+=y;let k=`,
41
+ ${w}`,R="",$="",O=Math.min(S,a);pn(c)&&(R+=Gi(c,k,a),_=_.slice(c.length),O-=c.length,$=k),s&&(_=dn(_,i)),m.push(c);for(let T=0;T<O;T++){let P=_[T],N=u(P,c[P],m,y,w);N!==void 0&&(R+=`${$}${me(P)}: ${N}`,$=k)}if(S>a){let T=S-a;R+=`${$}"...": "${Ce(T)} not stringified"`,$=k}return $!==""&&(R=`
42
42
  ${w}${R}
43
- ${b}`),m.pop(),`{${R}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function d(p,c,m){switch(typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return d(p,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",w=c.length!==void 0;if(w&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let R=Math.min(c.length,a),T=0;for(;T<R-1;T++){let $=d(String(T),c[T],m);y+=$!==void 0?$:"null",y+=","}let O=d(String(T),c[T],m);if(y+=O!==void 0?O:"null",c.length-1>a){let $=c.length-a-1;y+=`,"... ${Ce($)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",k=Math.min(_,a);w&&pn(c)&&(y+=Gi(c,",",a),b=b.slice(c.length),k-=c.length,S=","),s&&(b=dn(b,i)),m.push(c);for(let R=0;R<k;R++){let T=b[R],O=d(T,c[T],m);O!==void 0&&(y+=`${S}${me(T)}:${O}`,S=",")}if(_>a){let R=_-a;y+=`${S}"...":"${Ce(R)} not stringified"`}return m.pop(),`{${y}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function h(p,c,m){if(arguments.length>1){let y="";if(typeof m=="number"?y=" ".repeat(Math.min(m,10)):typeof m=="string"&&(y=m.slice(0,10)),c!=null){if(typeof c=="function")return l("",{"":p},[],c,y,"");if(Array.isArray(c))return f("",p,[],id(c),y,"")}if(y.length!==0)return u("",p,[],y,"")}return d("",p,[])}return h}});var to=I((km,eo)=>{"use strict";var gn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Qi}=jt(),ad=Qi.info;function ld(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Qi);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:f,minLevel:0,lastId:0,streams:[],clone:u,[gn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let w=cd(c.length,e.dedupe);fd(w,c.length,e.dedupe);w=ud(w,e.dedupe))if(h=c[w],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[gn]){let{lastTime:b,lastMsg:_,lastObj:S,lastLogger:k}=this;y.lastLevel=p,y.lastTime=b,y.lastMsg=_,y.lastObj=S,y.lastLogger=k}y.write(d),e.dedupe&&(m=h.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return n;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof d.levelVal=="number"?y=d.levelVal:typeof d.level=="string"?y=m[d.level]:typeof d.level=="number"?y=d.level:y=ad;let w={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(w),c.sort(Zi),this.minLevel=c[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(c=>c.id===d);return p>=0&&(h.splice(p,1),h.sort(Zi),this.minLevel=h.length>0?h[0].level:-1),n}function f(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:u,emit:i,flushSync:o,[gn]:!0}}}function Zi(t,e){return t.level-e.level}function cd(t,e){return e?t-1:0}function ud(t,e){return e?t-1:t+1}function fd(t,e,r){return r?t>=0:t<e}eo.exports=ld});var go=I((Cm,Y)=>{"use strict";var dd=require("node:os"),co=Fr(),pd=Lr(),hd=Nr(),uo=Ns(),md=Ki(),fo=Ne(),{configure:gd}=Yi(),{assertDefaultLevelFound:yd,mappings:po,genLsCache:wd,genLevelComparison:bd,assertLevelComparison:Sd}=on(),{DEFAULT_LEVELS:ho,SORTING_ORDER:_d}=jt(),{createArgsNormalizer:xd,asChindings:vd,buildSafeSonicBoom:ro,buildFormatters:kd,stringify:yn,normalizeDestFileDescriptor:no,noop:Cd}=Dt(),{version:$d}=an(),{chindingsSym:so,redactFmtSym:Td,serializersSym:io,timeSym:Ad,timeSliceIndexSym:Ed,streamSym:Od,stringifySym:oo,stringifySafeSym:wn,stringifiersSym:ao,setLevelSym:Rd,endSym:Id,formatOptsSym:Pd,messageKeySym:Md,errorKeySym:Fd,nestedKeySym:Ld,mixinSym:Dd,levelCompSym:jd,useOnlyCustomLevelsSym:Nd,formattersSym:lo,hooksSym:qd,nestedKeyStrSym:Ud,mixinMergeStrategySym:Bd,msgPrefixSym:Hd}=fo,{epochTime:mo,nullTime:Wd}=uo,{pid:Vd}=process,zd=dd.hostname(),Kd=co.err,Gd={level:"info",levelComparison:_d.ASC,levels:ho,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Vd,hostname:zd},serializers:Object.assign(Object.create(null),{err:Kd}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:mo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Jd=xd(Gd),Xd=Object.assign(Object.create(null),co);function bn(...t){let e={},{opts:r,stream:n}=Jd(e,pd(),...t);r.level&&typeof r.level=="string"&&ho[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:f,nestedKey:u,base:d,name:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:b,formatters:_,hooks:S,depthLimit:k,edgeLimit:R,onChild:T,msgPrefix:O}=r,$=gd({maximumDepth:k,maximumBreadth:R}),P=kd(_.level,_.bindings,_.log),N=yn.bind({[wn]:$}),L=s?hd(s,N):{},H=s?{stringify:L[Td]}:{stringify:N},U="}"+(i?`\r
43
+ ${b}`),m.pop(),`{${R}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function d(p,c,m){switch(typeof c){case"string":return me(c);case"object":{if(c===null)return"null";if(typeof c.toJSON=="function"){if(c=c.toJSON(p),typeof c!="object")return d(p,c,m);if(c===null)return"null"}if(m.indexOf(c)!==-1)return r;let y="",w=c.length!==void 0;if(w&&Array.isArray(c)){if(c.length===0)return"[]";if(o<m.length+1)return'"[Array]"';m.push(c);let R=Math.min(c.length,a),$=0;for(;$<R-1;$++){let T=d(String($),c[$],m);y+=T!==void 0?T:"null",y+=","}let O=d(String($),c[$],m);if(y+=O!==void 0?O:"null",c.length-1>a){let T=c.length-a-1;y+=`,"... ${Ce(T)} not stringified"`}return m.pop(),`[${y}]`}let b=Object.keys(c),_=b.length;if(_===0)return"{}";if(o<m.length+1)return'"[Object]"';let S="",k=Math.min(_,a);w&&pn(c)&&(y+=Gi(c,",",a),b=b.slice(c.length),k-=c.length,S=","),s&&(b=dn(b,i)),m.push(c);for(let R=0;R<k;R++){let $=b[R],O=d($,c[$],m);O!==void 0&&(y+=`${S}${me($)}:${O}`,S=",")}if(_>a){let R=_-a;y+=`${S}"...":"${Ce(R)} not stringified"`}return m.pop(),`{${y}}`}case"number":return isFinite(c)?String(c):e?e(c):"null";case"boolean":return c===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(c);default:return e?e(c):void 0}}function h(p,c,m){if(arguments.length>1){let y="";if(typeof m=="number"?y=" ".repeat(Math.min(m,10)):typeof m=="string"&&(y=m.slice(0,10)),c!=null){if(typeof c=="function")return l("",{"":p},[],c,y,"");if(Array.isArray(c))return f("",p,[],id(c),y,"")}if(y.length!==0)return u("",p,[],y,"")}return d("",p,[])}return h}});var to=I((km,eo)=>{"use strict";var gn=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:Qi}=jt(),ad=Qi.info;function ld(t,e){t=t||[],e=e||{dedupe:!1};let r=Object.create(Qi);r.silent=1/0,e.levels&&typeof e.levels=="object"&&Object.keys(e.levels).forEach(d=>{r[d]=e.levels[d]});let n={write:s,add:a,remove:l,emit:i,flushSync:o,end:f,minLevel:0,lastId:0,streams:[],clone:u,[gn]:!0,streamLevels:r};return Array.isArray(t)?t.forEach(a,n):a.call(n,t),t=null,n;function s(d){let h,p=this.lastLevel,{streams:c}=this,m=0,y;for(let w=cd(c.length,e.dedupe);fd(w,c.length,e.dedupe);w=ud(w,e.dedupe))if(h=c[w],h.level<=p){if(m!==0&&m!==h.level)break;if(y=h.stream,y[gn]){let{lastTime:b,lastMsg:_,lastObj:S,lastLogger:k}=this;y.lastLevel=p,y.lastTime=b,y.lastMsg=_,y.lastObj=S,y.lastLogger=k}y.write(d),e.dedupe&&(m=h.level)}else if(!e.dedupe)break}function i(...d){for(let{stream:h}of this.streams)typeof h.emit=="function"&&h.emit(...d)}function o(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync()}function a(d){if(!d)return n;let h=typeof d.write=="function"||d.stream,p=d.write?d:d.stream;if(!h)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:c,streamLevels:m}=this,y;typeof d.levelVal=="number"?y=d.levelVal:typeof d.level=="string"?y=m[d.level]:typeof d.level=="number"?y=d.level:y=ad;let w={stream:p,level:y,levelVal:void 0,id:++n.lastId};return c.unshift(w),c.sort(Zi),this.minLevel=c[0].level,n}function l(d){let{streams:h}=this,p=h.findIndex(c=>c.id===d);return p>=0&&(h.splice(p,1),h.sort(Zi),this.minLevel=h.length>0?h[0].level:-1),n}function f(){for(let{stream:d}of this.streams)typeof d.flushSync=="function"&&d.flushSync(),d.end()}function u(d){let h=new Array(this.streams.length);for(let p=0;p<h.length;p++)h[p]={level:d,stream:this.streams[p].stream};return{write:s,add:a,remove:l,minLevel:d,streams:h,clone:u,emit:i,flushSync:o,[gn]:!0}}}function Zi(t,e){return t.level-e.level}function cd(t,e){return e?t-1:0}function ud(t,e){return e?t-1:t+1}function fd(t,e,r){return r?t>=0:t<e}eo.exports=ld});var go=I((Cm,Y)=>{"use strict";var dd=require("node:os"),co=Mr(),pd=Dr(),hd=Nr(),uo=Ns(),md=Ki(),fo=Ne(),{configure:gd}=Yi(),{assertDefaultLevelFound:yd,mappings:po,genLsCache:wd,genLevelComparison:bd,assertLevelComparison:Sd}=on(),{DEFAULT_LEVELS:ho,SORTING_ORDER:_d}=jt(),{createArgsNormalizer:xd,asChindings:vd,buildSafeSonicBoom:ro,buildFormatters:kd,stringify:yn,normalizeDestFileDescriptor:no,noop:Cd}=Lt(),{version:Td}=an(),{chindingsSym:so,redactFmtSym:$d,serializersSym:io,timeSym:Ad,timeSliceIndexSym:Ed,streamSym:Od,stringifySym:oo,stringifySafeSym:wn,stringifiersSym:ao,setLevelSym:Rd,endSym:Id,formatOptsSym:Pd,messageKeySym:Fd,errorKeySym:Md,nestedKeySym:Dd,mixinSym:Ld,levelCompSym:jd,useOnlyCustomLevelsSym:Nd,formattersSym:lo,hooksSym:qd,nestedKeyStrSym:Ud,mixinMergeStrategySym:Bd,msgPrefixSym:Hd}=fo,{epochTime:mo,nullTime:Wd}=uo,{pid:Vd}=process,zd=dd.hostname(),Kd=co.err,Gd={level:"info",levelComparison:_d.ASC,levels:ho,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Vd,hostname:zd},serializers:Object.assign(Object.create(null),{err:Kd}),formatters:Object.assign(Object.create(null),{bindings(t){return t},level(t,e){return{level:e}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:mo,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Jd=xd(Gd),Xd=Object.assign(Object.create(null),co);function bn(...t){let e={},{opts:r,stream:n}=Jd(e,pd(),...t);r.level&&typeof r.level=="string"&&ho[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:s,crlf:i,serializers:o,timestamp:a,messageKey:l,errorKey:f,nestedKey:u,base:d,name:h,level:p,customLevels:c,levelComparison:m,mixin:y,mixinMergeStrategy:w,useOnlyCustomLevels:b,formatters:_,hooks:S,depthLimit:k,edgeLimit:R,onChild:$,msgPrefix:O}=r,T=gd({maximumDepth:k,maximumBreadth:R}),P=kd(_.level,_.bindings,_.log),N=yn.bind({[wn]:T}),D=s?hd(s,N):{},H=s?{stringify:D[$d]}:{stringify:N},U="}"+(i?`\r
44
44
  `:`
45
- `),W=vd.bind(null,{[so]:"",[io]:o,[ao]:L,[oo]:yn,[wn]:$,[lo]:P}),F="";d!==null&&(h===void 0?F=W(d):F=W(Object.assign({},d,{name:h})));let V=a instanceof Function?a:a?mo:Wd,ar=V().indexOf(":")+1;if(b&&!c)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);yd(p,c,b);let lr=po(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:lr,messageKey:l,errorKey:f}}),Sd(m);let cr=bd(m);return Object.assign(e,{levels:lr,[jd]:cr,[Nd]:b,[Od]:n,[Ad]:V,[Ed]:ar,[oo]:yn,[wn]:$,[ao]:L,[Id]:U,[Pd]:H,[Md]:l,[Fd]:f,[Ld]:u,[Ud]:u?`,${JSON.stringify(u)}:{`:"",[io]:o,[Dd]:y,[Bd]:w,[so]:F,[lo]:P,[qd]:S,silent:Cd,onChild:T,[Hd]:O}),Object.setPrototypeOf(e,md()),wd(e),e[Rd](p),e}Y.exports=bn;Y.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=no(t.dest||process.stdout.fd),ro(t)):ro({dest:no(t),minLength:0});Y.exports.transport=Qr();Y.exports.multistream=to();Y.exports.levels=po();Y.exports.stdSerializers=Xd;Y.exports.stdTimeFunctions=Object.assign({},uo);Y.exports.symbols=fo;Y.exports.version=$d;Y.exports.default=bn;Y.exports.pino=bn});var rs=C(ts(),1),{program:Fh,createCommand:Lh,createArgument:Dh,createOption:jh,CommanderError:Nh,InvalidArgumentError:qh,InvalidOptionArgumentError:Uh,Command:ns,Argument:Bh,Option:Hh,Help:Wh}=rs.default;var ee=C(require("fs")),_e=C(require("path")),ss=C(require("os"));var it={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:200,timeout:12e4,autoMode:!1,contextBudget:12e4,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},se={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var Le=_e.join(ss.homedir(),".hablas"),Cr=_e.join(Le,"config.json");function De(t={}){let e={};if(ee.existsSync(Cr))try{e=JSON.parse(ee.readFileSync(Cr,"utf-8"))}catch{}let r={...it,...e,tools:{...it.tools,...e.tools||{},runCommand:{...it.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...it.workspace,...e.workspace||{}}};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_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=_e.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 je(t){ee.existsSync(Le)||ee.mkdirSync(Le,{recursive:!0}),ee.writeFileSync(Cr,JSON.stringify(t,null,2),"utf-8")}function is(){let t=[Le,_e.join(Le,"logs"),_e.join(Le,"backup")];for(let e of t)ee.existsSync(e)||ee.mkdirSync(e,{recursive:!0})}var Sn=C(go()),_n=C(require("path")),yo=C(require("os")),Ut=C(require("fs"));function xn(t){let e=_n.join(yo.homedir(),".hablas","logs");Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0});let r=_n.join(e,`session-${Date.now()}.log`);return(0,Sn.default)({level:"info"},Sn.default.destination({dest:r,sync:!1}))}var Bt=C(require("fs")),ut=C(require("path"));function wo(){let t=[ut.resolve(__dirname,"..","package.json"),ut.resolve(__dirname,"..","..","package.json"),ut.resolve(process.cwd(),"package.json"),ut.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Bt.existsSync(e)){let r=JSON.parse(Bt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Ma=C(require("fs")),Fa=C(require("path"));var Ht=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let f=o.split(`
45
+ `),W=vd.bind(null,{[so]:"",[io]:o,[ao]:D,[oo]:yn,[wn]:T,[lo]:P}),M="";d!==null&&(h===void 0?M=W(d):M=W(Object.assign({},d,{name:h})));let V=a instanceof Function?a:a?mo:Wd,ar=V().indexOf(":")+1;if(b&&!c)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(y&&typeof y!="function")throw Error(`Unknown mixin type "${typeof y}" - expected "function"`);if(O&&typeof O!="string")throw Error(`Unknown msgPrefix type "${typeof O}" - expected "string"`);yd(p,c,b);let lr=po(c,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:lr,messageKey:l,errorKey:f}}),Sd(m);let cr=bd(m);return Object.assign(e,{levels:lr,[jd]:cr,[Nd]:b,[Od]:n,[Ad]:V,[Ed]:ar,[oo]:yn,[wn]:T,[ao]:D,[Id]:U,[Pd]:H,[Fd]:l,[Md]:f,[Dd]:u,[Ud]:u?`,${JSON.stringify(u)}:{`:"",[io]:o,[Ld]:y,[Bd]:w,[so]:M,[lo]:P,[qd]:S,silent:Cd,onChild:$,[Hd]:O}),Object.setPrototypeOf(e,md()),wd(e),e[Rd](p),e}Y.exports=bn;Y.exports.destination=(t=process.stdout.fd)=>typeof t=="object"?(t.dest=no(t.dest||process.stdout.fd),ro(t)):ro({dest:no(t),minLength:0});Y.exports.transport=Qr();Y.exports.multistream=to();Y.exports.levels=po();Y.exports.stdSerializers=Xd;Y.exports.stdTimeFunctions=Object.assign({},uo);Y.exports.symbols=fo;Y.exports.version=Td;Y.exports.default=bn;Y.exports.pino=bn});var rs=C(ts(),1),{program:Mh,createCommand:Dh,createArgument:Lh,createOption:jh,CommanderError:Nh,InvalidArgumentError:qh,InvalidOptionArgumentError:Uh,Command:ns,Argument:Bh,Option:Hh,Help:Wh}=rs.default;var ee=C(require("fs")),_e=C(require("path")),ss=C(require("os"));var it={model:"stepfun-ai/step-3.7-flash",ollamaHost:"http://localhost:11434",provider:"ollama",apiUrl:"",apiKey:"",workingDirectory:".",historySize:200,timeout:12e4,autoMode:!1,contextBudget:12e4,tools:{runCommand:{blocklist:[],timeout:12e4}},workspace:{envParsing:!0}},se={name:"NVIDIA",apiUrl:"https://integrate.api.nvidia.com/v1",defaultModel:"stepfun-ai/step-3.7-flash",models:["stepfun-ai/step-3.7-flash","stepfun-ai/step-3.5-flash","nvidia/llama-3.1-nemotron-70b-instruct","qwen/qwen2.5-coder-32b-instruct","deepseek-ai/deepseek-coder-33b-instruct"]};var De=_e.join(ss.homedir(),".hablas"),Cr=_e.join(De,"config.json");function Le(t={}){let e={};if(ee.existsSync(Cr))try{e=JSON.parse(ee.readFileSync(Cr,"utf-8"))}catch{}let r={...it,...e,tools:{...it.tools,...e.tools||{},runCommand:{...it.tools.runCommand,...(e.tools||{}).runCommand||{}}},workspace:{...it.workspace,...e.workspace||{}}};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_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=_e.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 je(t){ee.existsSync(De)||ee.mkdirSync(De,{recursive:!0}),ee.writeFileSync(Cr,JSON.stringify(t,null,2),"utf-8")}function is(){let t=[De,_e.join(De,"logs"),_e.join(De,"backup")];for(let e of t)ee.existsSync(e)||ee.mkdirSync(e,{recursive:!0})}var Sn=C(go()),_n=C(require("path")),yo=C(require("os")),Ut=C(require("fs"));function xn(t){let e=_n.join(yo.homedir(),".hablas","logs");Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0});let r=_n.join(e,`session-${Date.now()}.log`);return(0,Sn.default)({level:"info"},Sn.default.destination({dest:r,sync:!1}))}var Bt=C(require("fs")),ut=C(require("path"));function wo(){let t=[ut.resolve(__dirname,"..","package.json"),ut.resolve(__dirname,"..","..","package.json"),ut.resolve(process.cwd(),"package.json"),ut.resolve(__dirname,"..","..","..","package.json")];for(let e of t)try{if(Bt.existsSync(e)){let r=JSON.parse(Bt.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var Fa=C(require("fs")),Ma=C(require("path"));var Ht=class{baseUrl;model;constructor(e){this.baseUrl=e.ollamaHost,this.model=e.model}setModel(e){this.model=e}getModel(){return this.model}async checkConnection(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async listModels(){try{let e=await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(5e3)});return e.ok?((await e.json()).models||[]).map(n=>n.name):[]}catch{return[]}}async chatWithTools(e,r,n){let s={model:this.model,messages:e,stream:!1};r.length>0&&(s.tools=r);let i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)};n&&(i.signal=n);let o=await fetch(`${this.baseUrl}/api/chat`,i);if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(`Ollama error: ${o.status} ${o.statusText} \u2014 ${l}`)}return await o.json()}async*streamChat(e,r){let n=await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:e,stream:!0}),signal:r});if(!n.ok)throw new Error(`Ollama error: ${n.status} ${n.statusText}`);let s=n.body?.getReader();if(!s)throw new Error("No response body");let i=new TextDecoder,o="";for(;;){let{done:a,value:l}=await s.read();if(a)break;o+=i.decode(l,{stream:!0});let f=o.split(`
46
46
  `);o=f.pop()||"";for(let u of f)if(u.trim())try{let d=JSON.parse(u);d.message?.content&&(yield d.message.content)}catch{}}}};var bo=12e4,Yd=6e4,Wt=3,So=1e3,Zd=20;function _o(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 Qd(t){return t.map(e=>({type:"function",function:e.function}))}function ep(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 xo(t){return new Promise(e=>setTimeout(e,t))}function vo(t,e){return!(t.name==="AbortError"||e&&e>=400&&e<500&&e!==429)}var ft=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<Zd;){let i=this.apiUrl.replace(/\/+$/,"")+"/models",o=new URLSearchParams;n&&o.set("after",n),o.set("limit","1000");let a=o.toString();a&&(i+="?"+a);let l=await fetch(i,{headers:this.getHeaders(),signal:AbortSignal.timeout(Yd)});if(!l.ok)break;let f=await l.json();if(Array.isArray(f))e.push(...f.map(u=>u.id||u.name||u).filter(Boolean)),r=!1;else if(f.data&&Array.isArray(f.data)){let u=f.data.map(d=>d.id||d.name).filter(Boolean);e.push(...u),f.has_more&&u.length>0?(n=u[u.length-1],s++):r=!1}else f.models&&Array.isArray(f.models)&&e.push(...f.models.map(u=>u.name||u.id).filter(Boolean)),r=!1}return e.sort((i,o)=>i.localeCompare(o))}catch{return[]}}async chatWithTools(e,r,n){let s=this.apiUrl.replace(/\/+$/,"")+"/chat/completions",i={model:this.model,messages:_o(e)};r.length>0&&(i.tools=Qd(r),i.tool_choice="auto");let o=null;for(let a=0;a<=Wt;a++)try{let l=new AbortController,f=setTimeout(()=>l.abort(),bo),u={method:"POST",headers:{"Content-Type":"application/json",...this.getHeaders()},body:JSON.stringify(i),signal:n||l.signal};try{let d=await fetch(s,u);if(clearTimeout(f),!d.ok){let m=await d.text().catch(()=>"");if(!vo(null,d.status))throw new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`);if(o=new Error(`API error: ${d.status} ${d.statusText} \u2014 ${m}`),a<Wt){let y=So*Math.pow(2,a);await xo(y);continue}throw o}let p=(await d.json()).choices?.[0];if(!p)throw new Error("API returned empty response");let c=p.message.tool_calls?ep(p.message.tool_calls):void 0;return{message:{role:p.message.role||"assistant",content:p.message.content||"",tool_calls:c},done:!0,done_reason:p.finish_reason}}catch(d){if(clearTimeout(f),d.name==="AbortError"&&n?.aborted)throw d;if(vo(d)&&(o=d,a<Wt)){let h=So*Math.pow(2,a);await xo(h);continue}throw d}}catch(l){if(l.name==="AbortError")throw l;if(o=l,a>=Wt)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:_o(e),stream:!0}),signal:r||AbortSignal.timeout(bo)});if(!s.ok)throw new Error(`API error: ${s.status} ${s.statusText}`);let i=s.body?.getReader();if(!i)throw new Error("No response body");let o=new TextDecoder,a="";for(;;){let{done:l,value:f}=await i.read();if(l)break;a+=o.decode(f,{stream:!0});let u=a.split(`
47
- `);a=u.pop()||"";for(let d of u){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Be(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:se.apiUrl};return new ft(e)}return t.provider==="custom"&&t.apiUrl?new ft(t):new Ht(t)}function He(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var j=C(require("fs/promises")),On=C(require("fs")),ge=C(require("path"));function ce(){}ce.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(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,f=e.length,u=1,d=l+f;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,c=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(c[0],r,e,0);if(c[0].oldPos+1>=f&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,w=1/0;function b(){for(var S=Math.max(y,-u);S<=Math.min(w,u);S+=2){var k=void 0,R=c[S-1],T=c[S+1];R&&(c[S-1]=void 0);var O=!1;if(T){var $=T.oldPos-S;O=T&&0<=$&&$<l}var P=R&&R.oldPos+1<f;if(!O&&!P){c[S]=void 0;continue}if(!P||O&&R.oldPos+1<T.oldPos?k=o.addToPath(T,!0,void 0,0):k=o.addToPath(R,void 0,!0,1),m=o.extractCommon(k,r,e,S),k.oldPos+1>=f&&m+1>=l)return a(tp(o,k.lastComponent,r,e,o.useLongestToken));c[S]=k,k.oldPos+1>=f&&(w=Math.min(w,S-1)),m+1>=l&&(y=Math.max(y,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>p)return i();b()||S()},0)})();else for(;u<=d&&Date.now()<=p;){var _=b();if(_)return _}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,f=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,f++;return f&&(e.lastComponent={count:f,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function tp(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,f=0,u=0;a<l;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 p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=r.slice(f,f+d.count);h=h.map(function(m,y){var w=n[u+y];return w.length>m.length?w:m}),d.value=t.join(h)}else d.value=t.join(r.slice(f,f+d.count));f+=d.count,d.added||(u+=d.count)}}var c=i[l-1];return l>1&&typeof c.value=="string"&&(c.added||c.removed)&&t.equals("",c.value)&&(i[l-2].value+=c.value,i.pop()),i}var qm=new ce;var ko=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Co=/\S/,$o=new ce;$o.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Co.test(t)&&!Co.test(e)};$o.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]&&ko.test(e[r])&&ko.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var Tn=new ce;Tn.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
48
- `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function rp(t,e,r){return Tn.diff(t,e,r)}var np=new ce;np.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var sp=new ce;sp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Vt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Vt=function(e){return typeof e}:Vt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vt(t)}function vn(t){return ip(t)||op(t)||ap(t)||lp()}function ip(t){if(Array.isArray(t))return kn(t)}function op(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function ap(t,e){if(t){if(typeof t=="string")return kn(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 kn(t,e)}}function kn(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 lp(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
49
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var cp=Object.prototype.toString,dt=new ce;dt.useLongestToken=!0;dt.tokenize=Tn.tokenize;dt.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(Cn(t,null,null,s),s," ")};dt.equals=function(t,e){return ce.prototype.equals.call(dt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Cn(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(cp.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]=Cn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Vt(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=Cn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var $n=new ce;$n.tokenize=function(t){return t.slice()};$n.join=$n.removeEmpty=function(t){return t};function up(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=rp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(b){return" "+b})}for(var f=[],u=0,d=0,h=[],p=1,c=1,m=function(b){var _=a[b],S=_.lines||_.value.replace(/\n$/,"").split(`
50
- `);if(_.lines=S,_.added||_.removed){var k;if(!u){var R=a[b-1];u=p,d=c,R&&(h=o.context>0?l(R.lines.slice(-o.context)):[],u-=h.length,d-=h.length)}(k=h).push.apply(k,vn(S.map(function(U){return(_.added?"+":"-")+U}))),_.added?c+=S.length:p+=S.length}else{if(u)if(S.length<=o.context*2&&b<a.length-2){var T;(T=h).push.apply(T,vn(l(S)))}else{var O,$=Math.min(S.length,o.context);(O=h).push.apply(O,vn(l(S.slice(0,$))));var P={oldStart:u,oldLines:p-u+$,newStart:d,newLines:c-d+$,lines:h};if(b>=a.length-2&&S.length<=o.context){var N=/\n$/.test(r),L=/\n$/.test(n),H=S.length==0&&h.length>P.oldLines;!N&&H&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!H||!L)&&h.push("\")}f.push(P),u=0,d=0,h=[]}p+=S.length,c+=S.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:f}}function To(t){if(Array.isArray(t))return t.map(To).join(`
47
+ `);a=u.pop()||"";for(let d of u){let h=d.trim();if(!(!h||h==="data: [DONE]")&&h.startsWith("data: "))try{let c=JSON.parse(h.slice(6)).choices?.[0]?.delta?.content;c&&(yield c)}catch{}}}}getHeaders(){let e={};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}};function Be(t){if(t.provider==="nvidia"){let e={...t,provider:"custom",apiUrl:se.apiUrl};return new ft(e)}return t.provider==="custom"&&t.apiUrl?new ft(t):new Ht(t)}function He(t){if(t.provider==="nvidia")return"NVIDIA NIM";if(t.provider==="custom")try{return`Custom (${new URL(t.apiUrl).hostname})`}catch{return"Custom API"}return"Ollama (local)"}var j=C(require("fs/promises")),On=C(require("fs")),ge=C(require("path"));function ce(){}ce.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(S){return i?(setTimeout(function(){i(void 0,S)},0),!0):S}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var l=r.length,f=e.length,u=1,d=l+f;s.maxEditLength&&(d=Math.min(d,s.maxEditLength));var h=(n=s.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+h,c=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(c[0],r,e,0);if(c[0].oldPos+1>=f&&m+1>=l)return a([{value:this.join(r),count:r.length}]);var y=-1/0,w=1/0;function b(){for(var S=Math.max(y,-u);S<=Math.min(w,u);S+=2){var k=void 0,R=c[S-1],$=c[S+1];R&&(c[S-1]=void 0);var O=!1;if($){var T=$.oldPos-S;O=$&&0<=T&&T<l}var P=R&&R.oldPos+1<f;if(!O&&!P){c[S]=void 0;continue}if(!P||O&&R.oldPos+1<$.oldPos?k=o.addToPath($,!0,void 0,0):k=o.addToPath(R,void 0,!0,1),m=o.extractCommon(k,r,e,S),k.oldPos+1>=f&&m+1>=l)return a(tp(o,k.lastComponent,r,e,o.useLongestToken));c[S]=k,k.oldPos+1>=f&&(w=Math.min(w,S-1)),m+1>=l&&(y=Math.max(y,S+1))}u++}if(i)(function S(){setTimeout(function(){if(u>d||Date.now()>p)return i();b()||S()},0)})();else for(;u<=d&&Date.now()<=p;){var _=b();if(_)return _}},addToPath:function(e,r,n,s){var i=e.lastComponent;return i&&i.added===r&&i.removed===n?{oldPos:e.oldPos+s,lastComponent:{count:i.count+1,added:r,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+s,lastComponent:{count:1,added:r,removed:n,previousComponent:i}}},extractCommon:function(e,r,n,s){for(var i=r.length,o=n.length,a=e.oldPos,l=a-s,f=0;l+1<i&&a+1<o&&this.equals(r[l+1],n[a+1]);)l++,a++,f++;return f&&(e.lastComponent={count:f,previousComponent:e.lastComponent}),e.oldPos=a,l},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);return r},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function tp(t,e,r,n,s){for(var i=[],o;e;)i.push(e),o=e.previousComponent,delete e.previousComponent,e=o;i.reverse();for(var a=0,l=i.length,f=0,u=0;a<l;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 p=i[a-1];i[a-1]=i[a],i[a]=p}}else{if(!d.added&&s){var h=r.slice(f,f+d.count);h=h.map(function(m,y){var w=n[u+y];return w.length>m.length?w:m}),d.value=t.join(h)}else d.value=t.join(r.slice(f,f+d.count));f+=d.count,d.added||(u+=d.count)}}var c=i[l-1];return l>1&&typeof c.value=="string"&&(c.added||c.removed)&&t.equals("",c.value)&&(i[l-2].value+=c.value,i.pop()),i}var qm=new ce;var ko=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,Co=/\S/,To=new ce;To.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!Co.test(t)&&!Co.test(e)};To.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]&&ko.test(e[r])&&ko.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};var $n=new ce;$n.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
48
+ `));var e=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var n=0;n<r.length;n++){var s=r[n];n%2&&!this.options.newlineIsToken?e[e.length-1]+=s:(this.options.ignoreWhitespace&&(s=s.trim()),e.push(s))}return e};function rp(t,e,r){return $n.diff(t,e,r)}var np=new ce;np.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var sp=new ce;sp.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Vt(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Vt=function(e){return typeof e}:Vt=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vt(t)}function vn(t){return ip(t)||op(t)||ap(t)||lp()}function ip(t){if(Array.isArray(t))return kn(t)}function op(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function ap(t,e){if(t){if(typeof t=="string")return kn(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 kn(t,e)}}function kn(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 lp(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
49
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var cp=Object.prototype.toString,dt=new ce;dt.useLongestToken=!0;dt.tokenize=$n.tokenize;dt.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(Cn(t,null,null,s),s," ")};dt.equals=function(t,e){return ce.prototype.equals.call(dt,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Cn(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(cp.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]=Cn(t[i],e,r,n,s);return e.pop(),r.pop(),o}if(t&&t.toJSON&&(t=t.toJSON()),Vt(t)==="object"&&t!==null){e.push(t),o={},r.push(o);var a=[],l;for(l in t)t.hasOwnProperty(l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],o[l]=Cn(t[l],e,r,n,l);e.pop(),r.pop()}else o=t;return o}var Tn=new ce;Tn.tokenize=function(t){return t.slice()};Tn.join=Tn.removeEmpty=function(t){return t};function up(t,e,r,n,s,i,o){o||(o={}),typeof o.context>"u"&&(o.context=4);var a=rp(r,n,o);if(!a)return;a.push({value:"",lines:[]});function l(w){return w.map(function(b){return" "+b})}for(var f=[],u=0,d=0,h=[],p=1,c=1,m=function(b){var _=a[b],S=_.lines||_.value.replace(/\n$/,"").split(`
50
+ `);if(_.lines=S,_.added||_.removed){var k;if(!u){var R=a[b-1];u=p,d=c,R&&(h=o.context>0?l(R.lines.slice(-o.context)):[],u-=h.length,d-=h.length)}(k=h).push.apply(k,vn(S.map(function(U){return(_.added?"+":"-")+U}))),_.added?c+=S.length:p+=S.length}else{if(u)if(S.length<=o.context*2&&b<a.length-2){var $;($=h).push.apply($,vn(l(S)))}else{var O,T=Math.min(S.length,o.context);(O=h).push.apply(O,vn(l(S.slice(0,T))));var P={oldStart:u,oldLines:p-u+T,newStart:d,newLines:c-d+T,lines:h};if(b>=a.length-2&&S.length<=o.context){var N=/\n$/.test(r),D=/\n$/.test(n),H=S.length==0&&h.length>P.oldLines;!N&&H&&r.length>0&&h.splice(P.oldLines,0,"\"),(!N&&!H||!D)&&h.push("\")}f.push(P),u=0,d=0,h=[]}p+=S.length,c+=S.length}},y=0;y<a.length;y++)m(y);return{oldFileName:t,newFileName:e,oldHeader:s,newHeader:i,hunks:f}}function $o(t){if(Array.isArray(t))return t.map($o).join(`
51
51
  `);var e=[];t.oldFileName==t.newFileName&&e.push("Index: "+t.oldFileName),e.push("==================================================================="),e.push("--- "+t.oldFileName+(typeof t.oldHeader>"u"?"":" "+t.oldHeader)),e.push("+++ "+t.newFileName+(typeof t.newHeader>"u"?"":" "+t.newHeader));for(var r=0;r<t.hunks.length;r++){var n=t.hunks[r];n.oldLines===0&&(n.oldStart-=1),n.newLines===0&&(n.newStart-=1),e.push("@@ -"+n.oldStart+","+n.oldLines+" +"+n.newStart+","+n.newLines+" @@"),e.push.apply(e,n.lines)}return e.join(`
52
52
  `)+`
53
- `}function fp(t,e,r,n,s,i,o){return To(up(t,e,r,n,s,i,o))}function Ao(t,e,r,n,s,i){return fp(t,t,e,r,n,s,i)}function An(t,e,r){return Ao(t,e,r,"original","modified")}var oe=C(require("fs/promises")),En=C(require("fs")),We=C(require("path")),Oo=C(require("os")),pt=We.join(Oo.homedir(),".hablas","backup"),Eo=10;async function Te(t){try{if(!En.existsSync(t))return;En.existsSync(pt)||await oe.mkdir(pt,{recursive:!0});let e=await oe.readFile(t,"utf-8"),r=We.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=We.join(pt,s);await oe.writeFile(i,e,"utf-8");let a=(await oe.readdir(pt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Eo)for(let l of a.slice(Eo))await oe.unlink(We.join(pt,l))}catch{}}function Io(t){let e=p=>ge.resolve(t,p);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(p.path),y=(await j.readFile(c,"utf-8")).split(`
54
- `),w=y.length,b=p.start_line?Math.max(1,p.start_line):1,_=p.end_line?Math.min(w,p.end_line):w,S=y.slice(b-1,_),k=String(_).length,R=S.map(($,P)=>`${String(b+P).padStart(k," ")} | ${$}`),T=`[${p.path} \u2014 lines ${b}-${_} of ${w}]`,O=_<w?`
55
- ... [Partial read. Total lines: ${w}.]`:"";return{success:!0,output:`${T}
53
+ `}function fp(t,e,r,n,s,i,o){return $o(up(t,e,r,n,s,i,o))}function Ao(t,e,r,n,s,i){return fp(t,t,e,r,n,s,i)}function An(t,e,r){return Ao(t,e,r,"original","modified")}var oe=C(require("fs/promises")),En=C(require("fs")),We=C(require("path")),Oo=C(require("os")),pt=We.join(Oo.homedir(),".hablas","backup"),Eo=10;async function $e(t){try{if(!En.existsSync(t))return;En.existsSync(pt)||await oe.mkdir(pt,{recursive:!0});let e=await oe.readFile(t,"utf-8"),r=We.basename(t),n=Date.now(),s=`${r}.${n}.bak`,i=We.join(pt,s);await oe.writeFile(i,e,"utf-8");let a=(await oe.readdir(pt)).filter(l=>l.startsWith(`${r}.`)&&l.endsWith(".bak")).sort().reverse();if(a.length>Eo)for(let l of a.slice(Eo))await oe.unlink(We.join(pt,l))}catch{}}function Io(t){let e=p=>ge.resolve(t,p);return[{name:"read_file",description:"Read the FULL content of a file with line numbers (complete read, no truncation by default per user requirement for 1000/2000+ line files like architecture docs). Use start_line/end_line ONLY if you explicitly need a specific section. Never re-read the same path this turn \u2014 use previous tool observations from history.",safety:"safe",parameters:{path:{type:"string",description:"File path to read",required:!0},start_line:{type:"number",description:"Starting line number (1-based, optional)",required:!1},end_line:{type:"number",description:"Ending line number (inclusive, optional)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[read_file]: path is required"};let c=e(p.path),y=(await j.readFile(c,"utf-8")).split(`
54
+ `),w=y.length,b=p.start_line?Math.max(1,p.start_line):1,_=p.end_line?Math.min(w,p.end_line):w,S=y.slice(b-1,_),k=String(_).length,R=S.map((T,P)=>`${String(b+P).padStart(k," ")} | ${T}`),$=`[${p.path} \u2014 lines ${b}-${_} of ${w}]`,O=_<w?`
55
+ ... [Partial read. Total lines: ${w}.]`:"";return{success:!0,output:`${$}
56
56
  ${R.join(`
57
- `)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return On.existsSync(c)&&await Te(c),await j.mkdir(ge.dirname(c),{recursive:!0}),await j.writeFile(c,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[write_file]: ${c.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.old_content,w=p.new_content,b=Ro(m,y);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await Te(c);let _=m.replace(y,w);await j.writeFile(c,_,"utf-8");let S=An(p.path,m,_);return{success:!0,output:`Edited: ${p.path}
57
+ `)}${O}`}}catch(c){return{success:!1,output:"",error:`[read_file]: ${c.message}`}}}},{name:"write_file",description:"Create or overwrite a file with content",safety:"confirm",parameters:{path:{type:"string",description:"File path to write",required:!0},content:{type:"string",description:"Content to write",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[write_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[write_file]: content is required"};let c=e(p.path);return On.existsSync(c)&&await $e(c),await j.mkdir(ge.dirname(c),{recursive:!0}),await j.writeFile(c,p.content,"utf-8"),{success:!0,output:`Written: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[write_file]: ${c.message}`}}}},{name:"edit_file",description:'Apply a surgical edit by replacing old content with new content. Must match exactly one location. CRITICAL: old_content MUST be an EXACT unique string copied from a previous read_file result. If you do not have it, use patch_file with start_line/end_line instead. Do not guess old_content or the call will fail with "old_content is required".',safety:"confirm",parameters:{path:{type:"string",description:"File path to edit",required:!0},old_content:{type:"string",description:"Exact content to replace (must be unique in the file)",required:!0},new_content:{type:"string",description:"New content to insert",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[edit_file]: path is required"};if(!p.old_content)return{success:!1,output:"",error:"[edit_file]: old_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.old_content,w=p.new_content,b=Ro(m,y);if(b===0)return{success:!1,output:"",error:"[edit_file]: Old content not found in file"};if(b>1)return{success:!1,output:"",error:`[edit_file]: old_content matches ${b} locations in the file. Provide more surrounding context to be specific.`};await $e(c);let _=m.replace(y,w);await j.writeFile(c,_,"utf-8");let S=An(p.path,m,_);return{success:!0,output:`Edited: ${p.path}
58
58
  ${S}`}}catch(c){return{success:!1,output:"",error:`[edit_file]: ${c.message}`}}}},{name:"patch_file",description:"Replace lines in a file using line numbers. More reliable than edit_file. Use read_file first to see line numbers.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},start_line:{type:"number",description:"First line to replace (1-indexed)",required:!0},end_line:{type:"number",description:"Last line to replace (inclusive)",required:!0},new_content:{type:"string",description:"New content to insert in place of those lines",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[patch_file]: path is required"};if(!p.start_line)return{success:!1,output:"",error:"[patch_file]: start_line is required"};if(!p.end_line)return{success:!1,output:"",error:"[patch_file]: end_line is required"};if(p.new_content===void 0)return{success:!1,output:"",error:"[patch_file]: new_content is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=m.split(`
59
- `),w=y.length,b=p.start_line,_=p.end_line;if(b<1||b>w)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${w} lines)`};if(_<b||_>w)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${w})`};await Te(c);let S=y.slice(0,b-1),k=y.slice(_),R=p.new_content.split(`
60
- `),T=[...S,...R,...k].join(`
61
- `);await j.writeFile(c,T,"utf-8");let O=An(p.path,m,T),$=_-b+1,P=R.length;return{success:!0,output:`Patched: ${p.path} (replaced ${$} lines with ${P})
62
- ${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.search,w=p.replace,b=p.is_regex;await Te(c);let _,S;if(b){let k=new RegExp(y,"g");S=(m.match(k)||[]).length,_=m.replace(k,w)}else S=Ro(m,y),_=m.split(y).join(w);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await j.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${p.path}`})}catch(c){return{success:!1,output:"",error:`[search_and_replace]: ${c.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(p.path);return await j.mkdir(ge.dirname(c),{recursive:!0}),On.existsSync(c)&&await Te(c),await j.appendFile(c,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[append_to_file]: ${c.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(p.path);return await Te(c),await j.unlink(c),{success:!0,output:`Deleted: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[delete_file]: ${c.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(p.from),m=e(p.to);return await j.mkdir(ge.dirname(m),{recursive:!0}),await j.rename(c,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(c){return{success:!1,output:"",error:`[move_file]: ${c.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(p.path);return await j.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[create_dir]: ${c.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let c=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Po(c,"",m,0)||"(empty directory)"}}catch(c){return{success:!1,output:"",error:`[list_dir]: ${c.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(p.path),m=await j.stat(c);return{success:!0,output:[`Path: ${p.path}`,`Size: ${pp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
59
+ `),w=y.length,b=p.start_line,_=p.end_line;if(b<1||b>w)return{success:!1,output:"",error:`[patch_file]: start_line ${b} is out of range (file has ${w} lines)`};if(_<b||_>w)return{success:!1,output:"",error:`[patch_file]: end_line ${_} is out of range (start_line=${b}, total=${w})`};await $e(c);let S=y.slice(0,b-1),k=y.slice(_),R=p.new_content.split(`
60
+ `),$=[...S,...R,...k].join(`
61
+ `);await j.writeFile(c,$,"utf-8");let O=An(p.path,m,$),T=_-b+1,P=R.length;return{success:!0,output:`Patched: ${p.path} (replaced ${T} lines with ${P})
62
+ ${O}`}}catch(c){return{success:!1,output:"",error:`[patch_file]: ${c.message}`}}}},{name:"search_and_replace",description:"Find and replace all occurrences of a pattern in a file. Supports regex. Returns count of replacements made.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},search:{type:"string",description:"Search pattern (string or regex)",required:!0},replace:{type:"string",description:"Replacement string",required:!0},is_regex:{type:"boolean",description:"Treat search as regex (default: false)",required:!1}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[search_and_replace]: path is required"};if(!p.search)return{success:!1,output:"",error:"[search_and_replace]: search is required"};if(p.replace===void 0)return{success:!1,output:"",error:"[search_and_replace]: replace is required"};let c=e(p.path),m=await j.readFile(c,"utf-8"),y=p.search,w=p.replace,b=p.is_regex;await $e(c);let _,S;if(b){let k=new RegExp(y,"g");S=(m.match(k)||[]).length,_=m.replace(k,w)}else S=Ro(m,y),_=m.split(y).join(w);return S===0?{success:!1,output:"",error:"[search_and_replace]: Pattern not found in file"}:(await j.writeFile(c,_,"utf-8"),{success:!0,output:`Replaced ${S} occurrence(s) in ${p.path}`})}catch(c){return{success:!1,output:"",error:`[search_and_replace]: ${c.message}`}}}},{name:"append_to_file",description:"Append content to the end of a file. Creates the file if it does not exist.",safety:"confirm",parameters:{path:{type:"string",description:"File path",required:!0},content:{type:"string",description:"Content to append",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[append_to_file]: path is required"};if(p.content===void 0)return{success:!1,output:"",error:"[append_to_file]: content is required"};let c=e(p.path);return await j.mkdir(ge.dirname(c),{recursive:!0}),On.existsSync(c)&&await $e(c),await j.appendFile(c,p.content,"utf-8"),{success:!0,output:`Appended to: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[append_to_file]: ${c.message}`}}}},{name:"delete_file",description:"Delete a file",safety:"dangerous",parameters:{path:{type:"string",description:"File path to delete",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[delete_file]: path is required"};let c=e(p.path);return await $e(c),await j.unlink(c),{success:!0,output:`Deleted: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[delete_file]: ${c.message}`}}}},{name:"move_file",description:"Move or rename a file",safety:"confirm",parameters:{from:{type:"string",description:"Source path",required:!0},to:{type:"string",description:"Destination path",required:!0}},execute:async p=>{try{if(!p.from)return{success:!1,output:"",error:"[move_file]: from is required"};if(!p.to)return{success:!1,output:"",error:"[move_file]: to is required"};let c=e(p.from),m=e(p.to);return await j.mkdir(ge.dirname(m),{recursive:!0}),await j.rename(c,m),{success:!0,output:`Moved: ${p.from} \u2192 ${p.to}`}}catch(c){return{success:!1,output:"",error:`[move_file]: ${c.message}`}}}},{name:"create_dir",description:"Create a directory",safety:"safe",parameters:{path:{type:"string",description:"Directory path to create",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[create_dir]: path is required"};let c=e(p.path);return await j.mkdir(c,{recursive:!0}),{success:!0,output:`Created directory: ${p.path}`}}catch(c){return{success:!1,output:"",error:`[create_dir]: ${c.message}`}}}},{name:"list_dir",description:"List directory contents as a tree",safety:"safe",parameters:{path:{type:"string",description:"Directory path (default: .)",required:!1},depth:{type:"number",description:"Max depth (default: 3)",required:!1}},execute:async p=>{try{let c=e(p.path||"."),m=p.depth||3;return{success:!0,output:await Po(c,"",m,0)||"(empty directory)"}}catch(c){return{success:!1,output:"",error:`[list_dir]: ${c.message}`}}}},{name:"get_file_info",description:"Get file stats: size, last modified, type",safety:"safe",parameters:{path:{type:"string",description:"File path",required:!0}},execute:async p=>{try{if(!p.path)return{success:!1,output:"",error:"[get_file_info]: path is required"};let c=e(p.path),m=await j.stat(c);return{success:!0,output:[`Path: ${p.path}`,`Size: ${pp(m.size)}`,`Type: ${m.isDirectory()?"directory":"file"}`,`Modified: ${m.mtime.toISOString()}`,`Created: ${m.birthtime.toISOString()}`].join(`
63
63
  `)}}catch(c){return{success:!1,output:"",error:`[get_file_info]: ${c.message}`}}}}]}function Ro(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 dp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next"]);async function Po(t,e,r,n){if(n>=r)return"";let i=(await j.readdir(t,{withFileTypes:!0})).filter(a=>!dp.has(a.name)&&!a.name.startsWith(".")).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name)),o="";for(let a=0;a<i.length;a++){let l=i[a],f=a===i.length-1,u=f?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=l.isDirectory()?"\u{1F4C1}":"\u{1F4C4}";if(o+=`${e}${u}${d} ${l.name}
64
- `,l.isDirectory()){let h=e+(f?" ":"\u2502 ");o+=await Po(ge.join(t,l.name),h,r,n+1)}}return o}function pp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Lo=require("child_process");var Mo=require("child_process"),zt=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,Mo.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+=`
64
+ `,l.isDirectory()){let h=e+(f?" ":"\u2502 ");o+=await Po(ge.join(t,l.name),h,r,n+1)}}return o}function pp(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}var Do=require("child_process");var Fo=require("child_process"),zt=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,Fo.spawn)(e,{shell:!0,cwd:this.config.workingDir,env:{...process.env,...r?.env}}),o={id:n,command:e,process:i,stdout:"",stderr:"",startTime:Date.now(),pid:i.pid,status:"running"};return i.stdout?.on("data",a=>{o.stdout+=a.toString(),o.stdout.length>this.config.maxOutputSize&&(o.stdout=o.stdout.slice(-this.config.maxOutputSize))}),i.stderr?.on("data",a=>{o.stderr+=a.toString(),o.stderr.length>this.config.maxOutputSize&&(o.stderr=o.stderr.slice(-this.config.maxOutputSize))}),i.on("exit",a=>{o.status="finished",o.exitCode=a??void 0}),i.on("error",a=>{o.status="finished",o.stderr+=`
65
65
  Error: ${a.message}`}),s>0&&setTimeout(()=>{o.status==="running"&&(this.kill(n),o.status="timeout",o.stderr+=`
66
66
  Process timed out after ${s}ms`)},s),this.processes.set(n,o),n}readOutput(e,r){let n=this.processes.get(e);if(!n)return{success:!1,output:"",status:"not_found",error:`Background process ${e} not found`};let s=r?.type||"both",i="";return(s==="stdout"||s==="both")&&(i+=n.stdout),(s==="stderr"||s==="both")&&(i&&(i+=`
67
67
  `),i+=n.stderr),r?.lastLines&&(i=i.split(`
68
68
  `).slice(-r.lastLines).join(`
69
- `)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var hp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Rn=null;function Fo(t){return Rn||(Rn=new zt({workingDir:t})),Rn}function Do(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=[...hp,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Fo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
- PID: ${Fo(t).getProcess(l)?.pid}
71
- Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let f=(0,Lo.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{l(h===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${h}`})}),f.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Kt=C(require("fs/promises")),ye=C(require("path")),mp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function jo(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=ye.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await No(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
69
+ `)),{success:!0,output:i,status:n.status}}kill(e){let r=this.processes.get(e);if(!r)return!1;if(r.process.pid)try{process.kill(-r.process.pid,"SIGTERM")}catch{try{process.kill(r.process.pid,"SIGTERM")}catch{}}return r.status="killed",!0}killAll(){let e=0;for(let r of this.processes.keys())this.kill(r)&&e++;return e}listProcesses(){let e=[];for(let[r,n]of this.processes){let s=Date.now()-n.startTime,i=this.formatUptime(s);e.push({id:r,command:n.command,status:n.status,pid:n.pid,startTime:n.startTime,uptime:i})}return e}getProcess(e){return this.processes.get(e)}cleanup(){let e=0;for(let[r,n]of this.processes)(n.status==="finished"||n.status==="killed"||n.status==="timeout")&&(this.processes.delete(r),e++);return e}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return`${r}s`;let n=Math.floor(r/60);return n<60?`${n}m ${r%60}s`:`${Math.floor(n/60)}h ${n%60}m`}};var hp=["rm -rf /","rm -rf /*","rm -rf ~","rm -rf $HOME","rm -rf /home","mkfs",":(){ :|:& };:"],Rn=null;function Mo(t){return Rn||(Rn=new zt({workingDir:t})),Rn}function Lo(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=[...hp,...o];if(a.length>0){for(let l of a)if(n.includes(l))return{success:!1,output:"",error:`Blocked pattern: "${l}". This command is prohibited due to security risks.`}}if(s){let l=Mo(t).start(n,{timeout:i});return{success:!0,output:`Background process started: ${l}
70
+ PID: ${Mo(t).getProcess(l)?.pid}
71
+ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Promise(l=>{let f=(0,Do.exec)(n,{cwd:t,timeout:i,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{l(h===0?{success:!0,output:u||"(no output)"}:{success:!1,output:u,error:d||`Exit code: ${h}`})}),f.on("error",h=>{l({success:!1,output:"",error:h.message})})})}}}var Kt=C(require("fs/promises")),ye=C(require("path")),mp=new Set(["node_modules",".git","__pycache__",".venv","dist","build",".next",".cache"]),gp=new Set([".ts",".js",".tsx",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".css",".html",".json",".md",".yaml",".yml",".toml"]);function jo(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=ye.resolve(t,e.path||"."),s=new RegExp(r,"gi"),i=[];if(await No(n,s,i,t),i.length===0)return{success:!0,output:`No matches found for: "${r}"`};let o=i.slice(0,50).join(`
72
72
  `),a=i.length>50?`
73
73
  ... and ${i.length-50} more matches`:"";return{success:!0,output:o+a}}catch(r){return{success:!1,output:"",error:`Search failed: ${r.message}`}}}}}async function No(t,e,r,n){let s=await Kt.readdir(t,{withFileTypes:!0});for(let i of s){if(mp.has(i.name)||i.name.startsWith("."))continue;let o=ye.join(t,i.name);if(i.isDirectory())await No(o,e,r,n);else if(gp.has(ye.extname(i.name)))try{let l=(await Kt.readFile(o,"utf-8")).split(`
74
74
  `),f=ye.relative(n,o);for(let u=0;u<l.length;u++)e.test(l[u])&&(r.push(`${f}:${u+1}: ${l[u].trim()}`),e.lastIndex=0)}catch{}}}var In=require("child_process"),Z=C(require("fs")),we=C(require("path"));function yp(t){let e=[],r=we.join(t,"tsconfig.json");if(!Z.existsSync(r))return e;try{(0,In.execSync)("npx tsc --noEmit 2>&1",{cwd:t,encoding:"utf-8",timeout:3e4})}catch(n){let s=n,o=(s.stdout||s.message||"").split(`
@@ -86,13 +86,13 @@ Use bash_output to read output: bash_output(process_id="${l}")`}}return new Prom
86
86
  ${"#".repeat(parseInt(n))} ${s.replace(/<[^>]+>/g,"").trim()}
87
87
  `),e=e.replace(/<a[^>]+href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi,(r,n,s)=>{let i=s.replace(/<[^>]+>/g,"").trim();return i?`[${i}](${n})`:n}),e=e.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi,(r,n)=>"\n```\n"+n.replace(/<[^>]+>/g,"").trim()+"\n```\n"),e=e.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi,"`$1`"),e=e.replace(/<(b|strong)[^>]*>([\s\S]*?)<\/\1>/gi,"**$2**"),e=e.replace(/<(i|em)[^>]*>([\s\S]*?)<\/\1>/gi,"*$2*"),e=e.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi,"\u2022 $1"),e=e.replace(/<[^>]+>/g,""),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/&#(\d+);/g,(r,n)=>String.fromCharCode(parseInt(n))).replace(/&[a-z]+;/gi,""),e=e.replace(/[ \t]+/g," "),e=e.replace(/\n{3,}/g,`
88
88
 
89
- `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Cp(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 $p(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 Vo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ho);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":vp,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<Bo;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Bo)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl: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 ${Ho/1e3}s`):s}}function zo(){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 Vo(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Cp(r),o=kp(r);return o.length>Wo&&(o=o.slice(0,Wo)+`
89
+ `),e=e.replace(/^\s+|\s+$/gm,""),e.trim()}function Cp(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 Tp(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 Vo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Ho);try{let n=await fetch(t,{signal:e.signal,headers:{"User-Agent":vp,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<Bo;){let{done:u,value:d}=await i.read();if(u)break;o.push(d),a+=d.length}if(a>=Bo)try{i.cancel()}catch{}let l=new TextDecoder("utf-8",{fatal:!1});return{html:o.map(u=>l.decode(u,{stream:!0})).join("")+l.decode(),finalUrl: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 ${Ho/1e3}s`):s}}function zo(){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 Vo(e);if(!r||s>=400)return{success:!1,output:"",error:`HTTP ${s} \u2014 could not fetch ${e}`};let i=Cp(r),o=kp(r);return o.length>Wo&&(o=o.slice(0,Wo)+`
90
90
 
91
91
  [... content truncated ...]`),{success:!0,output:[`# ${i}`,`URL: ${n}`,`Fetched: ${new Date().toISOString()}`,"",o].join(`
92
- `)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await Vo(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=$p(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,f)=>`${f+1}. [${l.text}](${l.url})`).join(`
92
+ `)}}catch(r){let n=r instanceof Error?r.message:String(r);return{success:!1,output:"",error:`Failed to scrape ${e}: ${n}`}}}},{name:"extract_links",description:"Extract all links (URLs) from a web page. Returns a list of link text and URLs. Useful for finding documentation pages, navigation, or related resources.",safety:"safe",parameters:{url:{type:"string",description:"The URL to extract links from",required:!0},filter:{type:"string",description:"Optional: only return links containing this text in URL or link text",required:!1}},execute:async t=>{let e=t.url,r=t.filter?.toLowerCase()||"";if(!e)return{success:!1,output:"",error:"URL is required"};if(!e.startsWith("http://")&&!e.startsWith("https://"))return{success:!1,output:"",error:"URL must start with http:// or https://"};try{let{html:n,finalUrl:s,status:i}=await Vo(e);if(!n||i>=400)return{success:!1,output:"",error:`HTTP ${i} \u2014 could not fetch ${e}`};let o=Tp(n,s);if(r&&(o=o.filter(l=>l.url.toLowerCase().includes(r)||l.text.toLowerCase().includes(r))),o.length===0)return{success:!0,output:"No links found"+(r?` matching "${r}"`:"")};let a=o.slice(0,100).map((l,f)=>`${f+1}. [${l.text}](${l.url})`).join(`
93
93
  `);return{success:!0,output:`Found ${o.length} links:
94
94
 
95
- ${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var Tp=3600*1e3,Ve=new Map;function Ap(t){let e=Ve.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>Tp?(Ve.delete(t.toLowerCase().trim()),null):e.results:null}function Ep(t,e){if(Ve.size>200){let r=Ve.keys().next().value;r!==void 0&&Ve.delete(r)}Ve.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Op(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 Rp(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],f=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}f&&l&&!l.startsWith("/")&&i.push({title:f,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,f=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!f.has(u)&&!u.includes("duckduckgo.com")&&(f.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Ip(t,e=5){let r=Ap(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Op(t,e)},{name:"duckduckgo",fn:()=>Rp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Ep(t,i),i}catch{}return[]}function Ko(){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 Ip(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(`
95
+ ${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,output:"",error:`Failed to extract links from ${e}: ${s}`}}}}]}var $p=3600*1e3,Ve=new Map;function Ap(t){let e=Ve.get(t.toLowerCase().trim());return e?Date.now()-e.timestamp>$p?(Ve.delete(t.toLowerCase().trim()),null):e.results:null}function Ep(t,e){if(Ve.size>200){let r=Ve.keys().next().value;r!==void 0&&Ve.delete(r)}Ve.set(t.toLowerCase().trim(),{results:e,timestamp:Date.now()})}async function Op(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 Rp(t,e){try{let r=new URLSearchParams({q:t}),n=await fetch(`https://html.duckduckgo.com/html/?${r}`,{headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},signal:AbortSignal.timeout(1e4)});if(!n.ok)return null;let s=await n.text(),i=[],o=/<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi,a;for(;(a=o.exec(s))!==null&&i.length<e;){let l=a[1],f=a[2].replace(/<[^>]+>/g,"").trim(),u=a[3].replace(/<[^>]+>/g,"").trim(),d=l.match(/uddg=([^&]+)/);if(d)try{l=decodeURIComponent(d[1])}catch{}f&&l&&!l.startsWith("/")&&i.push({title:f,url:l,snippet:u,source:"duckduckgo"})}if(i.length===0){let l=/<a[^>]+href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/gi,f=new Set;for(;(a=l.exec(s))!==null&&i.length<e;){let u=a[1],d=a[2].replace(/<[^>]+>/g,"").trim();d&&d.length>5&&!f.has(u)&&!u.includes("duckduckgo.com")&&(f.add(u),i.push({title:d,url:u,snippet:"",source:"duckduckgo"}))}}return i.length>0?i:null}catch{return null}}async function Ip(t,e=5){let r=Ap(t);if(r)return r.slice(0,e);let n=[{name:"brave",fn:()=>Op(t,e)},{name:"duckduckgo",fn:()=>Rp(t,e)}];for(let s of n)try{let i=await s.fn();if(i&&i.length>0)return Ep(t,i),i}catch{}return[]}function Ko(){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 Ip(e.trim(),r);if(n.length===0)return{success:!0,output:`No results found for: "${e}". Try rephrasing the search query.`};let s=[`Search results for: "${e}" (${n.length} results, source: ${n[0].source})`,""];for(let i=0;i<n.length;i++){let o=n[i];s.push(`[${i+1}] ${o.title}`),s.push(` ${o.url}`),o.snippet&&s.push(` ${o.snippet}`),s.push("")}return{success:!0,output:s.join(`
96
96
  `)}}catch(n){return{success:!1,output:"",error:`Search failed: ${n instanceof Error?n.message:String(n)}`}}}}}var ue=C(require("fs")),Zo=C(require("path")),Go=50*1024*1024,Jo=4e4;function Xo(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=Ae(o[1]));let a=e.match(/\/Author\s*\(([^)]*)\)/);a&&(r.author=Ae(a[1]));let l=e.match(/\/Subject\s*\(([^)]*)\)/);l&&(r.subject=Ae(l[1]));let f=e.match(/\/Creator\s*\(([^)]*)\)/);f&&(r.creator=Ae(f[1]));let u=/stream\r?\n([\s\S]*?)\r?\nendstream/g,d;for(;(d=u.exec(e))!==null;){let p=d[1],c=Yo(p);c.trim()&&n.push(c);try{let m=require("zlib"),y=Buffer.from(p,"latin1"),w=m.inflateSync(y).toString("latin1"),b=Yo(w);b.trim()&&!n.includes(b)&&n.push(b)}catch{}}return{text:n.join(`
97
97
  `).replace(/\r\n/g,`
98
98
  `).replace(/\n{3,}/g,`
@@ -106,9 +106,9 @@ ${a}`}}catch(n){let s=n instanceof Error?n.message:String(n);return{success:!1,o
106
106
  [... content truncated ...]`),{success:!0,output:`${[`PDF: ${r.path}`,`Pages: ${a}`,l.title?`Title: ${l.title}`:"",l.author?`Author: ${l.author}`:"",`Size: ${(s.size/1024).toFixed(1)}KB`,""].filter(Boolean).join(`
107
107
  `)}
108
108
  ${f}`}}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(!ue.existsSync(n))return{success:!1,output:"",error:`File not found: ${r.path}`};try{let s=ue.statSync(n),i=ue.readFileSync(n),{pages:o,metadata:a}=Xo(i);return{success:!0,output:[`File: ${r.path}`,`Size: ${(s.size/1024).toFixed(1)}KB`,`Pages: ${o}`,a.title?`Title: ${a.title}`:null,a.author?`Author: ${a.author}`:null,a.subject?`Subject: ${a.subject}`:null,a.creator?`Creator: ${a.creator}`:null,`Modified: ${s.mtime.toISOString()}`].filter(Boolean).join(`
109
- `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var ra=require("child_process"),Gt=C(require("fs")),na=C(require("os")),sa=C(require("path")),ia=1e4,ea=16e3;function ze(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 ta={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>ze("tsx")?`tsx "${t}"`:ze("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=>ze("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>ze("python3")||ze("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>ze("bash")}};async function Pp(t,e,r=ia){let n=ta[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ta).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=na.tmpdir(),i=sa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Gt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let f=(0,ra.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:u.slice(0,ea),stderr:d.slice(0,ea/2),exitCode:h??1,duration:p,language:e})}),f.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{Gt.unlinkSync(i)}catch{}}}function Mp(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 oa(){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()||Mp(e),n=Math.min(Math.max(1e3,t.timeout||ia),3e4),s=await Pp(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?`
109
+ `)}}catch(s){return{success:!1,output:"",error:`Failed to read PDF metadata: ${s instanceof Error?s.message:String(s)}`}}}}]}var ra=require("child_process"),Gt=C(require("fs")),na=C(require("os")),sa=C(require("path")),ia=1e4,ea=16e3;function ze(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 ta={javascript:{extension:".js",command:t=>`node --no-warnings "${t}"`,available:()=>!0},typescript:{extension:".ts",command:t=>ze("tsx")?`tsx "${t}"`:ze("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=>ze("python3")?`python3 "${t}"`:`python "${t}"`,available:()=>ze("python3")||ze("python")},bash:{extension:".sh",command:t=>`bash "${t}"`,available:()=>ze("bash")}};async function Pp(t,e,r=ia){let n=ta[e];if(!n)return{success:!1,stdout:"",stderr:`Unsupported language: "${e}". Supported: ${Object.keys(ta).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=na.tmpdir(),i=sa.join(s,`hablas_exec_${Date.now()}${n.extension}`);try{Gt.writeFileSync(i,t,"utf-8");let o=n.command(i),a=Date.now();return await new Promise(l=>{let f=(0,ra.exec)(o,{timeout:r,maxBuffer:5242880,cwd:s,env:{...process.env,NODE_ENV:"production",FORCE_COLOR:"0"}}),u="",d="";f.stdout?.on("data",h=>{u+=h}),f.stderr?.on("data",h=>{d+=h}),f.on("close",h=>{let p=Date.now()-a;l({success:h===0,stdout:u.slice(0,ea),stderr:d.slice(0,ea/2),exitCode:h??1,duration:p,language:e})}),f.on("error",h=>{let p=Date.now()-a;l({success:!1,stdout:"",stderr:h.message,exitCode:1,duration:p,language:e})})})}finally{try{Gt.unlinkSync(i)}catch{}}}function Fp(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 oa(){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()||Fp(e),n=Math.min(Math.max(1e3,t.timeout||ia),3e4),s=await Pp(e,r,n),i=[];return i.push(`Language: ${s.language} | Exit: ${s.exitCode} | Duration: ${s.duration}ms`),i.push(""),s.stdout&&(i.push("Output:"),i.push(s.stdout)),s.stderr&&(i.push(s.stdout?`
110
110
  Errors/Warnings:`:"Errors:"),i.push(s.stderr)),!s.stdout&&!s.stderr&&i.push("(no output)"),{success:s.success,output:i.join(`
111
- `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Ke=class{tools=new Map;constructor(e,r){let n=Io(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Do(e,r)),this.tools.set("search_codebase",jo(e)),this.tools.set("detect_bugs",Uo(e)),this.tools.set("web_search",Ko());for(let s of zo())this.tools.set(s.name,s);for(let s of Qo(e))this.tools.set(s.name,s);for(let s of oa())this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
111
+ `),error:s.success?void 0:s.stderr||`Exit code: ${s.exitCode}`}}}]}var Ke=class{tools=new Map;constructor(e,r){let n=Io(e);for(let s of n)this.tools.set(s.name,s);this.tools.set("run_command",Lo(e,r)),this.tools.set("search_codebase",jo(e)),this.tools.set("detect_bugs",Uo(e)),this.tools.set("web_search",Ko());for(let s of zo())this.tools.set(s.name,s);for(let s of Qo(e))this.tools.set(s.name,s);for(let s of oa())this.tools.set(s.name,s)}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}getSafetyLevel(e){return this.tools.get(e)?.safety}async execute(e){let r=this.tools.get(e.name);return r?r.execute(e.arguments):{success:!1,output:"",error:`Unknown tool: ${e.name}`}}getOllamaTools(){return this.getAll().map(e=>{let r={},n=[];for(let[s,i]of Object.entries(e.parameters))r[s]={type:i.type==="number"?"number":"string",description:i.description},i.required&&n.push(s);return{type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:r,required:n}}}})}getToolDescriptions(){return this.getAll().map(r=>{let n=Object.entries(r.parameters).map(([s,i])=>` ${s}: ${i.type} \u2014 ${i.description}`).join(`
112
112
  `);return`- ${r.name} [${r.safety}]: ${r.description}
113
113
  ${n}`}).join(`
114
114
 
@@ -120,56 +120,114 @@ ${o.content}`),s+=o.tokenCount}return i.join(`
120
120
  `)}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(f=>i.length===0?!0:i.some(u=>f.path.includes(u))).sort((f,u)=>this.computeScore(u)-this.computeScore(f)),a=0,l=[];for(let f of o){if(a+f.tokenCount>n)break;l.push(`--- ${f.path} ---
121
121
  ${f.content}`),a+=f.tokenCount}return l.join(`
122
122
 
123
- `)}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=Pn(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 aa.createHash("md5").update(e).digest("hex")}};var Fp=0;function mt(){return`msg_${Date.now()}_${++Fp}`}function Je(t){return Math.ceil(t.length/4)}var Xe=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=Je(e);this.messages.push({id:mt(),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=mt(),s=Je(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=mt(),i=Je(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=mt(),s=Je(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=Je(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:mt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
123
+ `)}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=Pn(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 aa.createHash("md5").update(e).digest("hex")}};var Mp=0;function mt(){return`msg_${Date.now()}_${++Mp}`}function Je(t){return Math.ceil(t.length/4)}var Xe=class t{messages=[];maxMessages;maxTokens;sessionId;snapshots=[];forks=new Map;agentMessageCounts=new Map;totalTokens=0;constructor(e,r=50,n=32e3){this.maxMessages=r,this.maxTokens=n,this.sessionId=`session_${Date.now()}`;let s=Je(e);this.messages.push({id:mt(),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=mt(),s=Je(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=mt(),i=Je(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=mt(),s=Je(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=Je(e),n=this.messages.filter(s=>s.priority==="critical"&&s.role!=="system");this.messages=[{id:mt(),role:"system",content:e,timestamp:Date.now(),priority:"critical",tokenEstimate:r,compressed:!1,tags:["system"]},...n],this.recalculateTokens()}takeSnapshot(e){let r={id:`snap_${Date.now()}`,timestamp:Date.now(),messages:this.messages.map(n=>({...n})),systemPrompt:this.messages[0]?.content||"",label:e};return this.snapshots.push(r),this.snapshots.length>10&&(this.snapshots=this.snapshots.slice(-10)),r.id}rollback(e){let r=this.snapshots.find(n=>n.id===e);return r?(this.messages=r.messages.map(n=>({...n})),this.recalculateTokens(),!0):!1}getSnapshots(){return[...this.snapshots]}fork(e,r){let n=this.messages.length,s=new t(r,this.maxMessages,this.maxTokens),i=this.messages.filter(o=>o.priority==="critical"||o.priority==="high").filter(o=>o.role!=="system").slice(-5);for(let o of i)o.role==="user"?s.addUserMessage(o.content,{priority:o.priority,tags:[...o.tags,"inherited"]}):o.role==="assistant"&&s.addAssistantMessage(o.content,o.tool_calls,o.agent);return this.forks.set(e,{parentSessionId:this.sessionId,forkPoint:n,session:s}),s}mergeFork(e,r){let n=this.forks.get(e);if(!n)return!1;let s=n.session.getEnhancedMessages().filter(i=>i.role!=="system").filter(i=>!i.tags.includes("inherited"));if(r)this.addAssistantMessage(`[Agent @${e} result]: ${r}`,void 0,e);else if(s.length>0){let i=s.filter(o=>o.role==="assistant").pop();i&&this.addAssistantMessage(i.content,i.tool_calls,e)}return this.forks.delete(e),!0}getActiveForks(){return Array.from(this.forks.keys())}searchMessages(e){let r=e.toLowerCase();return this.messages.filter(n=>n.content.toLowerCase().includes(r))}getMessagesByTag(e){return this.messages.filter(r=>r.tags.includes(e))}getLastByRole(e,r=1){return this.messages.filter(n=>n.role===e).slice(-r)}trimIfNeeded(){if(this.messages.length<=this.maxMessages&&this.totalTokens<=this.maxTokens)return;let e=this.messages.filter(r=>r.role==="tool"&&!r.compressed&&r.tokenEstimate>200);for(let r of e.slice(0,-3)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(r)}if(this.totalTokens>this.maxTokens||this.messages.length>this.maxMessages){let r=this.messages.filter(n=>n.role==="assistant"&&!n.compressed&&n.priority!=="critical"&&n.tokenEstimate>300);for(let n of r.slice(0,-2)){if(this.totalTokens<=this.maxTokens&&this.messages.length<=this.maxMessages)break;this.compressMessage(n)}}if(this.messages.length>this.maxMessages){let r=this.messages[0],n=this.messages.slice(1),s={critical:3,high:2,normal:1,low:0},i=n.sort((o,a)=>{let l=s[a.priority]-s[o.priority];return l!==0?l:a.timestamp-o.timestamp}).slice(0,this.maxMessages-1);i.sort((o,a)=>o.timestamp-a.timestamp),this.messages=[r,...i],this.recalculateTokens()}}compressMessage(e){let r=e.content.length,n=e.tokenEstimate;e.role==="tool"?e.content=e.content.slice(0,200)+`
124
124
  ...(compressed from `+r+" chars)":e.content=e.content.slice(0,400)+`
125
- ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=Je(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 Ze=C(require("fs")),la=C(require("path"));var A=C(require("fs")),E=C(require("path"));function Lp(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Dp(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function jp(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Np(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ye(t){let e=Lp(t),r=Dp(t),n=jp(t),s=Np(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),f=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)A.existsSync(E.join(t,m))&&f.push(m);let d=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of h)A.existsSync(E.join(t,m))&&d.push(m);let p=[],c=["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 c)A.existsSync(E.join(t,m))&&p.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:f,configFiles:d,entryPoints:p}}function Jt(t){let e=[` Project: ${E.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(`
125
+ ...(compressed from `+r+" chars)",e.compressed=!0,e.originalLength=r,e.tokenEstimate=Je(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 Ze=C(require("fs")),la=C(require("path"));var A=C(require("fs")),E=C(require("path"));function Dp(t){let e=E.join(t,"package.json");if(A.existsSync(e))try{let r=JSON.parse(A.readFileSync(e,"utf-8")),n={...r.dependencies,...r.devDependencies};if(n.next)return"next";if(n.nuxt)return"nuxt";if(n["@angular/core"])return"angular";if(n.svelte||n["@sveltejs/kit"])return"svelte";if(n.vue)return"vue";if(n.react)return"react";if(n["@nestjs/core"])return"nest";if(n.fastify)return"fastify";if(n.express)return"express"}catch{}if(A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml")))try{let r=A.existsSync(E.join(t,"requirements.txt"))?A.readFileSync(E.join(t,"requirements.txt"),"utf-8"):"";if(r.includes("django"))return"django";if(r.includes("flask"))return"flask";if(r.includes("fastapi"))return"fastapi"}catch{}if(A.existsSync(E.join(t,"Cargo.toml")))try{if(A.readFileSync(E.join(t,"Cargo.toml"),"utf-8").includes("actix"))return"rust-actix"}catch{}if(A.existsSync(E.join(t,"go.mod")))try{if(A.readFileSync(E.join(t,"go.mod"),"utf-8").includes("fiber"))return"go-fiber"}catch{}return"unknown"}function Lp(t){return A.existsSync(E.join(t,"pnpm-lock.yaml"))?"pnpm":A.existsSync(E.join(t,"yarn.lock"))?"yarn":A.existsSync(E.join(t,"bun.lockb"))?"bun":A.existsSync(E.join(t,"package-lock.json"))?"npm":A.existsSync(E.join(t,"Cargo.toml"))?"cargo":A.existsSync(E.join(t,"go.mod"))?"go":A.existsSync(E.join(t,"requirements.txt"))||A.existsSync(E.join(t,"pyproject.toml"))?"pip":"unknown"}function jp(t){return A.existsSync(E.join(t,"tsconfig.json"))?"TypeScript":A.existsSync(E.join(t,"package.json"))?"JavaScript":A.existsSync(E.join(t,"Cargo.toml"))?"Rust":A.existsSync(E.join(t,"go.mod"))?"Go":A.existsSync(E.join(t,"pyproject.toml"))||A.existsSync(E.join(t,"requirements.txt"))?"Python":"Unknown"}function Np(t){let e=E.join(t,".git","HEAD");if(!A.existsSync(e))return null;try{let r=A.readFileSync(e,"utf-8").trim();return r.startsWith("ref: refs/heads/")?r.replace("ref: refs/heads/",""):r.substring(0,8)}catch{return null}}function Ye(t){let e=Dp(t),r=Lp(t),n=jp(t),s=Np(t),i=A.existsSync(E.join(t,"Dockerfile"))||A.existsSync(E.join(t,"docker-compose.yml"))||A.existsSync(E.join(t,"docker-compose.yaml")),o=A.existsSync(E.join(t,".github","workflows"))||A.existsSync(E.join(t,".gitlab-ci.yml"))||A.existsSync(E.join(t,"Jenkinsfile")),a=A.existsSync(E.join(t,"__tests__"))||A.existsSync(E.join(t,"tests"))||A.existsSync(E.join(t,"test"))||A.existsSync(E.join(t,"spec")),l=A.existsSync(E.join(t,".git")),f=[],u=[".env",".env.local",".env.development",".env.production",".env.example"];for(let m of u)A.existsSync(E.join(t,m))&&f.push(m);let d=[],h=["package.json","tsconfig.json","vite.config.ts","next.config.js","next.config.mjs","webpack.config.js","tailwind.config.ts","tailwind.config.js","eslint.config.js",".eslintrc.js",".prettierrc","Dockerfile","docker-compose.yml","Makefile"];for(let m of h)A.existsSync(E.join(t,m))&&d.push(m);let p=[],c=["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 c)A.existsSync(E.join(t,m))&&p.push(m);return{rootPath:t,framework:e,packageManager:r,language:n,hasDocker:i,hasCICD:o,hasTests:a,hasGit:l,gitBranch:s,envFiles:f,configFiles:d,entryPoints:p}}function Jt(t){let e=[` Project: ${E.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(`
126
126
  `)}async function Qe(t,e){let r=[],n=la.join(t,"package.json");if(Ze.existsSync(n))try{let o=JSON.parse(Ze.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=Ye(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=qp(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(`
127
127
  `)}function qp(t,e){try{return Ze.readdirSync(t).filter(r=>!r.startsWith(".")).filter(r=>!["node_modules","dist","build",".next",".cache"].includes(r)).slice(0,e)}catch{return[]}}function et(t,e){return`You are Hablas, a single powerful AI software engineering agent created by Abdulmoin Hablas.
128
128
 
129
- Identity:
129
+ Identity contract:
130
130
  - You are the only visible agent.
131
- - Do not mention internal teams, specialists, delegation, routing, orchestration, or hidden systems.
132
- - Speak as one decisive engineering agent.
131
+ - Never mention internal teams, specialist roles, delegation, orchestration, routing layers, or hidden systems.
132
+ - You must still THINK with the depth of a product manager, architect, engineer, debugger, researcher, reviewer, and devops lead \u2014 but you answer as one unified agent.
133
+
134
+ Your internal lenses (silent, never named to the user):
135
+ - Product lens: clarify intent, scope, user value, and priorities.
136
+ - Architecture lens: design clean structure, interfaces, constraints, and trade-offs.
137
+ - Engineer lens: make precise file changes, follow project conventions, ship working code.
138
+ - Debugger lens: find root cause first, make minimal correct fixes, prevent regressions.
139
+ - Research lens: ground claims in evidence from project files and external knowledge when required.
140
+ - Reviewer lens: check security, correctness, maintainability, and verification before claiming success.
141
+ - DevOps lens: consider run/build/test/deploy implications, reproducibility, and operational safety.
133
142
 
134
143
  Style:
135
- - Direct, technical, calm.
144
+ - Direct, technical, calm, precise.
136
145
  - No emojis.
137
146
  - No hype.
138
147
  - No filler.
139
- - No theatrical narration.
148
+ - No theatre.
149
+ - No motivational fluff.
140
150
  - Do not say "let me" unless you are actually about to inspect or execute something.
151
+ - Prefer short strong paragraphs or structured bullets over rambling prose.
152
+
153
+ Absolute operating rules:
154
+ 1. If the task does not need tools, answer directly and clearly.
155
+ 2. If the task needs tools, use tools. Do not fake execution with pure prose.
156
+ 3. For implementation, modification, continuation, or delivery work: real workspace actions are mandatory.
157
+ 4. Read before editing when file content is unknown.
158
+ 5. Do not reread the same file unless it changed or you need a different section.
159
+ 6. One tool call at a time.
160
+ 7. Never output raw tool JSON, XML, pseudo-calls, or internal formatting in user-facing text.
161
+ 8. Ground project-specific claims in observed files or command output.
162
+ 9. Verify before claiming success.
163
+ 10. If something is not verified, say so explicitly.
164
+ 11. If a task is blocked, ask the smallest necessary clarification instead of hallucinating.
165
+ 12. Prefer minimal correct edits over broad rewrites unless the user explicitly wants a rewrite.
166
+
167
+ Tool discipline:
168
+ - Use read_file for evidence.
169
+ - Use search_codebase to find patterns and references.
170
+ - Use patch_file or edit_file for precise changes.
171
+ - Use write_file for new files or full rewrites.
172
+ - Use run_command for verification, builds, installs, and tests.
173
+ - Use list_dir when structure matters.
174
+ - Use the minimum necessary tool sequence.
175
+ - Never claim a file was created, edited, or verified unless a tool actually did it.
176
+
177
+ Implementation contract:
178
+ - If the user asks to build, create, fix, continue, refactor, or complete something, you must enter a real tool-based execution path.
179
+ - Do NOT satisfy implementation tasks with a giant inline code dump when tools are available.
180
+ - If the workspace is empty or missing files, create the needed files.
181
+ - If the request references an unfinished project, continue from existing artifacts instead of restarting from zero.
182
+ - If the request asks for one-step or no-question delivery, complete as much as possible in one pass and avoid unnecessary back-and-forth.
183
+
184
+ Analysis contract:
185
+ - Architecture or design requests should still be rigorous.
186
+ - Prefer reasoning first, then inspect only the files needed to support the recommendation.
187
+ - Provide assumptions, trade-offs, and concrete recommendations.
188
+
189
+ Debugging contract:
190
+ - Start from symptom \u2192 locate evidence \u2192 form hypothesis \u2192 verify \u2192 fix \u2192 verify again.
191
+ - Focus on root cause, not superficial symptoms.
192
+ - Keep fixes minimal and explain why they work.
193
+
194
+ Review contract:
195
+ - Before finalizing technical work, silently review for:
196
+ - correctness
197
+ - security
198
+ - maintainability
199
+ - verification status
200
+ - accidental regressions
201
+
202
+ Response contract:
203
+ - For read-only questions: give the answer and cite the observed source in plain language.
204
+ - For implementation tasks: summarize what changed, what was verified, and what remains.
205
+ - For failed attempts: be explicit, technical, and honest.
206
+ - Never expose internal chain-of-thought.
141
207
 
142
- Core execution rules:
143
- 1. If the task does not need tools, answer directly without inventing a tool workflow.
144
- 2. If the task needs tools, use the minimum necessary tools.
145
- 3. Read before editing when content is unknown.
146
- 4. Do not reread the same file unless it changed or you genuinely need another section.
147
- 5. One tool call at a time.
148
- 6. Never output raw tool JSON, XML, or pseudo-calls in user-facing text.
149
- 7. If the task is project-specific, ground claims in observed files.
150
- 8. If the task is implementation, verify before claiming success.
151
- 9. If you cannot verify, say exactly what remains unverified.
208
+ Few-shot behavior rules:
209
+ - User: "hi"
210
+ -> direct answer, no tools.
211
+ - User: "what is the current version of this project"
212
+ -> inspect the minimum relevant files, then answer from evidence.
213
+ - User: "craet a flower store just frontend"
214
+ -> treat the typo as an implementation request, use tools, create or modify actual files, then summarize.
215
+ - User: "continue the unfinished project"
216
+ -> inspect existing artifacts first, continue from them, do not restart from zero.
217
+ - User: "design the architecture for auth"
218
+ -> provide structured analysis, inspect files only if needed, answer as one unified agent.
219
+ - User: "just give me the finished project in one step no questions"
220
+ -> do real work through tools, complete as much as possible, verify before claiming done.
152
221
 
222
+ Task profile:
153
223
  ${Up(e)}
154
224
 
155
225
  Current project context:
156
- ${t}`}function Up(t){if(t.kind==="casual")return`Task profile:
157
- - Casual social turn.
158
- - No tools unless absolutely unavoidable.`;if(t.kind==="read")return`Task profile:
159
- - Read-only or project-inspection task.
160
- - Use tools only to inspect the minimum necessary evidence.
161
- - Keep the final answer factual and tight.`;if(t.kind==="analysis")return`Task profile:
162
- - Analysis / architecture task.
163
- - Prefer reasoning first.
164
- - If files are relevant, inspect only what is necessary.
165
- - Deliver a structured recommendation, not drama.`;let e=t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",r=t.oneStepDelivery?"- The user requested one-step delivery with no follow-up questions. Complete as much as possible in one pass.":"- Ask a clarifying question only if the task is truly blocked.";return`Task profile:
166
- ${e}
167
- ${r}
168
- - You MUST use workspace tools for implementation work.
169
- - Do not answer with raw code blocks as the main result if you can create or modify files directly.
170
- - The task is not complete unless you actually inspect and then create/modify the relevant files.
171
- - Prefer minimal correct edits over broad rewrites.
172
- - Verify changes before claiming completion.`}var Bp=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Hp=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Wp=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Vp=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,zp=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Kp=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app)\b/i,Gp=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Jp=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,ca=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function gt(t){let e=t.trim(),r=e.toLowerCase(),n=Hp.test(r),s=Wp.test(r),i=Vp.test(r)||zp.test(r),o=Kp.test(r),a=Gp.test(r),l=i||n||s||o&&e.length>18&&!ca.test(r)&&!a,f=a&&!i&&!n&&!s,u=Jp.test(r)||o,d=!l&&!f&&(ca.test(r)||e.endsWith("?"));return Bp.test(e)&&!u&&!l&&!f?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:f?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function Xp(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function ua(t){let e=gt(t);return{input:t,profile:e,plan:Xp(t,e)}}var fa=C(require("readline")),Yt=require("process"),Xt=class{rl=fa.createInterface({input:Yt.stdin,output:Yt.stdout,terminal:!0});async prompt(e){return new Promise(r=>{this.rl.question(e,n=>r(n))})}async confirm(e){return(await this.prompt(`${e} [Y/n] `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return(await this.prompt(`${e} Type yes to confirm: `)).trim().toLowerCase()==="yes"}close(){this.rl.close()}};var Yp={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Zp=`
226
+ ${t}`}function Up(t){return t.kind==="casual"?["- Casual social turn.","- No tools unless absolutely unavoidable.","- Keep the answer short and natural."].join(`
227
+ `):t.kind==="read"?["- Read-only or project-inspection task.","- Use tools only to inspect the minimum necessary evidence.","- Keep the final answer factual, grounded, and tight."].join(`
228
+ `):t.kind==="analysis"?["- Analysis / architecture task.","- Prefer reasoning first.","- If files are relevant, inspect only what is necessary.","- Deliver a structured recommendation with trade-offs and assumptions."].join(`
229
+ `):[t.continuity?"- Continue from existing work. Do not restart the project from zero.":"- Implementation task.",t.oneStepDelivery?"- The user requested one-step delivery with no unnecessary 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.","- Verify changes before claiming completion."].join(`
230
+ `)}var Bp=/^(hi|hello|hey|thanks?|thank you|ok|okay|yes|no|اه|تمام|شكرا|شكراً|مرحبا|أهلا|هلا|كيفك)[.!?\s]*$/i,Hp=/\b(continue|unfinished|resume|previous|existing project|current project|from the previous|from the prd|this and there)\b/i,Wp=/\b(one step|no questions|no ask|just give me|deliver complete|finished project|run it)\b/i,Vp=/\b(build|create|implement|fix|debug|edit|change|update|refactor|generate|write|ship|complete|add|remove|migrate|craft|make)\b/i,zp=/\b(craet|cretae|creat|implemnt|updte|fronend|frontent)\b/i,Kp=/\b(frontend|backend|store|shop|website|web app|landing page|page|component|ui|ux|auth|login|dashboard|api|endpoint|schema|database|project|application|app)\b/i,Gp=/\b(architecture|architect|design|blueprint|plan|requirements|research|compare|investigate|approach|trade[- ]?off|document)\b/i,Jp=/\b(project|repo|repository|codebase|workspace|file|files|src|package\.json|version|current version|readme|config)\b/i,ca=/\b(read|inspect|check|show|list|find|what is|which|where)\b/i;function gt(t){let e=t.trim(),r=e.toLowerCase(),n=Hp.test(r),s=Wp.test(r),i=Vp.test(r)||zp.test(r),o=Kp.test(r),a=Gp.test(r),l=i||n||s||o&&e.length>18&&!ca.test(r)&&!a,f=a&&!i&&!n&&!s,u=Jp.test(r)||o,d=!l&&!f&&(ca.test(r)||e.endsWith("?"));return Bp.test(e)&&!u&&!l&&!f?{kind:"casual",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Pure social turn with no engineering signal."}:l?{kind:"implementation",needsTools:!0,needsWrite:!0,continuity:n,oneStepDelivery:s,requiresProjectContext:!0,reason:n?"Continuation of existing work requires reading and modifying project artifacts.":"Implementation request requires tool-based execution."}:f?{kind:"analysis",needsTools:u,needsWrite:!1,continuity:n,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Architecture/analysis request references the current project.":"Architecture/analysis request can start as a text-first reasoning turn."}:d||u?{kind:"read",needsTools:u,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:u,reason:u?"Project-specific question requires inspection of workspace artifacts.":"Read-only question can be answered directly."}:{kind:"analysis",needsTools:!1,needsWrite:!1,continuity:!1,oneStepDelivery:!1,requiresProjectContext:!1,reason:"Defaulting to direct analytical response."}}function Xp(t,e){if(!e.needsTools)return[{id:"respond",title:"Respond directly and clearly."}];if(e.kind==="read")return[{id:"inspect",title:"Inspect the minimum relevant files."},{id:"answer",title:"Answer precisely from observed facts."}];if(e.kind==="analysis")return[{id:"inspect-context",title:"Inspect only the files needed for analysis."},{id:"reason",title:"Form a concise architectural recommendation."},{id:"answer",title:"Present the result as Hablas only."}];let r=[];return e.continuity&&r.push({id:"continuity",title:"Load existing project context and continue instead of restarting."}),r.push({id:"inspect",title:"Inspect the relevant code and files."}),r.push({id:"implement",title:"Apply the smallest correct implementation."}),r.push({id:"verify",title:"Run verification before claiming completion."}),r.push({id:"answer",title:"Summarize the outcome clearly."}),e.oneStepDelivery&&r.unshift({id:"delivery-contract",title:"Treat the request as no-questions one-step delivery."}),r}function ua(t){let e=gt(t);return{input:t,profile:e,plan:Xp(t,e)}}var fa=C(require("readline")),Yt=require("process"),Xt=class{rl=fa.createInterface({input:Yt.stdin,output:Yt.stdout,terminal:!0});async prompt(e){return new Promise(r=>{this.rl.question(e,n=>r(n))})}async confirm(e){return(await this.prompt(`${e} [Y/n] `)).trim().toLowerCase()!=="n"}async confirmDangerous(e){return(await this.prompt(`${e} Type yes to confirm: `)).trim().toLowerCase()==="yes"}close(){this.rl.close()}};var Yp={maxSteps:150,thinkingEnabled:!0,selfEvalEnabled:!0,minConfidence:.6,showThinking:!1},Zp=`
173
231
  ## Reasoning Protocol
174
232
 
175
233
  Before taking ANY action, you MUST think step-by-step inside <thinking> tags.
@@ -202,7 +260,7 @@ After receiving a tool result, think again:
202
260
  ## Reasoning
203
261
  For non-trivial requests, think briefly inside <thinking>...</thinking> before acting.
204
262
  The user will NOT see thinking blocks. One tool call per turn.
205
- `.trim(),Mn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Yp,...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}
263
+ `.trim(),Fn=class{config;turnSteps=[];stepCounter=0;constructor(e){this.config={...Yp,...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}
206
264
 
207
265
  ${Qp}`:`${e}
208
266
 
@@ -229,21 +287,21 @@ Rate your work. Reply with ONLY a JSON object \u2014 no other text:
229
287
  }
230
288
  </self_eval>
231
289
  `.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(`
232
- `)}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 yt(t){return new Mn(t)}var eh=[{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}],Fn=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 eh)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,f=l?"decompose_task":a.strategy;return o.lastStrategy=f,this.failures.set(e,o),{errorClass:a.errorClass,strategy:f,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
233
- `)}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 wt(t=3){return new Fn(t)}var fe=C(require("fs")),Qt=C(require("path")),da=C(require("os")),Zt=Qt.join(da.homedir(),".hablas","model-formats.json");function th(){try{if(fe.existsSync(Zt))return JSON.parse(fe.readFileSync(Zt,"utf-8"))}catch{}return{}}function rh(t){try{let e=Qt.dirname(Zt);fe.existsSync(e)||fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Zt,JSON.stringify(t,null,2),"utf-8")}catch{}}function pa(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 bt(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 nh(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function sh(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=bt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function ih(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=bt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function oh(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=ha(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function ha(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"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},f=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=f.exec(o))!==null;){let h=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[h]=nh(p)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=d:n==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function ah(t){return ha(t)}function lh(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=bt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ch(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function uh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function fh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},f=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=f.exec(i))!==null;){let d=u[1].trim(),h=u[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[d]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=l.exec(t))!==null;){let u=f[1].trim(),d=f[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 Ln=[{format:"xml_tool_call_wrapper",parse:oh},{format:"xml_prompt",parse:ah},{format:"xml_tags",parse:sh},{format:"xml_parameters",parse:fh},{format:"hermes",parse:ih},{format:"markdown_json",parse:lh},{format:"function_call",parse:ch},{format:"json_object",parse:uh}],jn=class{registry;constructor(){this.registry=th()}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=Ln.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 Ln){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: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)[\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 Ln)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()},rh(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=s.replace(/\n{3,}/g,`
290
+ `)}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 yt(t){return new Fn(t)}var eh=[{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}],Mn=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 eh)if(a.test(r)){let l=s?.lastStrategy===a.strategy&&i>=2,f=l?"decompose_task":a.strategy;return o.lastStrategy=f,this.failures.set(e,o),{errorClass:a.errorClass,strategy:f,explanation:a.explanation,suggestion:l?`Previous recovery attempt ("${a.strategy}") also failed. Try breaking this into smaller steps or use a completely different approach.`:a.suggestion,alternatives:a.alternatives,autoRetry:!l&&a.autoRetry}}return o.lastStrategy=i===1?"retry_fixed":"graceful_fail",this.failures.set(e,o),{errorClass:"unknown",strategy:o.lastStrategy,explanation:`Unexpected error from "${e}".`,suggestion:i===1?"Review the error message and adjust your approach.":"This error is persistent. Explain to the user what went wrong and suggest manual steps.",alternatives:this.suggestAlternatives(e),autoRetry:!1}}buildRecoveryMessage(e,r){let n=[`ERROR: ${r}`,"","[Recovery Analysis]",` Type: ${e.errorClass}`,` Strategy: ${e.strategy}`,` Explanation: ${e.explanation}`,` Suggestion: ${e.suggestion}`];switch(e.alternatives.length>0&&n.push(` Alternative tools: ${e.alternatives.join(", ")}`),e.strategy){case"read_first":n.push("","\u2192 ACTION: Read the file or directory first, then retry with correct information.");break;case"retry_fixed":n.push("","\u2192 ACTION: Fix the arguments based on the error, then retry.");break;case"alternative_tool":n.push("","\u2192 ACTION: Use a different tool to achieve the same goal.");break;case"decompose_task":n.push("","\u2192 ACTION: Break this into smaller, simpler steps.");break;case"ask_user":n.push("","\u2192 ACTION: Ask the user for clarification. Do NOT retry automatically.");break;case"graceful_fail":n.push("","\u2192 ACTION: Explain what went wrong clearly. Suggest manual steps if possible.");break}return n.join(`
291
+ `)}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 wt(t=3){return new Mn(t)}var fe=C(require("fs")),Qt=C(require("path")),da=C(require("os")),Zt=Qt.join(da.homedir(),".hablas","model-formats.json");function th(){try{if(fe.existsSync(Zt))return JSON.parse(fe.readFileSync(Zt,"utf-8"))}catch{}return{}}function rh(t){try{let e=Qt.dirname(Zt);fe.existsSync(e)||fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Zt,JSON.stringify(t,null,2),"utf-8")}catch{}}function pa(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 bt(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 nh(t){return t.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function sh(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=bt(s);i&&e.push({...i,format:"xml_tags",rawMatch:n[0]})}catch{}return e}function ih(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=bt(s);i&&e.push({...i,format:"hermes",rawMatch:n[0]})}}catch{}return e}function oh(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=ha(s);for(let o of i)e.push({...o,format:"xml_tool_call_wrapper",rawMatch:n[0]})}return e}function ha(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"];for(let n of r){let s=new RegExp(`<<?${n}(\\s+[\\s\\S]*?)?(?:>>?([\\s\\S]*?)<<?\\/${n}>>?|\\s*\\/?>>?)`,"gi"),i;for(;(i=s.exec(t))!==null;){let o=i[1]||"",a=i[2]||"",l={},f=/(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+))/g,u;for(;(u=f.exec(o))!==null;){let h=u[1].toLowerCase(),p=u[2]??u[3]??u[4];l[h]=nh(p)}let d=a.trim();d&&(n==="write_file"||n==="append_to_file"?l.content=a:n==="run_command"?l.command=d:n==="patch_file"&&(l.new_content=a)),l.start_line&&(l.start_line=parseInt(l.start_line)),l.end_line&&(l.end_line=parseInt(l.end_line)),l.depth&&(l.depth=parseInt(l.depth)),n==="edit_file"?e.push({tool:"search_and_replace",args:l,format:"xml_prompt",rawMatch:i[0]}):e.push({tool:n,args:l,format:"xml_prompt",rawMatch:i[0]})}}return e}function ah(t){return ha(t)}function lh(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=bt(s);i&&e.push({...i,format:"markdown_json",rawMatch:n[0]})}catch{}return e}function ch(t){let e=[],r=/\{\s*"function"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"function_call",rawMatch:s})}catch{}}return e}function uh(t){let e=[],r=/\{\s*"(?:name|tool)"\s*:/g,n;for(;(n=r.exec(t))!==null;){let s=pa(t,n.index);if(s)try{let i=JSON.parse(s),o=bt(i);o&&e.push({...o,format:"json_object",rawMatch:s})}catch{}}return e}function fh(t){let e=[],r=/<<?tool[-_]call\s*>>?([\s\S]*?)(?:<<?\/tool[-_]call\s*>>?|$)/gi,n,s=!1;for(;(n=r.exec(t))!==null;){let i=n[1],o=/<function=([^>]+)>/i.exec(i);if(o){s=!0;let a=o[1].trim(),l={},f=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,u;for(;(u=f.exec(i))!==null;){let d=u[1].trim(),h=u[2].trim();h==="true"?h=!0:h==="false"?h=!1:!isNaN(Number(h))&&h!==""&&(h=Number(h)),l[d]=h}e.push({tool:a,args:l,format:"xml_parameters",rawMatch:n[0]})}}if(!s&&/<function=([^>]+)>/i.test(t)){let i=/<function=([^>]+)>/i.exec(t);if(i){let o=i[1].trim(),a={},l=/<parameter=([^>]+)>([\s\S]*?)<\/parameter>/gi,f;for(;(f=l.exec(t))!==null;){let u=f[1].trim(),d=f[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 Dn=[{format:"xml_tool_call_wrapper",parse:oh},{format:"xml_prompt",parse:ah},{format:"xml_tags",parse:sh},{format:"xml_parameters",parse:fh},{format:"hermes",parse:ih},{format:"markdown_json",parse:lh},{format:"function_call",parse:ch},{format:"json_object",parse:uh}],jn=class{registry;constructor(){this.registry=th()}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=Dn.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 Dn){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: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)[\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 Dn)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()},rh(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=s.replace(/\n{3,}/g,`
234
292
 
235
- `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},Dn=null;function ma(){return Dn||(Dn=new jn),Dn}var dh=600,ga=2e3,ya=2;function ph(t,e,r){let s=ma().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function hh(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(t==="edit_file"||t==="patch_file"||t==="search_and_replace")&&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):typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function mh(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 wa(t,e,r,n){let s=0,i=Date.now();for(;s<=ya;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=ya)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 Nn(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:f,skipTools:u}=t,d=t.reactEngine??yt(),h=t.errorRecovery??wt(),p=u?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??dh,y=[],w=[],b=[],_="",S=0,k=!1;for(;S<m;){if(S++,f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};let R=d.buildBudgetWarningPrompt();R&&s.addUserMessage(R,{priority:"critical",tags:["system-budget"]});let T;try{T=await r.chatWithTools(s.getMessages(),p,f)}catch(U){let W=U;if(W.name==="AbortError"||f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};if(S<=1){a.onNotice?.(`Transient model error: ${W.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(F=>setTimeout(F,1e3)),S--;continue}return a.onError?.(W.message??"Model request failed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:W.message,completedNaturally:k}}let O=T.message?.content||"",$=T.message?.tool_calls,P=d.parseThinking(O);P.hasThinking&&(d.recordStep({thought:P.thinking}),o.debug({thinking:P.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:L}=ph($,O,c);if(L&&L.trim()&&(_=L,await a.onAssistantText?.(L,e)),N.length===0){s.addAssistantMessage(O,void 0,e.role),k=!0;break}s.addAssistantMessage(O,N,e.role);let H=N.length;for(let U=0;U<N.length;U++){let W=N[U];if(!W?.function?.name)continue;let F=W.function.name,V=W.function.arguments||{},ar=n.getSafetyLevel(F)??"confirm";if(!n.get(F)){a.onNotice?.(`Unknown tool: ${F} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${F}". Available: ${n.getAll().map(Pe=>Pe.name).join(", ")}`);continue}if(await l(F,ar,V)==="skip"){s.addToolMessage(`Tool ${F} was skipped by policy/user.`);break}y.push(F),typeof V.path=="string"&&b.push(V.path);let cr=hh(F,V);a.onToolStart?.(F,cr,V),a.onToolCall?.(),d.recordStep({thought:P.hasThinking?`Executing: ${F}`:"",action:F,actionInput:V});let z=await wa(n,F,V,o);a.onToolEnd?.(F,z.success,z.error||z.output,z.duration,V);let Ie;if(z.success)Ie=ht(z.output,ga),d.recordObservation(Ie.slice(0,300)),w.push({tool:F,success:!0,summary:z.output.slice(0,150)});else{let Pe=z.error||"Unknown error",Me=h.analyze(F,Pe,V);if(Ie=h.buildRecoveryMessage(Me,Pe),d.recordObservation(`FAILED: ${Pe}`,`Recovery: ${Me.strategy} \u2014 ${Me.suggestion}`),o.info({tool:F,errorClass:Me.errorClass,strategy:Me.strategy},"Error recovery analysis"),w.push({tool:F,success:!1,summary:Pe.slice(0,150)}),Me.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Fe=await wa(n,F,V,o);a.onToolEnd?.(F,Fe.success,Fe.output,Fe.duration,V),Fe.success&&(Ie=ht(Fe.output,ga),d.recordObservation(Ie.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:F,success:!0,summary:Fe.output.slice(0,150)})}}if(s.addToolMessage(Ie),z.success&&F==="read_file"&&typeof V.path=="string"&&i?.addFile(V.path,z.output),o.info({tool:F,success:z.success,durationMs:z.duration,retries:z.retries},"Tool executed"),!z.success&&mh(z.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&U<H-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return S>=m&&!k&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!0,completedNaturally:k}}function be(t){return[...new Set(t)]}function ba(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 Sa(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}var tr=C(require("fs")),qn=C(require("os")),er=C(require("path"));function gh(){let t=[er.resolve(__dirname,"..","package.json"),er.resolve(__dirname,"..","..","package.json"),er.resolve(process.cwd(),"package.json")];for(let e of t)try{if(tr.existsSync(e)){let r=JSON.parse(tr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _a=gh(),xa=process.stdout.isTTY===!0,yh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb";function Ee(t,e){return!xa||yh?t:`${e}${t}\x1B[0m`}var v={strong:t=>Ee(t,"\x1B[1;37m"),muted:t=>Ee(t,"\x1B[38;5;244m"),accent:t=>Ee(t,"\x1B[38;5;81m"),info:t=>Ee(t,"\x1B[38;5;110m"),success:t=>Ee(t,"\x1B[38;5;108m"),warning:t=>Ee(t,"\x1B[38;5;179m"),error:t=>Ee(t,"\x1B[38;5;167m")};function va(t,e){let r=e.replace(qn.homedir(),"~"),n="\u2500".repeat(88);return["",v.muted(n),` ${v.strong("HABLAS")} ${v.muted("single-agent engineering runtime")}`,` ${v.muted("version")} ${v.accent(_a)} ${v.muted("model")} ${v.accent(t)}`,` ${v.muted("workspace")} ${v.muted(r)}`,v.muted(n),` ${v.muted("\u203A Type naturally to get started")}`,` ${v.muted("\u203A /help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,""].join(`
293
+ `),{toolCalls:n,displayContent:s.trim(),format:e[0]?.format??"unknown"}}},Ln=null;function ma(){return Ln||(Ln=new jn),Ln}var dh=600,ga=2e3,ya=2;function ph(t,e,r){let s=ma().parse(e,t,r);return{toolCalls:s.toolCalls,displayContent:s.displayContent}}function hh(t,e){return t==="write_file"&&typeof e.path=="string"?`create ${e.path}`:(t==="edit_file"||t==="patch_file"||t==="search_and_replace")&&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):typeof e.path=="string"?String(e.path):t.replace(/_/g," ")}function mh(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 wa(t,e,r,n){let s=0,i=Date.now();for(;s<=ya;){let o=await t.execute({name:e,arguments:r});if(o.success||s>=ya)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 Nn(t){let{identity:e,client:r,registry:n,session:s,contextManager:i,logger:o,io:a={},safetyPolicy:l,abortSignal:f,skipTools:u}=t,d=t.reactEngine??yt(),h=t.errorRecovery??wt(),p=u?[]:n.getOllamaTools(),c=r.getModel(),m=t.maxIterations??dh,y=[],w=[],b=[],_="",S=0,k=!1;for(;S<m;){if(S++,f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};let R=d.buildBudgetWarningPrompt();R&&s.addUserMessage(R,{priority:"critical",tags:["system-budget"]});let $;try{$=await r.chatWithTools(s.getMessages(),p,f)}catch(U){let W=U;if(W.name==="AbortError"||f?.aborted)return{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:"Aborted",completedNaturally:k};if(S<=1){a.onNotice?.(`Transient model error: ${W.message??"unknown"} \u2014 retrying\u2026`,"retry"),await new Promise(M=>setTimeout(M,1e3)),S--;continue}return a.onError?.(W.message??"Model request failed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!1,error:W.message,completedNaturally:k}}let O=$.message?.content||"",T=$.message?.tool_calls,P=d.parseThinking(O);P.hasThinking&&(d.recordStep({thought:P.thinking}),o.debug({thinking:P.thinking.slice(0,200)},"ReAct thinking"));let{toolCalls:N,displayContent:D}=ph(T,O,c);if(D&&D.trim()&&(_=D,await a.onAssistantText?.(D,e)),N.length===0){s.addAssistantMessage(O,void 0,e.role),k=!0;break}s.addAssistantMessage(O,N,e.role);let H=N.length;for(let U=0;U<N.length;U++){let W=N[U];if(!W?.function?.name)continue;let M=W.function.name,V=W.function.arguments||{},ar=n.getSafetyLevel(M)??"confirm";if(!n.get(M)){a.onNotice?.(`Unknown tool: ${M} \u2014 skipping`,"warn"),s.addToolMessage(`Error: Unknown tool "${M}". Available: ${n.getAll().map(Pe=>Pe.name).join(", ")}`);continue}if(await l(M,ar,V)==="skip"){s.addToolMessage(`Tool ${M} was skipped by policy/user.`);break}y.push(M),typeof V.path=="string"&&b.push(V.path);let cr=hh(M,V);a.onToolStart?.(M,cr,V),a.onToolCall?.(),d.recordStep({thought:P.hasThinking?`Executing: ${M}`:"",action:M,actionInput:V});let z=await wa(n,M,V,o);a.onToolEnd?.(M,z.success,z.error||z.output,z.duration,V);let Ie;if(z.success)Ie=ht(z.output,ga),d.recordObservation(Ie.slice(0,300)),w.push({tool:M,success:!0,summary:z.output.slice(0,150)});else{let Pe=z.error||"Unknown error",Fe=h.analyze(M,Pe,V);if(Ie=h.buildRecoveryMessage(Fe,Pe),d.recordObservation(`FAILED: ${Pe}`,`Recovery: ${Fe.strategy} \u2014 ${Fe.suggestion}`),o.info({tool:M,errorClass:Fe.errorClass,strategy:Fe.strategy},"Error recovery analysis"),w.push({tool:M,success:!1,summary:Pe.slice(0,150)}),Fe.autoRetry&&!d.isOverBudget()){a.onNotice?.("Auto-retrying (transient error)\u2026","retry");let Me=await wa(n,M,V,o);a.onToolEnd?.(M,Me.success,Me.output,Me.duration,V),Me.success&&(Ie=ht(Me.output,ga),d.recordObservation(Ie.slice(0,300),"Auto-retry succeeded"),w[w.length-1]={tool:M,success:!0,summary:Me.output.slice(0,150)})}}if(s.addToolMessage(Ie),z.success&&M==="read_file"&&typeof V.path=="string"&&i?.addFile(V.path,z.output),o.info({tool:M,success:z.success,durationMs:z.duration,retries:z.retries},"Tool executed"),!z.success&&mh(z.error)){a.onNotice?.("Critical tool failure \u2014 aborting subsequent tool executions.","warn");break}H>1&&U<H-1}d.isOverBudget()&&a.onNotice?.(`Reached max reasoning steps (${d.getConfig().maxSteps}). Wrapping up.`,"warn")}return S>=m&&!k&&a.onNotice?.(`Reached max iterations (${m}). Stopping.`,"warn"),o.info({summary:d.getTurnSummary(),agent:e.name},"Agentic turn completed"),{output:_,toolsUsed:be(y),toolResults:w,touchedFiles:be(b),iterations:S,success:!0,completedNaturally:k}}function be(t){return[...new Set(t)]}function ba(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 Sa(t){let{client:e,session:r,abortSignal:n,onChunk:s}=t,i="",o=null;for(let a=0;a<2;a++)try{i="";for await(let l of e.streamChat(r.getMessages(),n))i+=l,s?.(l);return r.addAssistantMessage(i||""),i}catch(l){if(o=l,l?.name==="AbortError"||n?.aborted)throw l;if(a===1)break}throw o||new Error("Text turn failed")}var tr=C(require("fs")),qn=C(require("os")),er=C(require("path"));function gh(){let t=[er.resolve(__dirname,"..","package.json"),er.resolve(__dirname,"..","..","package.json"),er.resolve(process.cwd(),"package.json")];for(let e of t)try{if(tr.existsSync(e)){let r=JSON.parse(tr.readFileSync(e,"utf-8"));if(r.version)return r.version}}catch{}return"0.0.0"}var _a=gh(),xa=process.stdout.isTTY===!0,yh=process.env.NO_COLOR!==void 0||process.env.TERM==="dumb";function Ee(t,e){return!xa||yh?t:`${e}${t}\x1B[0m`}var v={strong:t=>Ee(t,"\x1B[1;37m"),muted:t=>Ee(t,"\x1B[38;5;244m"),accent:t=>Ee(t,"\x1B[38;5;81m"),info:t=>Ee(t,"\x1B[38;5;110m"),success:t=>Ee(t,"\x1B[38;5;108m"),warning:t=>Ee(t,"\x1B[38;5;179m"),error:t=>Ee(t,"\x1B[38;5;167m")};function va(t,e){let r=e.replace(qn.homedir(),"~"),n="\u2500".repeat(88);return["",v.muted(n),` ${v.strong("HABLAS")} ${v.muted("single-agent engineering runtime")}`,` ${v.muted("version")} ${v.accent(_a)} ${v.muted("model")} ${v.accent(t)}`,` ${v.muted("workspace")} ${v.muted(r)}`,v.muted(n),` ${v.muted("\u203A Type naturally to get started")}`,` ${v.muted("\u203A /help \xB7 /status \xB7 /model \xB7 /provider \xB7 /exit")}`,""].join(`
236
294
  `)}function ka(t){return`
237
295
  ${v.muted("\u2500".repeat(28))} ${v.accent("Turn #"+t)} ${v.muted("\u2500".repeat(28))}`}function rt(){return`
238
296
  ${v.accent("Hablas")} ${v.muted("\xB7 response")}`}function Ca(){return["",` ${v.strong("Commands")}`,` ${v.muted("/help")} show help`,` ${v.muted("/status")} show current status`,` ${v.muted("/model")} show or switch the active model`,` ${v.muted("/models")} list available models`,` ${v.muted("/provider")} inspect or switch provider`,` ${v.muted("/history")} show recent turns`,` ${v.muted("/clear")} clear the session`,` ${v.muted("/workspace")} inspect the current workspace`,` ${v.muted("/doctor")} run diagnostics`,` ${v.muted("/version")} show version`,` ${v.muted("/about")} product identity`,` ${v.muted("/exit")} quit`,""].join(`
239
- `)}function $a(t){return["",` ${v.strong("Status")}`,` ${v.muted("provider")} ${v.info(t.provider)}`,` ${v.muted("model")} ${v.info(t.model)}`,` ${v.muted("workspace")} ${v.muted(t.workingDir.replace(qn.homedir(),"~"))}`,` ${v.muted("connected")} ${t.connected?v.success("yes"):v.error("no")}`,` ${v.muted("messages")} ${v.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${v.muted("tokens")} ${v.info(String(t.totalTokens))}`:"",""].filter(Boolean).join(`
240
- `)}function Q(t){return` ${v.info(t)}`}function Oe(t){return` ${v.success("\u2713")} ${t}`}function de(t){return` ${v.warning("\u26A0")} ${t}`}function Se(t){return` ${v.error("\u2717")} ${t}`}function Ta(){return` ${v.strong("Hablas")} ${v.accent("v"+_a)}`}function Aa(){return` ${v.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ea(t,e){return` ${v.muted("tool")} ${v.accent(t)} ${v.muted("\xB7")} ${e}`}function Oa(t,e,r){let n=t?v.success("\u2713"):v.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,140);return` ${n} ${s||(t?"done":"failed")} ${v.muted(`(${r}ms)`)}`}var tt=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){xa&&(this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${v.accent(this.frames[this.index])} ${v.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80)))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(Q(e))}};async function rr(t,e){let r=ua(t),n=await Qe(e.workingDir,e.config);if(e.session.updateSystemPrompt(et(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let u=new tt("Hablas is reasoning");u.start();let d=!1,h="";try{let p=await Sa({client:e.client,session:e.session,onChunk:c=>{d||(u.stop(),console.log(rt()),process.stdout.write(" "),d=!0),process.stdout.write(c),h+=c}});d?process.stdout.write(`
297
+ `)}function Ta(t){return["",` ${v.strong("Status")}`,` ${v.muted("provider")} ${v.info(t.provider)}`,` ${v.muted("model")} ${v.info(t.model)}`,` ${v.muted("workspace")} ${v.muted(t.workingDir.replace(qn.homedir(),"~"))}`,` ${v.muted("connected")} ${t.connected?v.success("yes"):v.error("no")}`,` ${v.muted("messages")} ${v.info(String(t.messageCount))}`,t.totalTokens!==void 0?` ${v.muted("tokens")} ${v.info(String(t.totalTokens))}`:"",""].filter(Boolean).join(`
298
+ `)}function Q(t){return` ${v.info(t)}`}function Oe(t){return` ${v.success("\u2713")} ${t}`}function de(t){return` ${v.warning("\u26A0")} ${t}`}function Se(t){return` ${v.error("\u2717")} ${t}`}function $a(){return` ${v.strong("Hablas")} ${v.accent("v"+_a)}`}function Aa(){return` ${v.strong("Hablas")} \u2014 single-agent terminal AI engineering runtime by Abdulmoin Hablas`}function Ea(t,e){return` ${v.muted("tool")} ${v.accent(t)} ${v.muted("\xB7")} ${e}`}function Oa(t,e,r){let n=t?v.success("\u2713"):v.error("\u2717"),s=e.replace(/\s+/g," ").trim().slice(0,140);return` ${n} ${s||(t?"done":"failed")} ${v.muted(`(${r}ms)`)}`}var tt=class{constructor(e){this.label=e}frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];index=0;timer=null;start(){xa&&(this.timer||(this.timer=setInterval(()=>{process.stdout.write(`\r ${v.accent(this.frames[this.index])} ${v.muted(this.label)}`),this.index=(this.index+1)%this.frames.length},80)))}stop(e){this.timer&&(clearInterval(this.timer),this.timer=null,process.stdout.write("\r\x1B[K")),e&&console.log(Q(e))}};async function rr(t,e){let r=ua(t),n=await Qe(e.workingDir,e.config);if(e.session.updateSystemPrompt(et(n,r.profile)),r.profile.continuity&&e.session.addUserMessage("[Execution note: continue from existing project context and do not restart from zero.]",{priority:"critical",tags:["runtime-note","continuity"]}),r.profile.oneStepDelivery&&e.session.addUserMessage("[Execution note: complete as much as possible in one pass with no unnecessary follow-up questions.]",{priority:"critical",tags:["runtime-note","one-step"]}),e.session.addUserMessage(t,{priority:"high",tags:[`kind:${r.profile.kind}`]}),!r.profile.needsTools){let u=new tt("Hablas is reasoning");u.start();let d=!1,h="";try{let p=await Sa({client:e.client,session:e.session,onChunk:c=>{d||(u.stop(),console.log(rt()),process.stdout.write(" "),d=!0),process.stdout.write(c),h+=c}});d?process.stdout.write(`
241
299
  `):(u.stop(),console.log(rt()),console.log(" "+p));return}catch(p){u.stop(),console.log(Se(p?.message||"Text turn failed"));return}}let s=yt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),i=wt(3),o=[],a={onAssistantText:async u=>{o.push(u),r.profile.kind!=="implementation"&&(console.log(rt()),console.log(" "+u))},onToolStart:(u,d)=>{console.log(Ea(u,d))},onToolEnd:(u,d,h,p)=>{console.log(Oa(d,h,p))},onNotice:(u,d)=>{console.log(d==="retry"?Q(`Retrying: ${u}`):Q(u))},onError:u=>{console.log(Se(u))},onToolCall:()=>e.onToolCall?.()},l=ba({autoMode:e.config.autoMode||!1,interactive:e.interactive,confirm:e.input?u=>e.input.confirm(u):void 0,confirmDangerous:e.input?u=>e.input.confirmDangerous(u):void 0}),f=await Nn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:a,safetyPolicy:l,reactEngine:s,errorRecovery:i,skipTools:!1});if(r.profile.kind==="implementation"&&f.toolsUsed.length>0&&o.length>0&&(console.log(rt()),console.log(" "+o[o.length-1])),r.profile.kind==="implementation"&&f.toolsUsed.length===0){e.session.addUserMessage("SYSTEM CORRECTION: This was an implementation request. You must use workspace tools, inspect files, and create or modify actual files instead of only replying with inline code. Retry now using tools.",{priority:"critical",tags:["system-correction","force-tools"]});let u=[];(await Nn({identity:{name:"Hablas",title:"Engineer",role:"hablas"},client:e.client,registry:e.registry,session:e.session,contextManager:e.contextManager,logger:e.logger,io:{...a,onAssistantText:async h=>{u.push(h)}},safetyPolicy:l,reactEngine:yt({thinkingEnabled:!0,selfEvalEnabled:!0,showThinking:!1,maxSteps:120,minConfidence:.6}),errorRecovery:wt(3),skipTools:!1})).toolsUsed.length===0?console.log(Se("Implementation request failed to enter a real tool-execution path. Refusing to present inline-code-only output as a completed result.")):u.length>0&&(console.log(rt()),console.log(" "+u[u.length-1]))}}var Un=C(require("fs")),Ra=C(require("path")),ne=C(require("os")),Ia=require("child_process");async function nr(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=Ra.join(ne.homedir(),".hablas");if(e.push({name:"Config directory",status:Un.existsSync(s)?"ok":"warn",message:Un.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=ne.homedir();if(process.platform!=="win32"){let a=(0,Ia.execSync)(`df -h "${i}" | tail -1`,{encoding:"utf-8"}).trim().split(/\s+/),l=a[3]||"unknown",f=a[4]||"?";e.push({name:"Disk space",status:parseInt(f)>90?"warn":"ok",message:`${l} available (${f} 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:`${ne.platform()} ${ne.arch()} \u2014 ${ne.cpus().length} cores, ${Math.round(ne.totalmem()/1024/1024/1024)}GB RAM`}),e}function sr(t){let e={ok:"\u2713",warn:"\u26A0",error:"\u2717"},r={ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m"},n="\x1B[0m",s="\x1B[2m",i=[""," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"," hablas doctor \u2014 System Diagnostics"," \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",""];for(let l of t){let f=`${r[l.status]}${e[l.status]}${n}`,u=l.name.padEnd(18);i.push(` ${f} ${u}${s}${l.message}${n}`)}let o=t.filter(l=>l.status==="error").length,a=t.filter(l=>l.status==="warn").length;return i.push(""),o>0?i.push(` ${r.error}${o} error(s) found \u2014 fix these for hablas to work properly${n}`):a>0?i.push(` ${r.warn}${a} warning(s) \u2014 hablas should work but check the items above${n}`):i.push(` ${r.ok}All checks passed \u2014 hablas is ready!${n}`),i.push(""),i.join(`
242
- `)}async function Pa(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ca());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Aa());return;case"/version":console.log(Ta());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===0){console.log(Q("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log($a({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(Q(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),je(e.config),console.log(Oe(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(de("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,f)=>console.log(` ${String(f+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(Q(`Provider: ${He(e.config)}`)),console.log(Q(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Oe("Connection OK"):Se("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=se.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=se.defaultModel);else if(i==="custom"){if(!s[1]){console.log(de("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(de("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Be(e.config);e.setClient(o),je(e.config),console.log(Oe(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await nr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(sr(i));return}case"/workspace":{console.log(""),console.log(Jt(Ye(e.workingDir))),console.log("");return}default:console.log(de(`Unknown command: ${n}`))}}async function La(t,e){is();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Be(t),s=new Ke(r,t),i=new Ge(t),o=await Qe(r,t),a=new Xe(et(o,gt("hello")),t.historySize),l=new Xt;console.log(va(t.model,r)),Ma.existsSync(Fa.join(r,".git"))||console.log(de("Not in a Git repository. Versioning and auto-sync features are limited."));let f=new tt("Connecting");f.start();let u=await n.checkConnection();if(f.stop(u?"ready":"offline"),u){let y=await n.listModels();console.log(Oe(`Connected \xB7 ${y.length} models available`))}else console.log(de(`Connection failed for ${He(t)}. You can still inspect local files and switch provider with /provider.`));console.log(Q("Hablas is ready. Single-agent runtime active.")),console.log("");let d=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(Q(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(de("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Pa(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}d+=1,console.log(ka(d)),c=new AbortController;try{await rr(w,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}})}catch(b){if(b?.name==="AbortError")continue;console.log(Se(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function Da(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Be(e),i=new Ke(n,e),o=new Ge(e),a=await Qe(n,e),l=new Xe(et(a,gt(t)),e.historySize);await rr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var ir=C(require("fs")),Re=C(require("path")),wh=[{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"}],bh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Sh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function _h(t,e){let r=[],n=e.split(`
300
+ `)}async function Pa(t,e){let r=t.trim().split(/\s+/),n=r[0],s=r.slice(1);switch(n){case"/help":console.log(Ca());return;case"/exit":case"/quit":return"quit";case"/about":console.log(Aa());return;case"/version":console.log($a());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===0){console.log(Q("No history yet."));return}console.log("");for(let a of o){let l=a.role==="user"?"you":a.role==="assistant"?"hablas":a.role;console.log(` ${l}: ${a.content.replace(/\s+/g," ").slice(0,160)}`)}console.log("");return}case"/status":{let i=await e.client.checkConnection();console.log(Ta({model:e.client.getModel(),provider:He(e.config),workingDir:e.workingDir,connected:i,messageCount:e.session.getMessageCount(),totalTokens:e.session.getTotalTokens()}));return}case"/model":{if(s.length===0){console.log(Q(`Current model: ${e.client.getModel()}`));return}let i=s.join(" ");e.config.model=i,e.client.setModel(i),je(e.config),console.log(Oe(`Model switched to ${i}`));return}case"/models":{let i=await e.client.listModels(),o=s.join(" ").toLowerCase(),a=o?i.filter(l=>l.toLowerCase().includes(o)):i;if(a.length===0){console.log(de("No matching models found."));return}console.log(""),a.slice(0,60).forEach((l,f)=>console.log(` ${String(f+1).padStart(2," ")}. ${l}`)),a.length>60&&console.log(` ... ${a.length-60} more`),console.log("");return}case"/provider":{let i=s[0];if(!i){console.log(Q(`Provider: ${He(e.config)}`)),console.log(Q(`Model: ${e.client.getModel()}`));return}if(i==="test"){let a=await e.client.checkConnection();console.log(a?Oe("Connection OK"):Se("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=se.apiUrl,s[1]&&(e.config.apiKey=s[1]),e.config.model||(e.config.model=se.defaultModel);else if(i==="custom"){if(!s[1]){console.log(de("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(de("Usage: /provider [ollama|nvidia|custom|test]"));return}let o=Be(e.config);e.setClient(o),je(e.config),console.log(Oe(`Provider switched to ${He(e.config)}`));return}case"/doctor":{let i=await nr({ollamaHost:e.config.ollamaHost,model:e.client.getModel(),provider:e.config.provider,apiUrl:e.config.apiUrl});console.log(sr(i));return}case"/workspace":{console.log(""),console.log(Jt(Ye(e.workingDir))),console.log("");return}default:console.log(de(`Unknown command: ${n}`))}}async function Da(t,e){is();let r=t.workingDirectory==="."?process.cwd():t.workingDirectory,n=Be(t),s=new Ke(r,t),i=new Ge(t),o=await Qe(r,t),a=new Xe(et(o,gt("hello")),t.historySize),l=new Xt;console.log(va(t.model,r)),Fa.existsSync(Ma.join(r,".git"))||console.log(de("Not in a Git repository. Versioning and auto-sync features are limited."));let f=new tt("Connecting");f.start();let u=await n.checkConnection();if(f.stop(u?"ready":"offline"),u){let y=await n.listModels();console.log(Oe(`Connected \xB7 ${y.length} models available`))}else console.log(de(`Connection failed for ${He(t)}. You can still inspect local files and switch provider with /provider.`));console.log(Q("Hablas is ready. Single-agent runtime active.")),console.log("");let d=0,h=0,p=Date.now(),c=new AbortController,m=0;for(process.on("SIGINT",()=>{let y=Date.now();y-m<1500&&(console.log(""),console.log(Q(`Session summary \xB7 turns=${d} \xB7 toolCalls=${h} \xB7 duration=${Math.round((Date.now()-p)/1e3)}s`)),l.close(),process.exit(0)),m=y,c.abort(),c=new AbortController,console.log(""),console.log(de("Operation cancelled \u2014 press Ctrl+C again to exit"))});;){let w=(await l.prompt(" \u203A ")).trim();if(w){if(w.startsWith("/")){if(await Pa(w,{config:t,client:n,setClient:_=>{n=_},session:a,workingDir:r})==="quit")break;continue}d+=1,console.log(ka(d)),c=new AbortController;try{await rr(w,{config:t,client:n,registry:s,contextManager:i,session:a,workingDir:r,logger:e,input:l,interactive:!0,onToolCall:()=>{h+=1}})}catch(b){if(b?.name==="AbortError")continue;console.log(Se(b?.message||"Turn failed")),e.error(b,"interactive turn failed")}}}l.close()}async function La(t,e,r){let n=e.workingDirectory==="."?process.cwd():e.workingDirectory,s=Be(e),i=new Ke(n,e),o=new Ge(e),a=await Qe(n,e),l=new Xe(et(a,gt(t)),e.historySize);await rr(t,{config:e,client:s,registry:i,contextManager:o,session:l,workingDir:n,logger:r,interactive:!1})}var ir=C(require("fs")),Re=C(require("path")),wh=[{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"}],bh=new Set(["node_modules",".git","dist","build",".next","__pycache__","venv",".venv","target","vendor",".cache"]),Sh=new Set([".png",".jpg",".jpeg",".gif",".svg",".ico",".woff",".woff2",".ttf",".eot",".mp4",".mp3",".zip",".tar",".gz",".lock"]);function _h(t,e){let r=[],n=e.split(`
243
301
  `);for(let{pattern:s,name:i,severity:o}of wh){s.lastIndex=0;let a;for(;(a=s.exec(e))!==null;){let f=e.substring(0,a.index).split(`
244
302
  `).length,u=n[f-1]||"";u.trim().startsWith("#")||u.trim().startsWith("//")||t.includes(".example")||t.includes(".sample")||r.push({severity:o,type:"secret",file:t,line:f,message:`Potential ${i} detected`,suggestion:"Move to environment variable or use a secrets manager. Add to .gitignore if needed."})}}return r}function xh(t,e){let r=[],n=e.split(`
245
303
  `),s=Re.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 ja(t,e=[]){try{let r=ir.readdirSync(t,{withFileTypes:!0});for(let n of r){if(bh.has(n.name))continue;let s=Re.join(t,n.name);if(n.isDirectory())ja(s,e);else if(n.isFile()){let i=Re.extname(n.name);Sh.has(i)||e.push(s)}}}catch{}return e}function Na(t){let e=Date.now(),r=ja(t),n=[];for(let o of r)try{let a=ir.readFileSync(o,"utf-8"),l=Re.relative(t,o),f=_h(l,a);n.push(...f);let u=xh(l,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 qa(t){let e=[];if(e.push(`
246
304
  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(`
247
305
  `)}var nt=C(require("fs")),Bn=C(require("path")),Ba=C(require("os")),vh=Bn.join(Ba.homedir(),".hablas"),Ua=Bn.join(vh,"analytics.json");function Ha(){try{if(nt.existsSync(Ua))return JSON.parse(nt.readFileSync(Ua,"utf-8"))}catch{}return kh()}function kh(){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 Wa(t){let e=[];e.push(`
248
306
  \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(`
249
- `)}var Va=C(require("readline"));var K="\x1B[36m",or="\x1B[32m",pe="\x1B[33m",M="\x1B[2m",he="\x1B[1m",x="\x1B[0m",Ch="\x1B[35m";function B(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function $h(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var St={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function za(t){let e=Va.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${he}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${x}`),console.log(`${he}${K} hablas \u2014 Setup Wizard${x}`),console.log(`${M} Configure your AI provider and model${x}`),console.log(`${he}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${x}`),console.log(),console.log(`${he} Choose your setup:${x}`),console.log(),console.log(` ${Ch}${he}1${x}. ${he}Hablas Integrated Engine${x} ${or}(instant \u2014 no setup needed)${x}`),console.log(` ${M}Pre-configured cloud AI, ready to use immediately${x}`),console.log(),console.log(` ${K}${he}2${x}. ${he}Custom Provider${x} ${M}(bring your own API key)${x}`),console.log(` ${M}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${x}`),console.log(),(await B(e,` ${M}Your choice (1-2):${x} `)).trim()){case"1":{t.provider=St.provider,t.apiUrl=St.apiUrl,t.apiKey=$h(),t.model=St.model,je(t),console.log(),console.log(`${or} \u2713 Hablas Integrated Engine activated!${x}`),console.log(`${M} Model: ${St.model}${x}`),console.log(`${M} API: ${St.apiUrl}${x}`),console.log(`${M} No API key needed \u2014 everything is pre-configured.${x}`);break}case"2":{switch(console.log(),console.log(`${M} Select your provider:${x}`),console.log(` ${K}a${x}. Ollama (local, free, private)`),console.log(` ${K}b${x}. OpenAI API`),console.log(` ${K}c${x}. Groq (fast, free tier)`),console.log(` ${K}d${x}. OpenRouter (many models)`),console.log(` ${K}e${x}. Together AI`),console.log(` ${K}f${x}. DeepSeek`),console.log(` ${K}g${x}. Custom OpenAI-compatible API`),console.log(` ${K}h${x}. NVIDIA NIM (powerful cloud models)`),console.log(),(await B(e,` ${M}Your choice (a-h):${x} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await B(e,` ${M}Ollama host [http://localhost:11434]:${x} `)).trim(),i=(await B(e,` ${M}Model [qwen2.5-coder:7b]:${x} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await B(e,` ${M}OpenAI API Key (sk-...):${x} `)).trim(),i=(await B(e,` ${M}Model [gpt-4o]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}Groq API Key (gsk_...):${x} `)).trim(),i=(await B(e,` ${M}Model [llama-3.3-70b-versatile]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}OpenRouter API Key (sk-or-...):${x} `)).trim(),i=(await B(e,` ${M}Model [anthropic/claude-3.5-sonnet]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}Together API Key:${x} `)).trim(),i=(await B(e,` ${M}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}DeepSeek API Key:${x} `)).trim(),i=(await B(e,` ${M}Model [deepseek-chat]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${M}API base URL:${x} `)).trim(),i=(await B(e,` ${M}API key (optional):${x} `)).trim(),o=(await B(e,` ${M}Model ID:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 URL is required \u2014 cancelled${x}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await B(e,` ${M}NVIDIA API Key (nvapi-...):${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),console.log(`${M} Get your key at: https://build.nvidia.com/${x}`),e.close();return}console.log(),console.log(`${M} Available NVIDIA models:${x}`),se.models.forEach((a,l)=>{console.log(` ${K}${l+1}${x}. ${a}`)}),console.log();let i=(await B(e,` ${M}Model number [1]:${x} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=se.apiUrl,t.apiKey=s,t.model=se.models[o]||se.defaultModel;break}default:console.log(`${pe} \u26A0 Invalid choice${x}`),e.close();return}je(t),console.log(),console.log(`${or} \u2713 Custom provider configured successfully${x}`),console.log(`${M} Provider: ${t.provider}${x}`),console.log(`${M} Model: ${t.model}${x}`);break}default:console.log(`${pe} \u26A0 Invalid choice \u2014 please select 1 or 2${x}`),e.close();return}console.log(),console.log(`${he}${or} \u2713 Setup complete!${x}`),console.log(`${M} Use ${K}hablas${x}${M} for interactive mode or ${K}hablas run "..."${x}${M} for one-shot execution.${x}`),console.log(),e.close()}var Ka=wo(),G=new ns;G.name("hablas").description(`Hablas CLI v${Ka} \u2014 single-agent engineering runtime for the terminal.`).version(Ka).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");G.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=G.opts(),r=De({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=xn(r);await Da(t,r,n)});G.command("doctor").description("Run system diagnostics").action(async()=>{let t=G.opts(),e=De({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await nr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(sr(r))});G.command("info").description("Show workspace information").action(async()=>{let t=G.opts(),e=De({project:t.project});console.log(""),console.log(Jt(Ye(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});G.command("security").description("Run a security scan on the current project").action(async()=>{let t=G.opts(),e=De({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(qa(Na(r)))});G.command("stats").description("Show local usage statistics").action(async()=>{console.log(Wa(Ha()))});G.action(async()=>{let t=G.opts(),e=De({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 za(e);return}let r=xn(e);await La(e,r)});G.parse();
307
+ `)}var Va=C(require("readline"));var K="\x1B[36m",or="\x1B[32m",pe="\x1B[33m",F="\x1B[2m",he="\x1B[1m",x="\x1B[0m",Ch="\x1B[35m";function B(t,e){return new Promise(r=>t.question(e,n=>r(n)))}function Th(){return["nvapi-","qJRIIcL3SbN6s91CK-","gk2DtzlHbUnaYvGJk","AoIohOTcABSY5lll","Kdwfj_fO_b55h"].join("")}var St={provider:"nvidia",apiUrl:"https://integrate.api.nvidia.com/v1",model:"stepfun-ai/step-3.7-flash",name:"Hablas Integrated Engine"};async function za(t){let e=Va.createInterface({input:process.stdin,output:process.stdout,terminal:!0});switch(console.log(),console.log(`${he}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${x}`),console.log(`${he}${K} hablas \u2014 Setup Wizard${x}`),console.log(`${F} Configure your AI provider and model${x}`),console.log(`${he}${K} \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501${x}`),console.log(),console.log(`${he} Choose your setup:${x}`),console.log(),console.log(` ${Ch}${he}1${x}. ${he}Hablas Integrated Engine${x} ${or}(instant \u2014 no setup needed)${x}`),console.log(` ${F}Pre-configured cloud AI, ready to use immediately${x}`),console.log(),console.log(` ${K}${he}2${x}. ${he}Custom Provider${x} ${F}(bring your own API key)${x}`),console.log(` ${F}Choose from Ollama, OpenAI, Groq, OpenRouter, and more${x}`),console.log(),(await B(e,` ${F}Your choice (1-2):${x} `)).trim()){case"1":{t.provider=St.provider,t.apiUrl=St.apiUrl,t.apiKey=Th(),t.model=St.model,je(t),console.log(),console.log(`${or} \u2713 Hablas Integrated Engine activated!${x}`),console.log(`${F} Model: ${St.model}${x}`),console.log(`${F} API: ${St.apiUrl}${x}`),console.log(`${F} No API key needed \u2014 everything is pre-configured.${x}`);break}case"2":{switch(console.log(),console.log(`${F} Select your provider:${x}`),console.log(` ${K}a${x}. Ollama (local, free, private)`),console.log(` ${K}b${x}. OpenAI API`),console.log(` ${K}c${x}. Groq (fast, free tier)`),console.log(` ${K}d${x}. OpenRouter (many models)`),console.log(` ${K}e${x}. Together AI`),console.log(` ${K}f${x}. DeepSeek`),console.log(` ${K}g${x}. Custom OpenAI-compatible API`),console.log(` ${K}h${x}. NVIDIA NIM (powerful cloud models)`),console.log(),(await B(e,` ${F}Your choice (a-h):${x} `)).trim().toLowerCase()){case"a":{t.provider="ollama";let s=(await B(e,` ${F}Ollama host [http://localhost:11434]:${x} `)).trim(),i=(await B(e,` ${F}Model [qwen2.5-coder:7b]:${x} `)).trim();t.ollamaHost=s||"http://localhost:11434",t.apiUrl="",t.apiKey="",t.model=i||"qwen2.5-coder:7b";break}case"b":{let s=(await B(e,` ${F}OpenAI API Key (sk-...):${x} `)).trim(),i=(await B(e,` ${F}Model [gpt-4o]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${F}Groq API Key (gsk_...):${x} `)).trim(),i=(await B(e,` ${F}Model [llama-3.3-70b-versatile]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${F}OpenRouter API Key (sk-or-...):${x} `)).trim(),i=(await B(e,` ${F}Model [anthropic/claude-3.5-sonnet]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${F}Together API Key:${x} `)).trim(),i=(await B(e,` ${F}Model [meta-llama/Llama-3.3-70B-Instruct-Turbo]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${F}DeepSeek API Key:${x} `)).trim(),i=(await B(e,` ${F}Model [deepseek-chat]:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),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 B(e,` ${F}API base URL:${x} `)).trim(),i=(await B(e,` ${F}API key (optional):${x} `)).trim(),o=(await B(e,` ${F}Model ID:${x} `)).trim();if(!s){console.log(`${pe} \u26A0 URL is required \u2014 cancelled${x}`),e.close();return}t.provider="custom",t.apiUrl=s,t.apiKey=i,o&&(t.model=o);break}case"h":{let s=(await B(e,` ${F}NVIDIA API Key (nvapi-...):${x} `)).trim();if(!s){console.log(`${pe} \u26A0 No key provided \u2014 cancelled${x}`),console.log(`${F} Get your key at: https://build.nvidia.com/${x}`),e.close();return}console.log(),console.log(`${F} Available NVIDIA models:${x}`),se.models.forEach((a,l)=>{console.log(` ${K}${l+1}${x}. ${a}`)}),console.log();let i=(await B(e,` ${F}Model number [1]:${x} `)).trim(),o=parseInt(i,10)-1;t.provider="nvidia",t.apiUrl=se.apiUrl,t.apiKey=s,t.model=se.models[o]||se.defaultModel;break}default:console.log(`${pe} \u26A0 Invalid choice${x}`),e.close();return}je(t),console.log(),console.log(`${or} \u2713 Custom provider configured successfully${x}`),console.log(`${F} Provider: ${t.provider}${x}`),console.log(`${F} Model: ${t.model}${x}`);break}default:console.log(`${pe} \u26A0 Invalid choice \u2014 please select 1 or 2${x}`),e.close();return}console.log(),console.log(`${he}${or} \u2713 Setup complete!${x}`),console.log(`${F} Use ${K}hablas${x}${F} for interactive mode or ${K}hablas run "..."${x}${F} for one-shot execution.${x}`),console.log(),e.close()}var Ka=wo(),G=new ns;G.name("hablas").description(`Hablas CLI v${Ka} \u2014 single-agent engineering runtime for the terminal.`).version(Ka).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");G.command("run <prompt>").description("Run a single prompt through the single-agent runtime").action(async t=>{let e=G.opts(),r=Le({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=xn(r);await La(t,r,n)});G.command("doctor").description("Run system diagnostics").action(async()=>{let t=G.opts(),e=Le({model:t.model,host:t.host,project:t.project,provider:t.provider,apiUrl:t.apiUrl,apiKey:t.apiKey}),r=await nr({ollamaHost:e.ollamaHost,model:e.model,provider:e.provider,apiUrl:e.apiUrl});console.log(sr(r))});G.command("info").description("Show workspace information").action(async()=>{let t=G.opts(),e=Le({project:t.project});console.log(""),console.log(Jt(Ye(e.workingDirectory==="."?process.cwd():e.workingDirectory))),console.log("")});G.command("security").description("Run a security scan on the current project").action(async()=>{let t=G.opts(),e=Le({project:t.project}),r=e.workingDirectory==="."?process.cwd():e.workingDirectory;console.log(qa(Na(r)))});G.command("stats").description("Show local usage statistics").action(async()=>{console.log(Wa(Ha()))});G.action(async()=>{let t=G.opts(),e=Le({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 za(e);return}let r=xn(e);await Da(e,r)});G.parse();