agentlogs 0.0.1

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 ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as x6}from"node:module";var k6=Object.create;var{getPrototypeOf:C6,defineProperty:g2,getOwnPropertyNames:T6}=Object;var v6=Object.prototype.hasOwnProperty;var b6=(_,Y,X)=>{X=_!=null?k6(C6(_)):{};let J=Y||!_||!_.__esModule?g2(X,"default",{value:_,enumerable:!0}):X;for(let H of T6(_))if(!v6.call(J,H))g2(J,H,{get:()=>_[H],enumerable:!0});return J};var P0=(_,Y)=>()=>(Y||_((Y={exports:{}}).exports,Y),Y.exports);var Z6=(_,Y)=>{for(var X in Y)g2(_,X,{get:Y[X],enumerable:!0,configurable:!0,set:(J)=>Y[X]=()=>J})};var Q2=x6(import.meta.url);var q2=P0((y6)=>{class m2 extends Error{constructor(_,Y,X){super(X);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=Y,this.exitCode=_,this.nestedError=void 0}}class y1 extends m2{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}y6.CommanderError=m2;y6.InvalidArgumentError=y1});var f2=P0((u6)=>{var{InvalidArgumentError:m6}=q2();class h1{constructor(_,Y){switch(this.description=Y||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,_[0]){case"<":this.required=!0,this._name=_.slice(1,-1);break;case"[":this.required=!1,this._name=_.slice(1,-1);break;default:this.required=!0,this._name=_;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(_,Y){if(Y===this.defaultValue||!Array.isArray(Y))return[_];return Y.push(_),Y}default(_,Y){return this.defaultValue=_,this.defaultValueDescription=Y,this}argParser(_){return this.parseArg=_,this}choices(_){return this.argChoices=_.slice(),this.parseArg=(Y,X)=>{if(!this.argChoices.includes(Y))throw new m6(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Y,X);return Y},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function c6(_){let Y=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+Y+">":"["+Y+"]"}u6.Argument=h1;u6.humanReadableArgName=c6});var c2=P0((n6)=>{var{humanReadableArgName:p6}=f2();class g1{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(_){this.helpWidth=this.helpWidth??_.helpWidth??80}visibleCommands(_){let Y=_.commands.filter((J)=>!J._hidden),X=_._getHelpCommand();if(X&&!X._hidden)Y.push(X);if(this.sortSubcommands)Y.sort((J,H)=>{return J.name().localeCompare(H.name())});return Y}compareOptions(_,Y){let X=(J)=>{return J.short?J.short.replace(/^-/,""):J.long.replace(/^--/,"")};return X(_).localeCompare(X(Y))}visibleOptions(_){let Y=_.options.filter((J)=>!J.hidden),X=_._getHelpOption();if(X&&!X.hidden){let J=X.short&&_._findOption(X.short),H=X.long&&_._findOption(X.long);if(!J&&!H)Y.push(X);else if(X.long&&!H)Y.push(_.createOption(X.long,X.description));else if(X.short&&!J)Y.push(_.createOption(X.short,X.description))}if(this.sortOptions)Y.sort(this.compareOptions);return Y}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let Y=[];for(let X=_.parent;X;X=X.parent){let J=X.options.filter((H)=>!H.hidden);Y.push(...J)}if(this.sortOptions)Y.sort(this.compareOptions);return Y}visibleArguments(_){if(_._argsDescription)_.registeredArguments.forEach((Y)=>{Y.description=Y.description||_._argsDescription[Y.name()]||""});if(_.registeredArguments.find((Y)=>Y.description))return _.registeredArguments;return[]}subcommandTerm(_){let Y=_.registeredArguments.map((X)=>p6(X)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+(Y?" "+Y:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,Y){return Y.visibleCommands(_).reduce((X,J)=>{return Math.max(X,this.displayWidth(Y.styleSubcommandTerm(Y.subcommandTerm(J))))},0)}longestOptionTermLength(_,Y){return Y.visibleOptions(_).reduce((X,J)=>{return Math.max(X,this.displayWidth(Y.styleOptionTerm(Y.optionTerm(J))))},0)}longestGlobalOptionTermLength(_,Y){return Y.visibleGlobalOptions(_).reduce((X,J)=>{return Math.max(X,this.displayWidth(Y.styleOptionTerm(Y.optionTerm(J))))},0)}longestArgumentTermLength(_,Y){return Y.visibleArguments(_).reduce((X,J)=>{return Math.max(X,this.displayWidth(Y.styleArgumentTerm(Y.argumentTerm(J))))},0)}commandUsage(_){let Y=_._name;if(_._aliases[0])Y=Y+"|"+_._aliases[0];let X="";for(let J=_.parent;J;J=J.parent)X=J.name()+" "+X;return X+Y+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let Y=[];if(_.argChoices)Y.push(`choices: ${_.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if(_.defaultValue!==void 0){if(_.required||_.optional||_.isBoolean()&&typeof _.defaultValue==="boolean")Y.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`)}if(_.presetArg!==void 0&&_.optional)Y.push(`preset: ${JSON.stringify(_.presetArg)}`);if(_.envVar!==void 0)Y.push(`env: ${_.envVar}`);if(Y.length>0){let X=`(${Y.join(", ")})`;if(_.description)return`${_.description} ${X}`;return X}return _.description}argumentDescription(_){let Y=[];if(_.argChoices)Y.push(`choices: ${_.argChoices.map((X)=>JSON.stringify(X)).join(", ")}`);if(_.defaultValue!==void 0)Y.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if(Y.length>0){let X=`(${Y.join(", ")})`;if(_.description)return`${_.description} ${X}`;return X}return _.description}formatItemList(_,Y,X){if(Y.length===0)return[];return[X.styleTitle(_),...Y,""]}groupItems(_,Y,X){let J=new Map;return _.forEach((H)=>{let Q=X(H);if(!J.has(Q))J.set(Q,[])}),Y.forEach((H)=>{let Q=X(H);if(!J.has(Q))J.set(Q,[]);J.get(Q).push(H)}),J}formatHelp(_,Y){let X=Y.padWidth(_,Y),J=Y.helpWidth??80;function H(L,V){return Y.formatItem(L,X,V,Y)}let Q=[`${Y.styleTitle("Usage:")} ${Y.styleUsage(Y.commandUsage(_))}`,""],q=Y.commandDescription(_);if(q.length>0)Q=Q.concat([Y.boxWrap(Y.styleCommandDescription(q),J),""]);let $=Y.visibleArguments(_).map((L)=>{return H(Y.styleArgumentTerm(Y.argumentTerm(L)),Y.styleArgumentDescription(Y.argumentDescription(L)))});if(Q=Q.concat(this.formatItemList("Arguments:",$,Y)),this.groupItems(_.options,Y.visibleOptions(_),(L)=>L.helpGroupHeading??"Options:").forEach((L,V)=>{let E=L.map((N)=>{return H(Y.styleOptionTerm(Y.optionTerm(N)),Y.styleOptionDescription(Y.optionDescription(N)))});Q=Q.concat(this.formatItemList(V,E,Y))}),Y.showGlobalOptions){let L=Y.visibleGlobalOptions(_).map((V)=>{return H(Y.styleOptionTerm(Y.optionTerm(V)),Y.styleOptionDescription(Y.optionDescription(V)))});Q=Q.concat(this.formatItemList("Global Options:",L,Y))}return this.groupItems(_.commands,Y.visibleCommands(_),(L)=>L.helpGroup()||"Commands:").forEach((L,V)=>{let E=L.map((N)=>{return H(Y.styleSubcommandTerm(Y.subcommandTerm(N)),Y.styleSubcommandDescription(Y.subcommandDescription(N)))});Q=Q.concat(this.formatItemList(V,E,Y))}),Q.join(`
3
+ `)}displayWidth(_){return m1(_).length}styleTitle(_){return _}styleUsage(_){return _.split(" ").map((Y)=>{if(Y==="[options]")return this.styleOptionText(Y);if(Y==="[command]")return this.styleSubcommandText(Y);if(Y[0]==="["||Y[0]==="<")return this.styleArgumentText(Y);return this.styleCommandText(Y)}).join(" ")}styleCommandDescription(_){return this.styleDescriptionText(_)}styleOptionDescription(_){return this.styleDescriptionText(_)}styleSubcommandDescription(_){return this.styleDescriptionText(_)}styleArgumentDescription(_){return this.styleDescriptionText(_)}styleDescriptionText(_){return _}styleOptionTerm(_){return this.styleOptionText(_)}styleSubcommandTerm(_){return _.split(" ").map((Y)=>{if(Y==="[options]")return this.styleOptionText(Y);if(Y[0]==="["||Y[0]==="<")return this.styleArgumentText(Y);return this.styleSubcommandText(Y)}).join(" ")}styleArgumentTerm(_){return this.styleArgumentText(_)}styleOptionText(_){return _}styleArgumentText(_){return _}styleSubcommandText(_){return _}styleCommandText(_){return _}padWidth(_,Y){return Math.max(Y.longestOptionTermLength(_,Y),Y.longestGlobalOptionTermLength(_,Y),Y.longestSubcommandTermLength(_,Y),Y.longestArgumentTermLength(_,Y))}preformatted(_){return/\n[^\S\r\n]/.test(_)}formatItem(_,Y,X,J){let Q=" ".repeat(2);if(!X)return Q+_;let q=_.padEnd(Y+_.length-J.displayWidth(_)),$=2,W=(this.helpWidth??80)-Y-$-2,L;if(W<this.minWidthToWrap||J.preformatted(X))L=X;else L=J.boxWrap(X,W).replace(/\n/g,`
4
+ `+" ".repeat(Y+$));return Q+q+" ".repeat($)+L.replace(/\n/g,`
5
+ ${Q}`)}boxWrap(_,Y){if(Y<this.minWidthToWrap)return _;let X=_.split(/\r\n|\n/),J=/[\s]*[^\s]+/g,H=[];return X.forEach((Q)=>{let q=Q.match(J);if(q===null){H.push("");return}let $=[q.shift()],G=this.displayWidth($[0]);q.forEach((W)=>{let L=this.displayWidth(W);if(G+L<=Y){$.push(W),G+=L;return}H.push($.join(""));let V=W.trimStart();$=[V],G=this.displayWidth(V)}),H.push($.join(""))}),H.join(`
6
+ `)}}function m1(_){let Y=/\x1b\[\d*(;\d*)*m/g;return _.replace(Y,"")}n6.Help=g1;n6.stripColor=m1});var u2=P0((a6)=>{var{InvalidArgumentError:o6}=q2();class u1{constructor(_,Y){this.flags=_,this.description=Y||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let X=s6(_);if(this.short=X.shortFlag,this.long=X.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(_,Y){return this.defaultValue=_,this.defaultValueDescription=Y,this}preset(_){return this.presetArg=_,this}conflicts(_){return this.conflictsWith=this.conflictsWith.concat(_),this}implies(_){let Y=_;if(typeof _==="string")Y={[_]:!0};return this.implied=Object.assign(this.implied||{},Y),this}env(_){return this.envVar=_,this}argParser(_){return this.parseArg=_,this}makeOptionMandatory(_=!0){return this.mandatory=!!_,this}hideHelp(_=!0){return this.hidden=!!_,this}_collectValue(_,Y){if(Y===this.defaultValue||!Array.isArray(Y))return[_];return Y.push(_),Y}choices(_){return this.argChoices=_.slice(),this.parseArg=(Y,X)=>{if(!this.argChoices.includes(Y))throw new o6(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(Y,X);return Y},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return c1(this.name().replace(/^no-/,""));return c1(this.name())}helpGroup(_){return this.helpGroupHeading=_,this}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class l1{constructor(_){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,_.forEach((Y)=>{if(Y.negate)this.negativeOptions.set(Y.attributeName(),Y);else this.positiveOptions.set(Y.attributeName(),Y)}),this.negativeOptions.forEach((Y,X)=>{if(this.positiveOptions.has(X))this.dualOptions.add(X)})}valueFromOption(_,Y){let X=Y.attributeName();if(!this.dualOptions.has(X))return!0;let J=this.negativeOptions.get(X).presetArg,H=J!==void 0?J:!1;return Y.negate===(H===_)}}function c1(_){return _.split("-").reduce((Y,X)=>{return Y+X[0].toUpperCase()+X.slice(1)})}function s6(_){let Y,X,J=/^-[^-]$/,H=/^--[^-]/,Q=_.split(/[ |,]+/).concat("guard");if(J.test(Q[0]))Y=Q.shift();if(H.test(Q[0]))X=Q.shift();if(!Y&&J.test(Q[0]))Y=Q.shift();if(!Y&&H.test(Q[0]))Y=X,X=Q.shift();if(Q[0].startsWith("-")){let q=Q[0],$=`option creation failed due to '${q}' in option flags '${_}'`;if(/^-[^-][^-]/.test(q))throw Error(`${$}
7
+ - a short flag is a single dash and a single character
8
+ - either use a single dash and a single character (for a short flag)
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(J.test(q))throw Error(`${$}
10
+ - too many short flags`);if(H.test(q))throw Error(`${$}
11
+ - too many long flags`);throw Error(`${$}
12
+ - unrecognised flag format`)}if(Y===void 0&&X===void 0)throw Error(`option creation failed due to no flags found in '${_}'.`);return{shortFlag:Y,longFlag:X}}a6.Option=u1;a6.DualOptions=l1});var d1=P0((X_)=>{function __(_,Y){if(Math.abs(_.length-Y.length)>3)return Math.max(_.length,Y.length);let X=[];for(let J=0;J<=_.length;J++)X[J]=[J];for(let J=0;J<=Y.length;J++)X[0][J]=J;for(let J=1;J<=Y.length;J++)for(let H=1;H<=_.length;H++){let Q=1;if(_[H-1]===Y[J-1])Q=0;else Q=1;if(X[H][J]=Math.min(X[H-1][J]+1,X[H][J-1]+1,X[H-1][J-1]+Q),H>1&&J>1&&_[H-1]===Y[J-2]&&_[H-2]===Y[J-1])X[H][J]=Math.min(X[H][J],X[H-2][J-2]+1)}return X[_.length][Y.length]}function Y_(_,Y){if(!Y||Y.length===0)return"";Y=Array.from(new Set(Y));let X=_.startsWith("--");if(X)_=_.slice(2),Y=Y.map((q)=>q.slice(2));let J=[],H=3,Q=0.4;if(Y.forEach((q)=>{if(q.length<=1)return;let $=__(_,q),G=Math.max(_.length,q.length);if((G-$)/G>Q){if($<H)H=$,J=[q];else if($===H)J.push(q)}}),J.sort((q,$)=>q.localeCompare($)),X)J=J.map((q)=>`--${q}`);if(J.length>1)return`
13
+ (Did you mean one of ${J.join(", ")}?)`;if(J.length===1)return`
14
+ (Did you mean ${J[0]}?)`;return""}X_.suggestSimilar=Y_});var r1=P0((L_)=>{var H_=Q2("node:events").EventEmitter,l2=Q2("node:child_process"),V0=Q2("node:path"),K2=Q2("node:fs"),g=Q2("node:process"),{Argument:Q_,humanReadableArgName:q_}=f2(),{CommanderError:d2}=q2(),{Help:$_,stripColor:G_}=c2(),{Option:p1,DualOptions:W_}=u2(),{suggestSimilar:n1}=d1();class n2 extends H_{constructor(_){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=_||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(Y)=>g.stdout.write(Y),writeErr:(Y)=>g.stderr.write(Y),outputError:(Y,X)=>X(Y),getOutHelpWidth:()=>g.stdout.isTTY?g.stdout.columns:void 0,getErrHelpWidth:()=>g.stderr.isTTY?g.stderr.columns:void 0,getOutHasColors:()=>p2()??(g.stdout.isTTY&&g.stdout.hasColors?.()),getErrHasColors:()=>p2()??(g.stderr.isTTY&&g.stderr.hasColors?.()),stripColor:(Y)=>G_(Y)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(_){return this._outputConfiguration=_._outputConfiguration,this._helpOption=_._helpOption,this._helpCommand=_._helpCommand,this._helpConfiguration=_._helpConfiguration,this._exitCallback=_._exitCallback,this._storeOptionsAsProperties=_._storeOptionsAsProperties,this._combineFlagAndOptionalValue=_._combineFlagAndOptionalValue,this._allowExcessArguments=_._allowExcessArguments,this._enablePositionalOptions=_._enablePositionalOptions,this._showHelpAfterError=_._showHelpAfterError,this._showSuggestionAfterError=_._showSuggestionAfterError,this}_getCommandAndAncestors(){let _=[];for(let Y=this;Y;Y=Y.parent)_.push(Y);return _}command(_,Y,X){let J=Y,H=X;if(typeof J==="object"&&J!==null)H=J,J=null;H=H||{};let[,Q,q]=_.match(/([^ ]+) *(.*)/),$=this.createCommand(Q);if(J)$.description(J),$._executableHandler=!0;if(H.isDefault)this._defaultCommandName=$._name;if($._hidden=!!(H.noHelp||H.hidden),$._executableFile=H.executableFile||null,q)$.arguments(q);if(this._registerCommand($),$.parent=this,$.copyInheritedSettings(this),J)return this;return $}createCommand(_){return new n2(_)}createHelp(){return Object.assign(new $_,this.configureHelp())}configureHelp(_){if(_===void 0)return this._helpConfiguration;return this._helpConfiguration=_,this}configureOutput(_){if(_===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,..._},this}showHelpAfterError(_=!0){if(typeof _!=="string")_=!!_;return this._showHelpAfterError=_,this}showSuggestionAfterError(_=!0){return this._showSuggestionAfterError=!!_,this}addCommand(_,Y){if(!_._name)throw Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);if(Y=Y||{},Y.isDefault)this._defaultCommandName=_._name;if(Y.noHelp||Y.hidden)_._hidden=!0;return this._registerCommand(_),_.parent=this,_._checkForBrokenPassThrough(),this}createArgument(_,Y){return new Q_(_,Y)}argument(_,Y,X,J){let H=this.createArgument(_,Y);if(typeof X==="function")H.default(J).argParser(X);else H.default(X);return this.addArgument(H),this}arguments(_){return _.trim().split(/ +/).forEach((Y)=>{this.argument(Y)}),this}addArgument(_){let Y=this.registeredArguments.slice(-1)[0];if(Y?.variadic)throw Error(`only the last argument can be variadic '${Y.name()}'`);if(_.required&&_.defaultValue!==void 0&&_.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${_.name()}'`);return this.registeredArguments.push(_),this}helpCommand(_,Y){if(typeof _==="boolean"){if(this._addImplicitHelpCommand=_,_&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let X=_??"help [command]",[,J,H]=X.match(/([^ ]+) *(.*)/),Q=Y??"display help for command",q=this.createCommand(J);if(q.helpOption(!1),H)q.arguments(H);if(Q)q.description(Q);if(this._addImplicitHelpCommand=!0,this._helpCommand=q,_||Y)this._initCommandGroup(q);return this}addHelpCommand(_,Y){if(typeof _!=="object")return this.helpCommand(_,Y),this;return this._addImplicitHelpCommand=!0,this._helpCommand=_,this._initCommandGroup(_),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(_,Y){let X=["preSubcommand","preAction","postAction"];if(!X.includes(_))throw Error(`Unexpected value for event passed to hook : '${_}'.
16
+ Expecting one of '${X.join("', '")}'`);if(this._lifeCycleHooks[_])this._lifeCycleHooks[_].push(Y);else this._lifeCycleHooks[_]=[Y];return this}exitOverride(_){if(_)this._exitCallback=_;else this._exitCallback=(Y)=>{if(Y.code!=="commander.executeSubCommandAsync")throw Y};return this}_exit(_,Y,X){if(this._exitCallback)this._exitCallback(new d2(_,Y,X));g.exit(_)}action(_){let Y=(X)=>{let J=this.registeredArguments.length,H=X.slice(0,J);if(this._storeOptionsAsProperties)H[J]=this;else H[J]=this.opts();return H.push(this),_.apply(this,H)};return this._actionHandler=Y,this}createOption(_,Y){return new p1(_,Y)}_callParseArg(_,Y,X,J){try{return _.parseArg(Y,X)}catch(H){if(H.code==="commander.invalidArgument"){let Q=`${J} ${H.message}`;this.error(Q,{exitCode:H.exitCode,code:H.code})}throw H}}_registerOption(_){let Y=_.short&&this._findOption(_.short)||_.long&&this._findOption(_.long);if(Y){let X=_.long&&this._findOption(_.long)?_.long:_.short;throw Error(`Cannot add option '${_.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${X}'
17
+ - already used by option '${Y.flags}'`)}this._initOptionGroup(_),this.options.push(_)}_registerCommand(_){let Y=(J)=>{return[J.name()].concat(J.aliases())},X=Y(_).find((J)=>this._findCommand(J));if(X){let J=Y(this._findCommand(X)).join("|"),H=Y(_).join("|");throw Error(`cannot add command '${H}' as already have command '${J}'`)}this._initCommandGroup(_),this.commands.push(_)}addOption(_){this._registerOption(_);let Y=_.name(),X=_.attributeName();if(_.negate){let H=_.long.replace(/^--no-/,"--");if(!this._findOption(H))this.setOptionValueWithSource(X,_.defaultValue===void 0?!0:_.defaultValue,"default")}else if(_.defaultValue!==void 0)this.setOptionValueWithSource(X,_.defaultValue,"default");let J=(H,Q,q)=>{if(H==null&&_.presetArg!==void 0)H=_.presetArg;let $=this.getOptionValue(X);if(H!==null&&_.parseArg)H=this._callParseArg(_,H,$,Q);else if(H!==null&&_.variadic)H=_._collectValue(H,$);if(H==null)if(_.negate)H=!1;else if(_.isBoolean()||_.optional)H=!0;else H="";this.setOptionValueWithSource(X,H,q)};if(this.on("option:"+Y,(H)=>{let Q=`error: option '${_.flags}' argument '${H}' is invalid.`;J(H,Q,"cli")}),_.envVar)this.on("optionEnv:"+Y,(H)=>{let Q=`error: option '${_.flags}' value '${H}' from env '${_.envVar}' is invalid.`;J(H,Q,"env")});return this}_optionEx(_,Y,X,J,H){if(typeof Y==="object"&&Y instanceof p1)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Q=this.createOption(Y,X);if(Q.makeOptionMandatory(!!_.mandatory),typeof J==="function")Q.default(H).argParser(J);else if(J instanceof RegExp){let q=J;J=($,G)=>{let W=q.exec($);return W?W[0]:G},Q.default(H).argParser(J)}else Q.default(J);return this.addOption(Q)}option(_,Y,X,J){return this._optionEx({},_,Y,X,J)}requiredOption(_,Y,X,J){return this._optionEx({mandatory:!0},_,Y,X,J)}combineFlagAndOptionalValue(_=!0){return this._combineFlagAndOptionalValue=!!_,this}allowUnknownOption(_=!0){return this._allowUnknownOption=!!_,this}allowExcessArguments(_=!0){return this._allowExcessArguments=!!_,this}enablePositionalOptions(_=!0){return this._enablePositionalOptions=!!_,this}passThroughOptions(_=!0){return this._passThroughOptions=!!_,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(_=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!_,this}getOptionValue(_){if(this._storeOptionsAsProperties)return this[_];return this._optionValues[_]}setOptionValue(_,Y){return this.setOptionValueWithSource(_,Y,void 0)}setOptionValueWithSource(_,Y,X){if(this._storeOptionsAsProperties)this[_]=Y;else this._optionValues[_]=Y;return this._optionValueSources[_]=X,this}getOptionValueSource(_){return this._optionValueSources[_]}getOptionValueSourceWithGlobals(_){let Y;return this._getCommandAndAncestors().forEach((X)=>{if(X.getOptionValueSource(_)!==void 0)Y=X.getOptionValueSource(_)}),Y}_prepareUserArgs(_,Y){if(_!==void 0&&!Array.isArray(_))throw Error("first parameter to parse must be array or undefined");if(Y=Y||{},_===void 0&&Y.from===void 0){if(g.versions?.electron)Y.from="electron";let J=g.execArgv??[];if(J.includes("-e")||J.includes("--eval")||J.includes("-p")||J.includes("--print"))Y.from="eval"}if(_===void 0)_=g.argv;this.rawArgs=_.slice();let X;switch(Y.from){case void 0:case"node":this._scriptPath=_[1],X=_.slice(2);break;case"electron":if(g.defaultApp)this._scriptPath=_[1],X=_.slice(2);else X=_.slice(1);break;case"user":X=_.slice(0);break;case"eval":X=_.slice(1);break;default:throw Error(`unexpected parse option { from: '${Y.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",X}parse(_,Y){this._prepareForParse();let X=this._prepareUserArgs(_,Y);return this._parseCommand([],X),this}async parseAsync(_,Y){this._prepareForParse();let X=this._prepareUserArgs(_,Y);return await this._parseCommand([],X),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
18
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(_,Y,X){if(K2.existsSync(_))return;let J=Y?`searched for local subcommand relative to directory '${Y}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",H=`'${_}' does not exist
19
+ - if '${X}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
+ - ${J}`;throw Error(H)}_executeSubCommand(_,Y){Y=Y.slice();let X=!1,J=[".js",".ts",".tsx",".mjs",".cjs"];function H(W,L){let V=V0.resolve(W,L);if(K2.existsSync(V))return V;if(J.includes(V0.extname(L)))return;let E=J.find((N)=>K2.existsSync(`${V}${N}`));if(E)return`${V}${E}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Q=_._executableFile||`${this._name}-${_._name}`,q=this._executableDir||"";if(this._scriptPath){let W;try{W=K2.realpathSync(this._scriptPath)}catch{W=this._scriptPath}q=V0.resolve(V0.dirname(W),q)}if(q){let W=H(q,Q);if(!W&&!_._executableFile&&this._scriptPath){let L=V0.basename(this._scriptPath,V0.extname(this._scriptPath));if(L!==this._name)W=H(q,`${L}-${_._name}`)}Q=W||Q}X=J.includes(V0.extname(Q));let $;if(g.platform!=="win32")if(X)Y.unshift(Q),Y=i1(g.execArgv).concat(Y),$=l2.spawn(g.argv[0],Y,{stdio:"inherit"});else $=l2.spawn(Q,Y,{stdio:"inherit"});else this._checkForMissingExecutable(Q,q,_._name),Y.unshift(Q),Y=i1(g.execArgv).concat(Y),$=l2.spawn(g.execPath,Y,{stdio:"inherit"});if(!$.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{g.on(L,()=>{if($.killed===!1&&$.exitCode===null)$.kill(L)})});let G=this._exitCallback;$.on("close",(W)=>{if(W=W??1,!G)g.exit(W);else G(new d2(W,"commander.executeSubCommandAsync","(close)"))}),$.on("error",(W)=>{if(W.code==="ENOENT")this._checkForMissingExecutable(Q,q,_._name);else if(W.code==="EACCES")throw Error(`'${Q}' not executable`);if(!G)g.exit(1);else{let L=new d2(1,"commander.executeSubCommandAsync","(error)");L.nestedError=W,G(L)}}),this.runningCommand=$}_dispatchSubcommand(_,Y,X){let J=this._findCommand(_);if(!J)this.help({error:!0});J._prepareForParse();let H;return H=this._chainOrCallSubCommandHook(H,J,"preSubcommand"),H=this._chainOrCall(H,()=>{if(J._executableHandler)this._executeSubCommand(J,Y.concat(X));else return J._parseCommand(Y,X)}),H}_dispatchHelpCommand(_){if(!_)this.help();let Y=this._findCommand(_);if(Y&&!Y._executableHandler)Y.help();return this._dispatchSubcommand(_,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((_,Y)=>{if(_.required&&this.args[Y]==null)this.missingArgument(_.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let _=(X,J,H)=>{let Q=J;if(J!==null&&X.parseArg){let q=`error: command-argument value '${J}' is invalid for argument '${X.name()}'.`;Q=this._callParseArg(X,J,H,q)}return Q};this._checkNumberOfArguments();let Y=[];this.registeredArguments.forEach((X,J)=>{let H=X.defaultValue;if(X.variadic){if(J<this.args.length){if(H=this.args.slice(J),X.parseArg)H=H.reduce((Q,q)=>{return _(X,q,Q)},X.defaultValue)}else if(H===void 0)H=[]}else if(J<this.args.length){if(H=this.args[J],X.parseArg)H=_(X,H,X.defaultValue)}Y[J]=H}),this.processedArgs=Y}_chainOrCall(_,Y){if(_?.then&&typeof _.then==="function")return _.then(()=>Y());return Y()}_chainOrCallHooks(_,Y){let X=_,J=[];if(this._getCommandAndAncestors().reverse().filter((H)=>H._lifeCycleHooks[Y]!==void 0).forEach((H)=>{H._lifeCycleHooks[Y].forEach((Q)=>{J.push({hookedCommand:H,callback:Q})})}),Y==="postAction")J.reverse();return J.forEach((H)=>{X=this._chainOrCall(X,()=>{return H.callback(H.hookedCommand,this)})}),X}_chainOrCallSubCommandHook(_,Y,X){let J=_;if(this._lifeCycleHooks[X]!==void 0)this._lifeCycleHooks[X].forEach((H)=>{J=this._chainOrCall(J,()=>{return H(this,Y)})});return J}_parseCommand(_,Y){let X=this.parseOptions(Y);if(this._parseOptionsEnv(),this._parseOptionsImplied(),_=_.concat(X.operands),Y=X.unknown,this.args=_.concat(Y),_&&this._findCommand(_[0]))return this._dispatchSubcommand(_[0],_.slice(1),Y);if(this._getHelpCommand()&&_[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(_[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(Y),this._dispatchSubcommand(this._defaultCommandName,_,Y);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(X.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let J=()=>{if(X.unknown.length>0)this.unknownOption(X.unknown[0])},H=`command:${this.name()}`;if(this._actionHandler){J(),this._processArguments();let Q;if(Q=this._chainOrCallHooks(Q,"preAction"),Q=this._chainOrCall(Q,()=>this._actionHandler(this.processedArgs)),this.parent)Q=this._chainOrCall(Q,()=>{this.parent.emit(H,_,Y)});return Q=this._chainOrCallHooks(Q,"postAction"),Q}if(this.parent?.listenerCount(H))J(),this._processArguments(),this.parent.emit(H,_,Y);else if(_.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",_,Y);if(this.listenerCount("command:*"))this.emit("command:*",_,Y);else if(this.commands.length)this.unknownCommand();else J(),this._processArguments()}else if(this.commands.length)J(),this.help({error:!0});else J(),this._processArguments()}_findCommand(_){if(!_)return;return this.commands.find((Y)=>Y._name===_||Y._aliases.includes(_))}_findOption(_){return this.options.find((Y)=>Y.is(_))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((_)=>{_.options.forEach((Y)=>{if(Y.mandatory&&_.getOptionValue(Y.attributeName())===void 0)_.missingMandatoryOptionValue(Y)})})}_checkForConflictingLocalOptions(){let _=this.options.filter((X)=>{let J=X.attributeName();if(this.getOptionValue(J)===void 0)return!1;return this.getOptionValueSource(J)!=="default"});_.filter((X)=>X.conflictsWith.length>0).forEach((X)=>{let J=_.find((H)=>X.conflictsWith.includes(H.attributeName()));if(J)this._conflictingOption(X,J)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((_)=>{_._checkForConflictingLocalOptions()})}parseOptions(_){let Y=[],X=[],J=Y;function H(W){return W.length>1&&W[0]==="-"}let Q=(W)=>{if(!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(W))return!1;return!this._getCommandAndAncestors().some((L)=>L.options.map((V)=>V.short).some((V)=>/^-\d$/.test(V)))},q=null,$=null,G=0;while(G<_.length||$){let W=$??_[G++];if($=null,W==="--"){if(J===X)J.push(W);J.push(..._.slice(G));break}if(q&&(!H(W)||Q(W))){this.emit(`option:${q.name()}`,W);continue}if(q=null,H(W)){let L=this._findOption(W);if(L){if(L.required){let V=_[G++];if(V===void 0)this.optionMissingArgument(L);this.emit(`option:${L.name()}`,V)}else if(L.optional){let V=null;if(G<_.length&&(!H(_[G])||Q(_[G])))V=_[G++];this.emit(`option:${L.name()}`,V)}else this.emit(`option:${L.name()}`);q=L.variadic?L:null;continue}}if(W.length>2&&W[0]==="-"&&W[1]!=="-"){let L=this._findOption(`-${W[1]}`);if(L){if(L.required||L.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${L.name()}`,W.slice(2));else this.emit(`option:${L.name()}`),$=`-${W.slice(2)}`;continue}}if(/^--[^=]+=/.test(W)){let L=W.indexOf("="),V=this._findOption(W.slice(0,L));if(V&&(V.required||V.optional)){this.emit(`option:${V.name()}`,W.slice(L+1));continue}}if(J===Y&&H(W)&&!(this.commands.length===0&&Q(W)))J=X;if((this._enablePositionalOptions||this._passThroughOptions)&&Y.length===0&&X.length===0){if(this._findCommand(W)){Y.push(W),X.push(..._.slice(G));break}else if(this._getHelpCommand()&&W===this._getHelpCommand().name()){Y.push(W,..._.slice(G));break}else if(this._defaultCommandName){X.push(W,..._.slice(G));break}}if(this._passThroughOptions){J.push(W,..._.slice(G));break}J.push(W)}return{operands:Y,unknown:X}}opts(){if(this._storeOptionsAsProperties){let _={},Y=this.options.length;for(let X=0;X<Y;X++){let J=this.options[X].attributeName();_[J]=J===this._versionOptionName?this._version:this[J]}return _}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((_,Y)=>Object.assign(_,Y.opts()),{})}error(_,Y){if(this._outputConfiguration.outputError(`${_}
22
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
+ `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
24
+ `),this.outputHelp({error:!0});let X=Y||{},J=X.exitCode||1,H=X.code||"commander.error";this._exit(J,H,_)}_parseOptionsEnv(){this.options.forEach((_)=>{if(_.envVar&&_.envVar in g.env){let Y=_.attributeName();if(this.getOptionValue(Y)===void 0||["default","config","env"].includes(this.getOptionValueSource(Y)))if(_.required||_.optional)this.emit(`optionEnv:${_.name()}`,g.env[_.envVar]);else this.emit(`optionEnv:${_.name()}`)}})}_parseOptionsImplied(){let _=new W_(this.options),Y=(X)=>{return this.getOptionValue(X)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(X))};this.options.filter((X)=>X.implied!==void 0&&Y(X.attributeName())&&_.valueFromOption(this.getOptionValue(X.attributeName()),X)).forEach((X)=>{Object.keys(X.implied).filter((J)=>!Y(J)).forEach((J)=>{this.setOptionValueWithSource(J,X.implied[J],"implied")})})}missingArgument(_){let Y=`error: missing required argument '${_}'`;this.error(Y,{code:"commander.missingArgument"})}optionMissingArgument(_){let Y=`error: option '${_.flags}' argument missing`;this.error(Y,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(_){let Y=`error: required option '${_.flags}' not specified`;this.error(Y,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(_,Y){let X=(Q)=>{let q=Q.attributeName(),$=this.getOptionValue(q),G=this.options.find((L)=>L.negate&&q===L.attributeName()),W=this.options.find((L)=>!L.negate&&q===L.attributeName());if(G&&(G.presetArg===void 0&&$===!1||G.presetArg!==void 0&&$===G.presetArg))return G;return W||Q},J=(Q)=>{let q=X(Q),$=q.attributeName();if(this.getOptionValueSource($)==="env")return`environment variable '${q.envVar}'`;return`option '${q.flags}'`},H=`error: ${J(_)} cannot be used with ${J(Y)}`;this.error(H,{code:"commander.conflictingOption"})}unknownOption(_){if(this._allowUnknownOption)return;let Y="";if(_.startsWith("--")&&this._showSuggestionAfterError){let J=[],H=this;do{let Q=H.createHelp().visibleOptions(H).filter((q)=>q.long).map((q)=>q.long);J=J.concat(Q),H=H.parent}while(H&&!H._enablePositionalOptions);Y=n1(_,J)}let X=`error: unknown option '${_}'${Y}`;this.error(X,{code:"commander.unknownOption"})}_excessArguments(_){if(this._allowExcessArguments)return;let Y=this.registeredArguments.length,X=Y===1?"":"s",H=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${Y} argument${X} but got ${_.length}.`;this.error(H,{code:"commander.excessArguments"})}unknownCommand(){let _=this.args[0],Y="";if(this._showSuggestionAfterError){let J=[];this.createHelp().visibleCommands(this).forEach((H)=>{if(J.push(H.name()),H.alias())J.push(H.alias())}),Y=n1(_,J)}let X=`error: unknown command '${_}'${Y}`;this.error(X,{code:"commander.unknownCommand"})}version(_,Y,X){if(_===void 0)return this._version;this._version=_,Y=Y||"-V, --version",X=X||"output the version number";let J=this.createOption(Y,X);return this._versionOptionName=J.attributeName(),this._registerOption(J),this.on("option:"+J.name(),()=>{this._outputConfiguration.writeOut(`${_}
25
+ `),this._exit(0,"commander.version",_)}),this}description(_,Y){if(_===void 0&&Y===void 0)return this._description;if(this._description=_,Y)this._argsDescription=Y;return this}summary(_){if(_===void 0)return this._summary;return this._summary=_,this}alias(_){if(_===void 0)return this._aliases[0];let Y=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)Y=this.commands[this.commands.length-1];if(_===Y._name)throw Error("Command alias can't be the same as its name");let X=this.parent?._findCommand(_);if(X){let J=[X.name()].concat(X.aliases()).join("|");throw Error(`cannot add alias '${_}' to command '${this.name()}' as already have command '${J}'`)}return Y._aliases.push(_),this}aliases(_){if(_===void 0)return this._aliases;return _.forEach((Y)=>this.alias(Y)),this}usage(_){if(_===void 0){if(this._usage)return this._usage;let Y=this.registeredArguments.map((X)=>{return q_(X)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?Y:[]).join(" ")}return this._usage=_,this}name(_){if(_===void 0)return this._name;return this._name=_,this}helpGroup(_){if(_===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=_,this}commandsGroup(_){if(_===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=_,this}optionsGroup(_){if(_===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=_,this}_initOptionGroup(_){if(this._defaultOptionGroup&&!_.helpGroupHeading)_.helpGroup(this._defaultOptionGroup)}_initCommandGroup(_){if(this._defaultCommandGroup&&!_.helpGroup())_.helpGroup(this._defaultCommandGroup)}nameFromFilename(_){return this._name=V0.basename(_,V0.extname(_)),this}executableDir(_){if(_===void 0)return this._executableDir;return this._executableDir=_,this}helpInformation(_){let Y=this.createHelp(),X=this._getOutputContext(_);Y.prepareContext({error:X.error,helpWidth:X.helpWidth,outputHasColors:X.hasColors});let J=Y.formatHelp(this,Y);if(X.hasColors)return J;return this._outputConfiguration.stripColor(J)}_getOutputContext(_){_=_||{};let Y=!!_.error,X,J,H;if(Y)X=(q)=>this._outputConfiguration.writeErr(q),J=this._outputConfiguration.getErrHasColors(),H=this._outputConfiguration.getErrHelpWidth();else X=(q)=>this._outputConfiguration.writeOut(q),J=this._outputConfiguration.getOutHasColors(),H=this._outputConfiguration.getOutHelpWidth();return{error:Y,write:(q)=>{if(!J)q=this._outputConfiguration.stripColor(q);return X(q)},hasColors:J,helpWidth:H}}outputHelp(_){let Y;if(typeof _==="function")Y=_,_=void 0;let X=this._getOutputContext(_),J={error:X.error,write:X.write,command:this};this._getCommandAndAncestors().reverse().forEach((Q)=>Q.emit("beforeAllHelp",J)),this.emit("beforeHelp",J);let H=this.helpInformation({error:X.error});if(Y){if(H=Y(H),typeof H!=="string"&&!Buffer.isBuffer(H))throw Error("outputHelp callback must return a string or a Buffer")}if(X.write(H),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",J),this._getCommandAndAncestors().forEach((Q)=>Q.emit("afterAllHelp",J))}helpOption(_,Y){if(typeof _==="boolean"){if(_){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(_??"-h, --help",Y??"display help for command"),_||Y)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(_){return this._helpOption=_,this._initOptionGroup(_),this}help(_){this.outputHelp(_);let Y=Number(g.exitCode??0);if(Y===0&&_&&typeof _!=="function"&&_.error)Y=1;this._exit(Y,"commander.help","(outputHelp)")}addHelpText(_,Y){let X=["beforeAll","before","after","afterAll"];if(!X.includes(_))throw Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${X.join("', '")}'`);let J=`${_}Help`;return this.on(J,(H)=>{let Q;if(typeof Y==="function")Q=Y({error:H.error,command:H.command});else Q=Y;if(Q)H.write(`${Q}
27
+ `)}),this}_outputHelpIfRequested(_){let Y=this._getHelpOption();if(Y&&_.find((J)=>Y.is(J)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function i1(_){return _.map((Y)=>{if(!Y.startsWith("--inspect"))return Y;let X,J="127.0.0.1",H="9229",Q;if((Q=Y.match(/^(--inspect(-brk)?)$/))!==null)X=Q[1];else if((Q=Y.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(X=Q[1],/^\d+$/.test(Q[3]))H=Q[3];else J=Q[3];else if((Q=Y.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)X=Q[1],J=Q[3],H=Q[4];if(X&&H!=="0")return`${X}=${J}:${parseInt(H)+1}`;return Y})}function p2(){if(g.env.NO_COLOR||g.env.FORCE_COLOR==="0"||g.env.FORCE_COLOR==="false")return!1;if(g.env.FORCE_COLOR||g.env.CLICOLOR_FORCE!==void 0)return!0;return}L_.Command=n2;L_.useColor=p2});var t1=P0((E_)=>{var{Argument:o1}=f2(),{Command:i2}=r1(),{CommanderError:V_,InvalidArgumentError:s1}=q2(),{Help:U_}=c2(),{Option:a1}=u2();E_.program=new i2;E_.createCommand=(_)=>new i2(_);E_.createOption=(_,Y)=>new a1(_,Y);E_.createArgument=(_,Y)=>new o1(_,Y);E_.Command=i2;E_.Option=a1;E_.Argument=o1;E_.Help=U_;E_.CommanderError=V_;E_.InvalidArgumentError=s1;E_.InvalidOptionArgumentError=s1});var e1=b6(t1(),1),{program:s5,createCommand:a5,createArgument:t5,createOption:e5,CommanderError:_J,InvalidArgumentError:YJ,InvalidOptionArgumentError:XJ,Command:_4,Argument:JJ,Option:HJ,Help:QJ}=e1.default;import{appendFileSync as v_,mkdirSync as b_}from"fs";import{dirname as Z_}from"path";import{existsSync as O_,readFileSync as I_}from"fs";import{homedir as P_}from"os";import{dirname as k_,resolve as r2}from"path";function C_(){let _=process.cwd(),Y=10,X=0;while(X<Y){let J=r2(_,"package.json");if(O_(J))try{if(JSON.parse(I_(J,"utf-8")).workspaces)return _}catch{}let H=k_(_);if(H===_)break;_=H,X++}throw Error("Could not find monorepo root (no package.json with workspaces field found)")}function T_(){return r2(C_(),"logs")}function D2(){return r2(T_(),"dev.log")}function k0(_){let Y=P_();if(_.startsWith(Y))return _.replace(Y,"~");return _}function j2(_){if(_==="."||_===null)return"";return _}var Y4=!1;function x_(_){if(_===void 0||_===null)return _;if(process.env.DEBUG_PAYLOADS!=="true"){if(!Y4)return Y4=!0,"[payload logging disabled - set DEBUG_PAYLOADS=true to enable]";return}if(typeof _==="object"){let X=JSON.stringify(_),J=Math.round(X.length/1024),H=X.includes('"isImage":true')||X.includes('"isImage": true')||X.length>1e4&&/[A-Za-z0-9+/]{100,}/.test(X);if(H||X.length>1e4)return`[payload: ${J}KB${H?", contains binary data":""}]`}return _}class X4{component;logToFile;logFilePath;disableConsole;constructor(_){this.component=_.component,this.disableConsole=_.disableConsole??!1;let Y=typeof process<"u"&&!!process.versions?.node;this.logToFile=_.logToFile??(Y&&!1);try{if(Y&&this.logToFile)this.logFilePath=_.logFilePath??D2();else this.logFilePath="",this.logToFile=!1}catch(X){if(this.logToFile=!1,this.logFilePath="",process.env.DEBUG)console.warn(`[${this.component}] Could not initialize file logging:`,X)}if(process.env.DEBUG)console.log(`[${this.component}] Logger config:`,{logToFile:this.logToFile,logFilePath:this.logFilePath,cwd:process.cwd(),NODE_ENV:"production"});if(this.logToFile)try{let X=Z_(this.logFilePath);b_(X,{recursive:!0})}catch(X){if(process.env.DEBUG)console.error(`[${this.component}] Failed to create logs directory:`,X)}}log(_,Y,X){let J=new Date,Q=`[${`${String(J.getMonth()+1).padStart(2,"0")}-${String(J.getDate()).padStart(2,"0")} ${String(J.getHours()).padStart(2,"0")}:${String(J.getMinutes()).padStart(2,"0")}:${String(J.getSeconds()).padStart(2,"0")}`}] [${this.component}] [${_}] ${Y}`,q=_==="ERROR"?console.error:_==="WARN"?console.warn:console.log,$=x_(X);if(!this.disableConsole){if(q(Q),$!==void 0){let G=typeof $==="object"?JSON.stringify($,null,2):String($);q(` ${G}`)}}if(this.logToFile)try{let G=Q+`
28
+ `;if($!==void 0){let W=typeof $==="object"?JSON.stringify($):String($);G+=` ${W}
29
+ `}v_(this.logFilePath,G)}catch{}}debug(_,Y){if(process.env.DEBUG)this.log("DEBUG",_,Y)}info(_,Y){this.log("INFO",_,Y)}warn(_,Y){this.log("WARN",_,Y)}error(_,Y){this.log("ERROR",_,Y)}}function J4(_,Y){return new X4({component:_,...Y})}import{existsSync as H4,mkdirSync as y_,readFileSync as h_,writeFileSync as g_}from"fs";import{homedir as m_}from"os";import{join as Q4}from"path";import{Entry as a2}from"@napi-rs/keyring";var N2="production";var o2=Q4(m_(),".config","agentlogs"),s2=Q4(o2,"config.json"),t2="agentlogs-cli";function e2(_){return N2==="production"?`prod:${_}`:`dev:${_}`}function q4(){if(!H4(o2))y_(o2,{recursive:!0})}function t(){if(q4(),!H4(s2))return{};try{let _=h_(s2,"utf-8");return JSON.parse(_)}catch(_){return console.error("Failed to read config file:",_),{}}}function $4(_){q4();try{g_(s2,JSON.stringify(_,null,2),"utf-8")}catch(Y){throw console.error("Failed to write config file:",Y),Y}}function e(){try{let _=t();if(!_.user?.email)return null;let Y=e2(_.user.email);return new a2(t2,Y).getPassword()}catch{return null}}function G4(_,Y){try{let X=e2(_);new a2(t2,X).setPassword(Y)}catch(X){throw console.error("Failed to store token in keychain:",X),X}}function W4(){try{let _=t();if(!_.user?.email)return;let Y=e2(_.user.email);new a2(t2,Y).deletePassword()}catch{}}import{createHash as CY}from"crypto";import{existsSync as E1,readFileSync as TY}from"fs";import{dirname as vY,isAbsolute as bY,resolve as ZY}from"path";import M9 from"node:crypto";var B={};Z6(B,{void:()=>S8,util:()=>b,unknown:()=>N8,union:()=>I8,undefined:()=>K8,tuple:()=>C8,transformer:()=>c8,symbol:()=>f8,string:()=>f4,strictObject:()=>O8,setErrorMap:()=>l_,set:()=>b8,record:()=>T8,quotelessJson:()=>c_,promise:()=>m8,preprocess:()=>d8,pipeline:()=>p8,ostring:()=>n8,optional:()=>u8,onumber:()=>i8,oboolean:()=>r8,objectUtil:()=>_1,object:()=>z8,number:()=>K4,nullable:()=>l8,null:()=>D8,never:()=>A8,nativeEnum:()=>g8,nan:()=>E8,map:()=>v8,makeIssue:()=>$2,literal:()=>y8,lazy:()=>x8,late:()=>V8,isValid:()=>f0,isDirty:()=>S2,isAsync:()=>h0,isAborted:()=>A2,intersection:()=>k8,instanceof:()=>U8,getParsedType:()=>$0,getErrorMap:()=>y0,function:()=>Z8,enum:()=>h8,effect:()=>c8,discriminatedUnion:()=>P8,defaultErrorMap:()=>U0,datetimeRegex:()=>E4,date:()=>R8,custom:()=>R4,coerce:()=>o8,boolean:()=>D4,bigint:()=>F8,array:()=>w8,any:()=>j8,addIssueToContext:()=>f,ZodVoid:()=>W2,ZodUnknown:()=>K0,ZodUnion:()=>d0,ZodUndefined:()=>u0,ZodType:()=>T,ZodTuple:()=>W0,ZodTransformer:()=>H0,ZodSymbol:()=>G2,ZodString:()=>_0,ZodSet:()=>b0,ZodSchema:()=>T,ZodRecord:()=>L2,ZodReadonly:()=>a0,ZodPromise:()=>Z0,ZodPipeline:()=>V2,ZodParsedType:()=>F,ZodOptional:()=>X0,ZodObject:()=>l,ZodNumber:()=>D0,ZodNullable:()=>F0,ZodNull:()=>l0,ZodNever:()=>G0,ZodNativeEnum:()=>r0,ZodNaN:()=>M2,ZodMap:()=>B2,ZodLiteral:()=>i0,ZodLazy:()=>n0,ZodIssueCode:()=>U,ZodIntersection:()=>p0,ZodFunction:()=>m0,ZodFirstPartyTypeKind:()=>w,ZodError:()=>o,ZodEnum:()=>N0,ZodEffects:()=>H0,ZodDiscriminatedUnion:()=>w2,ZodDefault:()=>o0,ZodDate:()=>T0,ZodCatch:()=>s0,ZodBranded:()=>z2,ZodBoolean:()=>c0,ZodBigInt:()=>j0,ZodArray:()=>Y0,ZodAny:()=>v0,Schema:()=>T,ParseStatus:()=>n,OK:()=>i,NEVER:()=>s8,INVALID:()=>A,EMPTY_PATH:()=>d_,DIRTY:()=>C0,BRAND:()=>M8});var b;(function(_){_.assertEqual=(H)=>{};function Y(H){}_.assertIs=Y;function X(H){throw Error()}_.assertNever=X,_.arrayToEnum=(H)=>{let Q={};for(let q of H)Q[q]=q;return Q},_.getValidEnumValues=(H)=>{let Q=_.objectKeys(H).filter(($)=>typeof H[H[$]]!=="number"),q={};for(let $ of Q)q[$]=H[$];return _.objectValues(q)},_.objectValues=(H)=>{return _.objectKeys(H).map(function(Q){return H[Q]})},_.objectKeys=typeof Object.keys==="function"?(H)=>Object.keys(H):(H)=>{let Q=[];for(let q in H)if(Object.prototype.hasOwnProperty.call(H,q))Q.push(q);return Q},_.find=(H,Q)=>{for(let q of H)if(Q(q))return q;return},_.isInteger=typeof Number.isInteger==="function"?(H)=>Number.isInteger(H):(H)=>typeof H==="number"&&Number.isFinite(H)&&Math.floor(H)===H;function J(H,Q=" | "){return H.map((q)=>typeof q==="string"?`'${q}'`:q).join(Q)}_.joinValues=J,_.jsonStringifyReplacer=(H,Q)=>{if(typeof Q==="bigint")return Q.toString();return Q}})(b||(b={}));var _1;(function(_){_.mergeShapes=(Y,X)=>{return{...Y,...X}}})(_1||(_1={}));var F=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),$0=(_)=>{switch(typeof _){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(_)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":if(Array.isArray(_))return F.array;if(_===null)return F.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return F.promise;if(typeof Map<"u"&&_ instanceof Map)return F.map;if(typeof Set<"u"&&_ instanceof Set)return F.set;if(typeof Date<"u"&&_ instanceof Date)return F.date;return F.object;default:return F.unknown}};var U=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),c_=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class o extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let Y=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Y);else this.__proto__=Y;this.name="ZodError",this.issues=_}format(_){let Y=_||function(H){return H.message},X={_errors:[]},J=(H)=>{for(let Q of H.issues)if(Q.code==="invalid_union")Q.unionErrors.map(J);else if(Q.code==="invalid_return_type")J(Q.returnTypeError);else if(Q.code==="invalid_arguments")J(Q.argumentsError);else if(Q.path.length===0)X._errors.push(Y(Q));else{let q=X,$=0;while($<Q.path.length){let G=Q.path[$];if($!==Q.path.length-1)q[G]=q[G]||{_errors:[]};else q[G]=q[G]||{_errors:[]},q[G]._errors.push(Y(Q));q=q[G],$++}}};return J(this),X}static assert(_){if(!(_ instanceof o))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(Y)=>Y.message){let Y={},X=[];for(let J of this.issues)if(J.path.length>0){let H=J.path[0];Y[H]=Y[H]||[],Y[H].push(_(J))}else X.push(_(J));return{formErrors:X,fieldErrors:Y}}get formErrors(){return this.flatten()}}o.create=(_)=>{return new o(_)};var u_=(_,Y)=>{let X;switch(_.code){case U.invalid_type:if(_.received===F.undefined)X="Required";else X=`Expected ${_.expected}, received ${_.received}`;break;case U.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify(_.expected,b.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:X=`Unrecognized key(s) in object: ${b.joinValues(_.keys,", ")}`;break;case U.invalid_union:X="Invalid input";break;case U.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${b.joinValues(_.options)}`;break;case U.invalid_enum_value:X=`Invalid enum value. Expected ${b.joinValues(_.options)}, received '${_.received}'`;break;case U.invalid_arguments:X="Invalid function arguments";break;case U.invalid_return_type:X="Invalid function return type";break;case U.invalid_date:X="Invalid date";break;case U.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(X=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)X=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)X=`Invalid input: must end with "${_.validation.endsWith}"`;else b.assertNever(_.validation);else if(_.validation!=="regex")X=`Invalid ${_.validation}`;else X="Invalid";break;case U.too_small:if(_.type==="array")X=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")X=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")X=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")X=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")X=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else X="Invalid input";break;case U.too_big:if(_.type==="array")X=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")X=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")X=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")X=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")X=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else X="Invalid input";break;case U.custom:X="Invalid input";break;case U.invalid_intersection_types:X="Intersection results could not be merged";break;case U.not_multiple_of:X=`Number must be a multiple of ${_.multipleOf}`;break;case U.not_finite:X="Number must be finite";break;default:X=Y.defaultError,b.assertNever(_)}return{message:X}},U0=u_;var L4=U0;function l_(_){L4=_}function y0(){return L4}var $2=(_)=>{let{data:Y,path:X,errorMaps:J,issueData:H}=_,Q=[...X,...H.path||[]],q={...H,path:Q};if(H.message!==void 0)return{...H,path:Q,message:H.message};let $="",G=J.filter((W)=>!!W).slice().reverse();for(let W of G)$=W(q,{data:Y,defaultError:$}).message;return{...H,path:Q,message:$}},d_=[];function f(_,Y){let X=y0(),J=$2({issueData:Y,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,X,X===U0?void 0:U0].filter((H)=>!!H)});_.common.issues.push(J)}class n{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,Y){let X=[];for(let J of Y){if(J.status==="aborted")return A;if(J.status==="dirty")_.dirty();X.push(J.value)}return{status:_.value,value:X}}static async mergeObjectAsync(_,Y){let X=[];for(let J of Y){let H=await J.key,Q=await J.value;X.push({key:H,value:Q})}return n.mergeObjectSync(_,X)}static mergeObjectSync(_,Y){let X={};for(let J of Y){let{key:H,value:Q}=J;if(H.status==="aborted")return A;if(Q.status==="aborted")return A;if(H.status==="dirty")_.dirty();if(Q.status==="dirty")_.dirty();if(H.value!=="__proto__"&&(typeof Q.value<"u"||J.alwaysSet))X[H.value]=Q.value}return{status:_.value,value:X}}}var A=Object.freeze({status:"aborted"}),C0=(_)=>({status:"dirty",value:_}),i=(_)=>({status:"valid",value:_}),A2=(_)=>_.status==="aborted",S2=(_)=>_.status==="dirty",f0=(_)=>_.status==="valid",h0=(_)=>typeof Promise<"u"&&_ instanceof Promise;var D;(function(_){_.errToObj=(Y)=>typeof Y==="string"?{message:Y}:Y||{},_.toString=(Y)=>typeof Y==="string"?Y:Y?.message})(D||(D={}));class J0{constructor(_,Y,X,J){this._cachedPath=[],this.parent=_,this.data=Y,this._path=X,this._key=J}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var B4=(_,Y)=>{if(f0(Y))return{success:!0,data:Y.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new o(_.common.issues);return this._error=X,this._error}}}};function P(_){if(!_)return{};let{errorMap:Y,invalid_type_error:X,required_error:J,description:H}=_;if(Y&&(X||J))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Y)return{errorMap:Y,description:H};return{errorMap:(q,$)=>{let{message:G}=_;if(q.code==="invalid_enum_value")return{message:G??$.defaultError};if(typeof $.data>"u")return{message:G??J??$.defaultError};if(q.code!=="invalid_type")return{message:$.defaultError};return{message:G??X??$.defaultError}},description:H}}class T{get description(){return this._def.description}_getType(_){return $0(_.data)}_getOrReturnCtx(_,Y){return Y||{common:_.parent.common,data:_.data,parsedType:$0(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new n,ctx:{common:_.parent.common,data:_.data,parsedType:$0(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let Y=this._parse(_);if(h0(Y))throw Error("Synchronous parse encountered promise.");return Y}_parseAsync(_){let Y=this._parse(_);return Promise.resolve(Y)}parse(_,Y){let X=this.safeParse(_,Y);if(X.success)return X.data;throw X.error}safeParse(_,Y){let X={common:{issues:[],async:Y?.async??!1,contextualErrorMap:Y?.errorMap},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:$0(_)},J=this._parseSync({data:_,path:X.path,parent:X});return B4(X,J)}"~validate"(_){let Y={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:$0(_)};if(!this["~standard"].async)try{let X=this._parseSync({data:_,path:[],parent:Y});return f0(X)?{value:X.value}:{issues:Y.common.issues}}catch(X){if(X?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Y.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:Y}).then((X)=>f0(X)?{value:X.value}:{issues:Y.common.issues})}async parseAsync(_,Y){let X=await this.safeParseAsync(_,Y);if(X.success)return X.data;throw X.error}async safeParseAsync(_,Y){let X={common:{issues:[],contextualErrorMap:Y?.errorMap,async:!0},path:Y?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:$0(_)},J=this._parse({data:_,path:X.path,parent:X}),H=await(h0(J)?J:Promise.resolve(J));return B4(X,H)}refine(_,Y){let X=(J)=>{if(typeof Y==="string"||typeof Y>"u")return{message:Y};else if(typeof Y==="function")return Y(J);else return Y};return this._refinement((J,H)=>{let Q=_(J),q=()=>H.addIssue({code:U.custom,...X(J)});if(typeof Promise<"u"&&Q instanceof Promise)return Q.then(($)=>{if(!$)return q(),!1;else return!0});if(!Q)return q(),!1;else return!0})}refinement(_,Y){return this._refinement((X,J)=>{if(!_(X))return J.addIssue(typeof Y==="function"?Y(X,J):Y),!1;else return!0})}_refinement(_){return new H0({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(Y)=>this["~validate"](Y)}}optional(){return X0.create(this,this._def)}nullable(){return F0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Y0.create(this)}promise(){return Z0.create(this,this._def)}or(_){return d0.create([this,_],this._def)}and(_){return p0.create(this,_,this._def)}transform(_){return new H0({...P(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let Y=typeof _==="function"?_:()=>_;return new o0({...P(this._def),innerType:this,defaultValue:Y,typeName:w.ZodDefault})}brand(){return new z2({typeName:w.ZodBranded,type:this,...P(this._def)})}catch(_){let Y=typeof _==="function"?_:()=>_;return new s0({...P(this._def),innerType:this,catchValue:Y,typeName:w.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return V2.create(this,_)}readonly(){return a0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var p_=/^c[^\s-]{8,}$/i,n_=/^[0-9a-z]+$/,i_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,r_=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,o_=/^[a-z0-9_-]{21}$/i,s_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,a_=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,t_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,e_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Y1,_8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Y8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,X8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,J8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H8=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Q8=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,V4="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",q8=new RegExp(`^${V4}$`);function U4(_){let Y="[0-5]\\d";if(_.precision)Y=`${Y}\\.\\d{${_.precision}}`;else if(_.precision==null)Y=`${Y}(\\.\\d+)?`;let X=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Y})${X}`}function $8(_){return new RegExp(`^${U4(_)}$`)}function E4(_){let Y=`${V4}T${U4(_)}`,X=[];if(X.push(_.local?"Z?":"Z"),_.offset)X.push("([+-]\\d{2}:?\\d{2})");return Y=`${Y}(${X.join("|")})`,new RegExp(`^${Y}$`)}function G8(_,Y){if((Y==="v4"||!Y)&&_8.test(_))return!0;if((Y==="v6"||!Y)&&X8.test(_))return!0;return!1}function W8(_,Y){if(!s_.test(_))return!1;try{let[X]=_.split(".");if(!X)return!1;let J=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),H=JSON.parse(atob(J));if(typeof H!=="object"||H===null)return!1;if("typ"in H&&H?.typ!=="JWT")return!1;if(!H.alg)return!1;if(Y&&H.alg!==Y)return!1;return!0}catch{return!1}}function L8(_,Y){if((Y==="v4"||!Y)&&Y8.test(_))return!0;if((Y==="v6"||!Y)&&J8.test(_))return!0;return!1}class _0 extends T{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==F.string){let H=this._getOrReturnCtx(_);return f(H,{code:U.invalid_type,expected:F.string,received:H.parsedType}),A}let X=new n,J=void 0;for(let H of this._def.checks)if(H.kind==="min"){if(_.data.length<H.value)J=this._getOrReturnCtx(_,J),f(J,{code:U.too_small,minimum:H.value,type:"string",inclusive:!0,exact:!1,message:H.message}),X.dirty()}else if(H.kind==="max"){if(_.data.length>H.value)J=this._getOrReturnCtx(_,J),f(J,{code:U.too_big,maximum:H.value,type:"string",inclusive:!0,exact:!1,message:H.message}),X.dirty()}else if(H.kind==="length"){let Q=_.data.length>H.value,q=_.data.length<H.value;if(Q||q){if(J=this._getOrReturnCtx(_,J),Q)f(J,{code:U.too_big,maximum:H.value,type:"string",inclusive:!0,exact:!0,message:H.message});else if(q)f(J,{code:U.too_small,minimum:H.value,type:"string",inclusive:!0,exact:!0,message:H.message});X.dirty()}}else if(H.kind==="email"){if(!t_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"email",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="emoji"){if(!Y1)Y1=new RegExp(e_,"u");if(!Y1.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"emoji",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="uuid"){if(!r_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"uuid",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="nanoid"){if(!o_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"nanoid",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="cuid"){if(!p_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"cuid",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="cuid2"){if(!n_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"cuid2",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="ulid"){if(!i_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"ulid",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="url")try{new URL(_.data)}catch{J=this._getOrReturnCtx(_,J),f(J,{validation:"url",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="regex"){if(H.regex.lastIndex=0,!H.regex.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"regex",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="trim")_.data=_.data.trim();else if(H.kind==="includes"){if(!_.data.includes(H.value,H.position))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:{includes:H.value,position:H.position},message:H.message}),X.dirty()}else if(H.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(H.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(H.kind==="startsWith"){if(!_.data.startsWith(H.value))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:{startsWith:H.value},message:H.message}),X.dirty()}else if(H.kind==="endsWith"){if(!_.data.endsWith(H.value))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:{endsWith:H.value},message:H.message}),X.dirty()}else if(H.kind==="datetime"){if(!E4(H).test(_.data))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:"datetime",message:H.message}),X.dirty()}else if(H.kind==="date"){if(!q8.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:"date",message:H.message}),X.dirty()}else if(H.kind==="time"){if(!$8(H).test(_.data))J=this._getOrReturnCtx(_,J),f(J,{code:U.invalid_string,validation:"time",message:H.message}),X.dirty()}else if(H.kind==="duration"){if(!a_.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"duration",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="ip"){if(!G8(_.data,H.version))J=this._getOrReturnCtx(_,J),f(J,{validation:"ip",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="jwt"){if(!W8(_.data,H.alg))J=this._getOrReturnCtx(_,J),f(J,{validation:"jwt",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="cidr"){if(!L8(_.data,H.version))J=this._getOrReturnCtx(_,J),f(J,{validation:"cidr",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="base64"){if(!H8.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"base64",code:U.invalid_string,message:H.message}),X.dirty()}else if(H.kind==="base64url"){if(!Q8.test(_.data))J=this._getOrReturnCtx(_,J),f(J,{validation:"base64url",code:U.invalid_string,message:H.message}),X.dirty()}else b.assertNever(H);return{status:X.value,value:_.data}}_regex(_,Y,X){return this.refinement((J)=>_.test(J),{validation:Y,code:U.invalid_string,...D.errToObj(X)})}_addCheck(_){return new _0({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...D.errToObj(_)})}url(_){return this._addCheck({kind:"url",...D.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...D.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...D.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...D.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...D.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...D.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...D.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...D.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...D.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...D.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...D.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...D.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...D.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...D.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...D.errToObj(_)})}regex(_,Y){return this._addCheck({kind:"regex",regex:_,...D.errToObj(Y)})}includes(_,Y){return this._addCheck({kind:"includes",value:_,position:Y?.position,...D.errToObj(Y?.message)})}startsWith(_,Y){return this._addCheck({kind:"startsWith",value:_,...D.errToObj(Y)})}endsWith(_,Y){return this._addCheck({kind:"endsWith",value:_,...D.errToObj(Y)})}min(_,Y){return this._addCheck({kind:"min",value:_,...D.errToObj(Y)})}max(_,Y){return this._addCheck({kind:"max",value:_,...D.errToObj(Y)})}length(_,Y){return this._addCheck({kind:"length",value:_,...D.errToObj(Y)})}nonempty(_){return this.min(1,D.errToObj(_))}trim(){return new _0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _0({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(_===null||Y.value>_)_=Y.value}return _}get maxLength(){let _=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(_===null||Y.value<_)_=Y.value}return _}}_0.create=(_)=>{return new _0({checks:[],typeName:w.ZodString,coerce:_?.coerce??!1,...P(_)})};function B8(_,Y){let X=(_.toString().split(".")[1]||"").length,J=(Y.toString().split(".")[1]||"").length,H=X>J?X:J,Q=Number.parseInt(_.toFixed(H).replace(".","")),q=Number.parseInt(Y.toFixed(H).replace(".",""));return Q%q/10**H}class D0 extends T{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==F.number){let H=this._getOrReturnCtx(_);return f(H,{code:U.invalid_type,expected:F.number,received:H.parsedType}),A}let X=void 0,J=new n;for(let H of this._def.checks)if(H.kind==="int"){if(!b.isInteger(_.data))X=this._getOrReturnCtx(_,X),f(X,{code:U.invalid_type,expected:"integer",received:"float",message:H.message}),J.dirty()}else if(H.kind==="min"){if(H.inclusive?_.data<H.value:_.data<=H.value)X=this._getOrReturnCtx(_,X),f(X,{code:U.too_small,minimum:H.value,type:"number",inclusive:H.inclusive,exact:!1,message:H.message}),J.dirty()}else if(H.kind==="max"){if(H.inclusive?_.data>H.value:_.data>=H.value)X=this._getOrReturnCtx(_,X),f(X,{code:U.too_big,maximum:H.value,type:"number",inclusive:H.inclusive,exact:!1,message:H.message}),J.dirty()}else if(H.kind==="multipleOf"){if(B8(_.data,H.value)!==0)X=this._getOrReturnCtx(_,X),f(X,{code:U.not_multiple_of,multipleOf:H.value,message:H.message}),J.dirty()}else if(H.kind==="finite"){if(!Number.isFinite(_.data))X=this._getOrReturnCtx(_,X),f(X,{code:U.not_finite,message:H.message}),J.dirty()}else b.assertNever(H);return{status:J.value,value:_.data}}gte(_,Y){return this.setLimit("min",_,!0,D.toString(Y))}gt(_,Y){return this.setLimit("min",_,!1,D.toString(Y))}lte(_,Y){return this.setLimit("max",_,!0,D.toString(Y))}lt(_,Y){return this.setLimit("max",_,!1,D.toString(Y))}setLimit(_,Y,X,J){return new D0({...this._def,checks:[...this._def.checks,{kind:_,value:Y,inclusive:X,message:D.toString(J)}]})}_addCheck(_){return new D0({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:D.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(_)})}multipleOf(_,Y){return this._addCheck({kind:"multipleOf",value:_,message:D.toString(Y)})}finite(_){return this._addCheck({kind:"finite",message:D.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(_)})}get minValue(){let _=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(_===null||Y.value>_)_=Y.value}return _}get maxValue(){let _=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(_===null||Y.value<_)_=Y.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&b.isInteger(_.value))}get isFinite(){let _=null,Y=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(Y===null||X.value>Y)Y=X.value}else if(X.kind==="max"){if(_===null||X.value<_)_=X.value}return Number.isFinite(Y)&&Number.isFinite(_)}}D0.create=(_)=>{return new D0({checks:[],typeName:w.ZodNumber,coerce:_?.coerce||!1,...P(_)})};class j0 extends T{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==F.bigint)return this._getInvalidInput(_);let X=void 0,J=new n;for(let H of this._def.checks)if(H.kind==="min"){if(H.inclusive?_.data<H.value:_.data<=H.value)X=this._getOrReturnCtx(_,X),f(X,{code:U.too_small,type:"bigint",minimum:H.value,inclusive:H.inclusive,message:H.message}),J.dirty()}else if(H.kind==="max"){if(H.inclusive?_.data>H.value:_.data>=H.value)X=this._getOrReturnCtx(_,X),f(X,{code:U.too_big,type:"bigint",maximum:H.value,inclusive:H.inclusive,message:H.message}),J.dirty()}else if(H.kind==="multipleOf"){if(_.data%H.value!==BigInt(0))X=this._getOrReturnCtx(_,X),f(X,{code:U.not_multiple_of,multipleOf:H.value,message:H.message}),J.dirty()}else b.assertNever(H);return{status:J.value,value:_.data}}_getInvalidInput(_){let Y=this._getOrReturnCtx(_);return f(Y,{code:U.invalid_type,expected:F.bigint,received:Y.parsedType}),A}gte(_,Y){return this.setLimit("min",_,!0,D.toString(Y))}gt(_,Y){return this.setLimit("min",_,!1,D.toString(Y))}lte(_,Y){return this.setLimit("max",_,!0,D.toString(Y))}lt(_,Y){return this.setLimit("max",_,!1,D.toString(Y))}setLimit(_,Y,X,J){return new j0({...this._def,checks:[...this._def.checks,{kind:_,value:Y,inclusive:X,message:D.toString(J)}]})}_addCheck(_){return new j0({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(_)})}multipleOf(_,Y){return this._addCheck({kind:"multipleOf",value:_,message:D.toString(Y)})}get minValue(){let _=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(_===null||Y.value>_)_=Y.value}return _}get maxValue(){let _=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(_===null||Y.value<_)_=Y.value}return _}}j0.create=(_)=>{return new j0({checks:[],typeName:w.ZodBigInt,coerce:_?.coerce??!1,...P(_)})};class c0 extends T{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==F.boolean){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.boolean,received:X.parsedType}),A}return i(_.data)}}c0.create=(_)=>{return new c0({typeName:w.ZodBoolean,coerce:_?.coerce||!1,...P(_)})};class T0 extends T{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==F.date){let H=this._getOrReturnCtx(_);return f(H,{code:U.invalid_type,expected:F.date,received:H.parsedType}),A}if(Number.isNaN(_.data.getTime())){let H=this._getOrReturnCtx(_);return f(H,{code:U.invalid_date}),A}let X=new n,J=void 0;for(let H of this._def.checks)if(H.kind==="min"){if(_.data.getTime()<H.value)J=this._getOrReturnCtx(_,J),f(J,{code:U.too_small,message:H.message,inclusive:!0,exact:!1,minimum:H.value,type:"date"}),X.dirty()}else if(H.kind==="max"){if(_.data.getTime()>H.value)J=this._getOrReturnCtx(_,J),f(J,{code:U.too_big,message:H.message,inclusive:!0,exact:!1,maximum:H.value,type:"date"}),X.dirty()}else b.assertNever(H);return{status:X.value,value:new Date(_.data.getTime())}}_addCheck(_){return new T0({...this._def,checks:[...this._def.checks,_]})}min(_,Y){return this._addCheck({kind:"min",value:_.getTime(),message:D.toString(Y)})}max(_,Y){return this._addCheck({kind:"max",value:_.getTime(),message:D.toString(Y)})}get minDate(){let _=null;for(let Y of this._def.checks)if(Y.kind==="min"){if(_===null||Y.value>_)_=Y.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let Y of this._def.checks)if(Y.kind==="max"){if(_===null||Y.value<_)_=Y.value}return _!=null?new Date(_):null}}T0.create=(_)=>{return new T0({checks:[],coerce:_?.coerce||!1,typeName:w.ZodDate,...P(_)})};class G2 extends T{_parse(_){if(this._getType(_)!==F.symbol){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.symbol,received:X.parsedType}),A}return i(_.data)}}G2.create=(_)=>{return new G2({typeName:w.ZodSymbol,...P(_)})};class u0 extends T{_parse(_){if(this._getType(_)!==F.undefined){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.undefined,received:X.parsedType}),A}return i(_.data)}}u0.create=(_)=>{return new u0({typeName:w.ZodUndefined,...P(_)})};class l0 extends T{_parse(_){if(this._getType(_)!==F.null){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.null,received:X.parsedType}),A}return i(_.data)}}l0.create=(_)=>{return new l0({typeName:w.ZodNull,...P(_)})};class v0 extends T{constructor(){super(...arguments);this._any=!0}_parse(_){return i(_.data)}}v0.create=(_)=>{return new v0({typeName:w.ZodAny,...P(_)})};class K0 extends T{constructor(){super(...arguments);this._unknown=!0}_parse(_){return i(_.data)}}K0.create=(_)=>{return new K0({typeName:w.ZodUnknown,...P(_)})};class G0 extends T{_parse(_){let Y=this._getOrReturnCtx(_);return f(Y,{code:U.invalid_type,expected:F.never,received:Y.parsedType}),A}}G0.create=(_)=>{return new G0({typeName:w.ZodNever,...P(_)})};class W2 extends T{_parse(_){if(this._getType(_)!==F.undefined){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.void,received:X.parsedType}),A}return i(_.data)}}W2.create=(_)=>{return new W2({typeName:w.ZodVoid,...P(_)})};class Y0 extends T{_parse(_){let{ctx:Y,status:X}=this._processInputParams(_),J=this._def;if(Y.parsedType!==F.array)return f(Y,{code:U.invalid_type,expected:F.array,received:Y.parsedType}),A;if(J.exactLength!==null){let Q=Y.data.length>J.exactLength.value,q=Y.data.length<J.exactLength.value;if(Q||q)f(Y,{code:Q?U.too_big:U.too_small,minimum:q?J.exactLength.value:void 0,maximum:Q?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),X.dirty()}if(J.minLength!==null){if(Y.data.length<J.minLength.value)f(Y,{code:U.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),X.dirty()}if(J.maxLength!==null){if(Y.data.length>J.maxLength.value)f(Y,{code:U.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),X.dirty()}if(Y.common.async)return Promise.all([...Y.data].map((Q,q)=>{return J.type._parseAsync(new J0(Y,Q,Y.path,q))})).then((Q)=>{return n.mergeArray(X,Q)});let H=[...Y.data].map((Q,q)=>{return J.type._parseSync(new J0(Y,Q,Y.path,q))});return n.mergeArray(X,H)}get element(){return this._def.type}min(_,Y){return new Y0({...this._def,minLength:{value:_,message:D.toString(Y)}})}max(_,Y){return new Y0({...this._def,maxLength:{value:_,message:D.toString(Y)}})}length(_,Y){return new Y0({...this._def,exactLength:{value:_,message:D.toString(Y)}})}nonempty(_){return this.min(1,_)}}Y0.create=(_,Y)=>{return new Y0({type:_,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...P(Y)})};function g0(_){if(_ instanceof l){let Y={};for(let X in _.shape){let J=_.shape[X];Y[X]=X0.create(g0(J))}return new l({..._._def,shape:()=>Y})}else if(_ instanceof Y0)return new Y0({..._._def,type:g0(_.element)});else if(_ instanceof X0)return X0.create(g0(_.unwrap()));else if(_ instanceof F0)return F0.create(g0(_.unwrap()));else if(_ instanceof W0)return W0.create(_.items.map((Y)=>g0(Y)));else return _}class l extends T{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),Y=b.objectKeys(_);return this._cached={shape:_,keys:Y},this._cached}_parse(_){if(this._getType(_)!==F.object){let G=this._getOrReturnCtx(_);return f(G,{code:U.invalid_type,expected:F.object,received:G.parsedType}),A}let{status:X,ctx:J}=this._processInputParams(_),{shape:H,keys:Q}=this._getCached(),q=[];if(!(this._def.catchall instanceof G0&&this._def.unknownKeys==="strip")){for(let G in J.data)if(!Q.includes(G))q.push(G)}let $=[];for(let G of Q){let W=H[G],L=J.data[G];$.push({key:{status:"valid",value:G},value:W._parse(new J0(J,L,J.path,G)),alwaysSet:G in J.data})}if(this._def.catchall instanceof G0){let G=this._def.unknownKeys;if(G==="passthrough")for(let W of q)$.push({key:{status:"valid",value:W},value:{status:"valid",value:J.data[W]}});else if(G==="strict"){if(q.length>0)f(J,{code:U.unrecognized_keys,keys:q}),X.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let W of q){let L=J.data[W];$.push({key:{status:"valid",value:W},value:G._parse(new J0(J,L,J.path,W)),alwaysSet:W in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let G=[];for(let W of $){let L=await W.key,V=await W.value;G.push({key:L,value:V,alwaysSet:W.alwaysSet})}return G}).then((G)=>{return n.mergeObjectSync(X,G)});else return n.mergeObjectSync(X,$)}get shape(){return this._def.shape()}strict(_){return D.errToObj,new l({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(Y,X)=>{let J=this._def.errorMap?.(Y,X).message??X.defaultError;if(Y.code==="unrecognized_keys")return{message:D.errToObj(_).message??J};return{message:J}}}:{}})}strip(){return new l({...this._def,unknownKeys:"strip"})}passthrough(){return new l({...this._def,unknownKeys:"passthrough"})}extend(_){return new l({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new l({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:w.ZodObject})}setKey(_,Y){return this.augment({[_]:Y})}catchall(_){return new l({...this._def,catchall:_})}pick(_){let Y={};for(let X of b.objectKeys(_))if(_[X]&&this.shape[X])Y[X]=this.shape[X];return new l({...this._def,shape:()=>Y})}omit(_){let Y={};for(let X of b.objectKeys(this.shape))if(!_[X])Y[X]=this.shape[X];return new l({...this._def,shape:()=>Y})}deepPartial(){return g0(this)}partial(_){let Y={};for(let X of b.objectKeys(this.shape)){let J=this.shape[X];if(_&&!_[X])Y[X]=J;else Y[X]=J.optional()}return new l({...this._def,shape:()=>Y})}required(_){let Y={};for(let X of b.objectKeys(this.shape))if(_&&!_[X])Y[X]=this.shape[X];else{let H=this.shape[X];while(H instanceof X0)H=H._def.innerType;Y[X]=H}return new l({...this._def,shape:()=>Y})}keyof(){return F4(b.objectKeys(this.shape))}}l.create=(_,Y)=>{return new l({shape:()=>_,unknownKeys:"strip",catchall:G0.create(),typeName:w.ZodObject,...P(Y)})};l.strictCreate=(_,Y)=>{return new l({shape:()=>_,unknownKeys:"strict",catchall:G0.create(),typeName:w.ZodObject,...P(Y)})};l.lazycreate=(_,Y)=>{return new l({shape:_,unknownKeys:"strip",catchall:G0.create(),typeName:w.ZodObject,...P(Y)})};class d0 extends T{_parse(_){let{ctx:Y}=this._processInputParams(_),X=this._def.options;function J(H){for(let q of H)if(q.result.status==="valid")return q.result;for(let q of H)if(q.result.status==="dirty")return Y.common.issues.push(...q.ctx.common.issues),q.result;let Q=H.map((q)=>new o(q.ctx.common.issues));return f(Y,{code:U.invalid_union,unionErrors:Q}),A}if(Y.common.async)return Promise.all(X.map(async(H)=>{let Q={...Y,common:{...Y.common,issues:[]},parent:null};return{result:await H._parseAsync({data:Y.data,path:Y.path,parent:Q}),ctx:Q}})).then(J);else{let H=void 0,Q=[];for(let $ of X){let G={...Y,common:{...Y.common,issues:[]},parent:null},W=$._parseSync({data:Y.data,path:Y.path,parent:G});if(W.status==="valid")return W;else if(W.status==="dirty"&&!H)H={result:W,ctx:G};if(G.common.issues.length)Q.push(G.common.issues)}if(H)return Y.common.issues.push(...H.ctx.common.issues),H.result;let q=Q.map(($)=>new o($));return f(Y,{code:U.invalid_union,unionErrors:q}),A}}get options(){return this._def.options}}d0.create=(_,Y)=>{return new d0({options:_,typeName:w.ZodUnion,...P(Y)})};var E0=(_)=>{if(_ instanceof n0)return E0(_.schema);else if(_ instanceof H0)return E0(_.innerType());else if(_ instanceof i0)return[_.value];else if(_ instanceof N0)return _.options;else if(_ instanceof r0)return b.objectValues(_.enum);else if(_ instanceof o0)return E0(_._def.innerType);else if(_ instanceof u0)return[void 0];else if(_ instanceof l0)return[null];else if(_ instanceof X0)return[void 0,...E0(_.unwrap())];else if(_ instanceof F0)return[null,...E0(_.unwrap())];else if(_ instanceof z2)return E0(_.unwrap());else if(_ instanceof a0)return E0(_.unwrap());else if(_ instanceof s0)return E0(_._def.innerType);else return[]};class w2 extends T{_parse(_){let{ctx:Y}=this._processInputParams(_);if(Y.parsedType!==F.object)return f(Y,{code:U.invalid_type,expected:F.object,received:Y.parsedType}),A;let X=this.discriminator,J=Y.data[X],H=this.optionsMap.get(J);if(!H)return f(Y,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),A;if(Y.common.async)return H._parseAsync({data:Y.data,path:Y.path,parent:Y});else return H._parseSync({data:Y.data,path:Y.path,parent:Y})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,Y,X){let J=new Map;for(let H of Y){let Q=E0(H.shape[_]);if(!Q.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let q of Q){if(J.has(q))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(q)}`);J.set(q,H)}}return new w2({typeName:w.ZodDiscriminatedUnion,discriminator:_,options:Y,optionsMap:J,...P(X)})}}function X1(_,Y){let X=$0(_),J=$0(Y);if(_===Y)return{valid:!0,data:_};else if(X===F.object&&J===F.object){let H=b.objectKeys(Y),Q=b.objectKeys(_).filter(($)=>H.indexOf($)!==-1),q={..._,...Y};for(let $ of Q){let G=X1(_[$],Y[$]);if(!G.valid)return{valid:!1};q[$]=G.data}return{valid:!0,data:q}}else if(X===F.array&&J===F.array){if(_.length!==Y.length)return{valid:!1};let H=[];for(let Q=0;Q<_.length;Q++){let q=_[Q],$=Y[Q],G=X1(q,$);if(!G.valid)return{valid:!1};H.push(G.data)}return{valid:!0,data:H}}else if(X===F.date&&J===F.date&&+_===+Y)return{valid:!0,data:_};else return{valid:!1}}class p0 extends T{_parse(_){let{status:Y,ctx:X}=this._processInputParams(_),J=(H,Q)=>{if(A2(H)||A2(Q))return A;let q=X1(H.value,Q.value);if(!q.valid)return f(X,{code:U.invalid_intersection_types}),A;if(S2(H)||S2(Q))Y.dirty();return{status:Y.value,value:q.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([H,Q])=>J(H,Q));else return J(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}p0.create=(_,Y,X)=>{return new p0({left:_,right:Y,typeName:w.ZodIntersection,...P(X)})};class W0 extends T{_parse(_){let{status:Y,ctx:X}=this._processInputParams(_);if(X.parsedType!==F.array)return f(X,{code:U.invalid_type,expected:F.array,received:X.parsedType}),A;if(X.data.length<this._def.items.length)return f(X,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;if(!this._def.rest&&X.data.length>this._def.items.length)f(X,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y.dirty();let H=[...X.data].map((Q,q)=>{let $=this._def.items[q]||this._def.rest;if(!$)return null;return $._parse(new J0(X,Q,X.path,q))}).filter((Q)=>!!Q);if(X.common.async)return Promise.all(H).then((Q)=>{return n.mergeArray(Y,Q)});else return n.mergeArray(Y,H)}get items(){return this._def.items}rest(_){return new W0({...this._def,rest:_})}}W0.create=(_,Y)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new W0({items:_,typeName:w.ZodTuple,rest:null,...P(Y)})};class L2 extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:Y,ctx:X}=this._processInputParams(_);if(X.parsedType!==F.object)return f(X,{code:U.invalid_type,expected:F.object,received:X.parsedType}),A;let J=[],H=this._def.keyType,Q=this._def.valueType;for(let q in X.data)J.push({key:H._parse(new J0(X,q,X.path,q)),value:Q._parse(new J0(X,X.data[q],X.path,q)),alwaysSet:q in X.data});if(X.common.async)return n.mergeObjectAsync(Y,J);else return n.mergeObjectSync(Y,J)}get element(){return this._def.valueType}static create(_,Y,X){if(Y instanceof T)return new L2({keyType:_,valueType:Y,typeName:w.ZodRecord,...P(X)});return new L2({keyType:_0.create(),valueType:_,typeName:w.ZodRecord,...P(Y)})}}class B2 extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:Y,ctx:X}=this._processInputParams(_);if(X.parsedType!==F.map)return f(X,{code:U.invalid_type,expected:F.map,received:X.parsedType}),A;let J=this._def.keyType,H=this._def.valueType,Q=[...X.data.entries()].map(([q,$],G)=>{return{key:J._parse(new J0(X,q,X.path,[G,"key"])),value:H._parse(new J0(X,$,X.path,[G,"value"]))}});if(X.common.async){let q=new Map;return Promise.resolve().then(async()=>{for(let $ of Q){let G=await $.key,W=await $.value;if(G.status==="aborted"||W.status==="aborted")return A;if(G.status==="dirty"||W.status==="dirty")Y.dirty();q.set(G.value,W.value)}return{status:Y.value,value:q}})}else{let q=new Map;for(let $ of Q){let{key:G,value:W}=$;if(G.status==="aborted"||W.status==="aborted")return A;if(G.status==="dirty"||W.status==="dirty")Y.dirty();q.set(G.value,W.value)}return{status:Y.value,value:q}}}}B2.create=(_,Y,X)=>{return new B2({valueType:Y,keyType:_,typeName:w.ZodMap,...P(X)})};class b0 extends T{_parse(_){let{status:Y,ctx:X}=this._processInputParams(_);if(X.parsedType!==F.set)return f(X,{code:U.invalid_type,expected:F.set,received:X.parsedType}),A;let J=this._def;if(J.minSize!==null){if(X.data.size<J.minSize.value)f(X,{code:U.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),Y.dirty()}if(J.maxSize!==null){if(X.data.size>J.maxSize.value)f(X,{code:U.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),Y.dirty()}let H=this._def.valueType;function Q($){let G=new Set;for(let W of $){if(W.status==="aborted")return A;if(W.status==="dirty")Y.dirty();G.add(W.value)}return{status:Y.value,value:G}}let q=[...X.data.values()].map(($,G)=>H._parse(new J0(X,$,X.path,G)));if(X.common.async)return Promise.all(q).then(($)=>Q($));else return Q(q)}min(_,Y){return new b0({...this._def,minSize:{value:_,message:D.toString(Y)}})}max(_,Y){return new b0({...this._def,maxSize:{value:_,message:D.toString(Y)}})}size(_,Y){return this.min(_,Y).max(_,Y)}nonempty(_){return this.min(1,_)}}b0.create=(_,Y)=>{return new b0({valueType:_,minSize:null,maxSize:null,typeName:w.ZodSet,...P(Y)})};class m0 extends T{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:Y}=this._processInputParams(_);if(Y.parsedType!==F.function)return f(Y,{code:U.invalid_type,expected:F.function,received:Y.parsedType}),A;function X(q,$){return $2({data:q,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,y0(),U0].filter((G)=>!!G),issueData:{code:U.invalid_arguments,argumentsError:$}})}function J(q,$){return $2({data:q,path:Y.path,errorMaps:[Y.common.contextualErrorMap,Y.schemaErrorMap,y0(),U0].filter((G)=>!!G),issueData:{code:U.invalid_return_type,returnTypeError:$}})}let H={errorMap:Y.common.contextualErrorMap},Q=Y.data;if(this._def.returns instanceof Z0){let q=this;return i(async function(...$){let G=new o([]),W=await q._def.args.parseAsync($,H).catch((E)=>{throw G.addIssue(X($,E)),G}),L=await Reflect.apply(Q,this,W);return await q._def.returns._def.type.parseAsync(L,H).catch((E)=>{throw G.addIssue(J(L,E)),G})})}else{let q=this;return i(function(...$){let G=q._def.args.safeParse($,H);if(!G.success)throw new o([X($,G.error)]);let W=Reflect.apply(Q,this,G.data),L=q._def.returns.safeParse(W,H);if(!L.success)throw new o([J(W,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new m0({...this._def,args:W0.create(_).rest(K0.create())})}returns(_){return new m0({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,Y,X){return new m0({args:_?_:W0.create([]).rest(K0.create()),returns:Y||K0.create(),typeName:w.ZodFunction,...P(X)})}}class n0 extends T{get schema(){return this._def.getter()}_parse(_){let{ctx:Y}=this._processInputParams(_);return this._def.getter()._parse({data:Y.data,path:Y.path,parent:Y})}}n0.create=(_,Y)=>{return new n0({getter:_,typeName:w.ZodLazy,...P(Y)})};class i0 extends T{_parse(_){if(_.data!==this._def.value){let Y=this._getOrReturnCtx(_);return f(Y,{received:Y.data,code:U.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:_.data}}get value(){return this._def.value}}i0.create=(_,Y)=>{return new i0({value:_,typeName:w.ZodLiteral,...P(Y)})};function F4(_,Y){return new N0({values:_,typeName:w.ZodEnum,...P(Y)})}class N0 extends T{_parse(_){if(typeof _.data!=="string"){let Y=this._getOrReturnCtx(_),X=this._def.values;return f(Y,{expected:b.joinValues(X),received:Y.parsedType,code:U.invalid_type}),A}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let Y=this._getOrReturnCtx(_),X=this._def.values;return f(Y,{received:Y.data,code:U.invalid_enum_value,options:X}),A}return i(_.data)}get options(){return this._def.values}get enum(){let _={};for(let Y of this._def.values)_[Y]=Y;return _}get Values(){let _={};for(let Y of this._def.values)_[Y]=Y;return _}get Enum(){let _={};for(let Y of this._def.values)_[Y]=Y;return _}extract(_,Y=this._def){return N0.create(_,{...this._def,...Y})}exclude(_,Y=this._def){return N0.create(this.options.filter((X)=>!_.includes(X)),{...this._def,...Y})}}N0.create=F4;class r0 extends T{_parse(_){let Y=b.getValidEnumValues(this._def.values),X=this._getOrReturnCtx(_);if(X.parsedType!==F.string&&X.parsedType!==F.number){let J=b.objectValues(Y);return f(X,{expected:b.joinValues(J),received:X.parsedType,code:U.invalid_type}),A}if(!this._cache)this._cache=new Set(b.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let J=b.objectValues(Y);return f(X,{received:X.data,code:U.invalid_enum_value,options:J}),A}return i(_.data)}get enum(){return this._def.values}}r0.create=(_,Y)=>{return new r0({values:_,typeName:w.ZodNativeEnum,...P(Y)})};class Z0 extends T{unwrap(){return this._def.type}_parse(_){let{ctx:Y}=this._processInputParams(_);if(Y.parsedType!==F.promise&&Y.common.async===!1)return f(Y,{code:U.invalid_type,expected:F.promise,received:Y.parsedType}),A;let X=Y.parsedType===F.promise?Y.data:Promise.resolve(Y.data);return i(X.then((J)=>{return this._def.type.parseAsync(J,{path:Y.path,errorMap:Y.common.contextualErrorMap})}))}}Z0.create=(_,Y)=>{return new Z0({type:_,typeName:w.ZodPromise,...P(Y)})};class H0 extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:Y,ctx:X}=this._processInputParams(_),J=this._def.effect||null,H={addIssue:(Q)=>{if(f(X,Q),Q.fatal)Y.abort();else Y.dirty()},get path(){return X.path}};if(H.addIssue=H.addIssue.bind(H),J.type==="preprocess"){let Q=J.transform(X.data,H);if(X.common.async)return Promise.resolve(Q).then(async(q)=>{if(Y.value==="aborted")return A;let $=await this._def.schema._parseAsync({data:q,path:X.path,parent:X});if($.status==="aborted")return A;if($.status==="dirty")return C0($.value);if(Y.value==="dirty")return C0($.value);return $});else{if(Y.value==="aborted")return A;let q=this._def.schema._parseSync({data:Q,path:X.path,parent:X});if(q.status==="aborted")return A;if(q.status==="dirty")return C0(q.value);if(Y.value==="dirty")return C0(q.value);return q}}if(J.type==="refinement"){let Q=(q)=>{let $=J.refinement(q,H);if(X.common.async)return Promise.resolve($);if($ instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return q};if(X.common.async===!1){let q=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(q.status==="aborted")return A;if(q.status==="dirty")Y.dirty();return Q(q.value),{status:Y.value,value:q.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((q)=>{if(q.status==="aborted")return A;if(q.status==="dirty")Y.dirty();return Q(q.value).then(()=>{return{status:Y.value,value:q.value}})})}if(J.type==="transform")if(X.common.async===!1){let Q=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!f0(Q))return A;let q=J.transform(Q.value,H);if(q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Y.value,value:q}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((Q)=>{if(!f0(Q))return A;return Promise.resolve(J.transform(Q.value,H)).then((q)=>({status:Y.value,value:q}))});b.assertNever(J)}}H0.create=(_,Y,X)=>{return new H0({schema:_,typeName:w.ZodEffects,effect:Y,...P(X)})};H0.createWithPreprocess=(_,Y,X)=>{return new H0({schema:Y,effect:{type:"preprocess",transform:_},typeName:w.ZodEffects,...P(X)})};class X0 extends T{_parse(_){if(this._getType(_)===F.undefined)return i(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}X0.create=(_,Y)=>{return new X0({innerType:_,typeName:w.ZodOptional,...P(Y)})};class F0 extends T{_parse(_){if(this._getType(_)===F.null)return i(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}F0.create=(_,Y)=>{return new F0({innerType:_,typeName:w.ZodNullable,...P(Y)})};class o0 extends T{_parse(_){let{ctx:Y}=this._processInputParams(_),X=Y.data;if(Y.parsedType===F.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:Y.path,parent:Y})}removeDefault(){return this._def.innerType}}o0.create=(_,Y)=>{return new o0({innerType:_,typeName:w.ZodDefault,defaultValue:typeof Y.default==="function"?Y.default:()=>Y.default,...P(Y)})};class s0 extends T{_parse(_){let{ctx:Y}=this._processInputParams(_),X={...Y,common:{...Y.common,issues:[]}},J=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(h0(J))return J.then((H)=>{return{status:"valid",value:H.status==="valid"?H.value:this._def.catchValue({get error(){return new o(X.common.issues)},input:X.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new o(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}s0.create=(_,Y)=>{return new s0({innerType:_,typeName:w.ZodCatch,catchValue:typeof Y.catch==="function"?Y.catch:()=>Y.catch,...P(Y)})};class M2 extends T{_parse(_){if(this._getType(_)!==F.nan){let X=this._getOrReturnCtx(_);return f(X,{code:U.invalid_type,expected:F.nan,received:X.parsedType}),A}return{status:"valid",value:_.data}}}M2.create=(_)=>{return new M2({typeName:w.ZodNaN,...P(_)})};var M8=Symbol("zod_brand");class z2 extends T{_parse(_){let{ctx:Y}=this._processInputParams(_),X=Y.data;return this._def.type._parse({data:X,path:Y.path,parent:Y})}unwrap(){return this._def.type}}class V2 extends T{_parse(_){let{status:Y,ctx:X}=this._processInputParams(_);if(X.common.async)return(async()=>{let H=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(H.status==="aborted")return A;if(H.status==="dirty")return Y.dirty(),C0(H.value);else return this._def.out._parseAsync({data:H.value,path:X.path,parent:X})})();else{let J=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return A;if(J.status==="dirty")return Y.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:X.path,parent:X})}}static create(_,Y){return new V2({in:_,out:Y,typeName:w.ZodPipeline})}}class a0 extends T{_parse(_){let Y=this._def.innerType._parse(_),X=(J)=>{if(f0(J))J.value=Object.freeze(J.value);return J};return h0(Y)?Y.then((J)=>X(J)):X(Y)}unwrap(){return this._def.innerType}}a0.create=(_,Y)=>{return new a0({innerType:_,typeName:w.ZodReadonly,...P(Y)})};function M4(_,Y){let X=typeof _==="function"?_(Y):typeof _==="string"?{message:_}:_;return typeof X==="string"?{message:X}:X}function R4(_,Y={},X){if(_)return v0.create().superRefine((J,H)=>{let Q=_(J);if(Q instanceof Promise)return Q.then((q)=>{if(!q){let $=M4(Y,J),G=$.fatal??X??!0;H.addIssue({code:"custom",...$,fatal:G})}});if(!Q){let q=M4(Y,J),$=q.fatal??X??!0;H.addIssue({code:"custom",...q,fatal:$})}return});return v0.create()}var V8={object:l.lazycreate},w;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(w||(w={}));var U8=(_,Y={message:`Input not instance of ${_.name}`})=>R4((X)=>X instanceof _,Y),f4=_0.create,K4=D0.create,E8=M2.create,F8=j0.create,D4=c0.create,R8=T0.create,f8=G2.create,K8=u0.create,D8=l0.create,j8=v0.create,N8=K0.create,A8=G0.create,S8=W2.create,w8=Y0.create,z8=l.create,O8=l.strictCreate,I8=d0.create,P8=w2.create,k8=p0.create,C8=W0.create,T8=L2.create,v8=B2.create,b8=b0.create,Z8=m0.create,x8=n0.create,y8=i0.create,h8=N0.create,g8=r0.create,m8=Z0.create,c8=H0.create,u8=X0.create,l8=F0.create,d8=H0.createWithPreprocess,p8=V2.create,n8=()=>f4().optional(),i8=()=>K4().optional(),r8=()=>D4().optional(),o8={string:(_)=>_0.create({..._,coerce:!0}),number:(_)=>D0.create({..._,coerce:!0}),boolean:(_)=>c0.create({..._,coerce:!0}),bigint:(_)=>j0.create({..._,coerce:!0}),date:(_)=>T0.create({..._,coerce:!0})};var s8=A;var a8=B.object({type:B.literal("user"),text:B.string(),id:B.string().optional(),timestamp:B.string().optional()}),t8=B.object({type:B.literal("compaction-summary"),text:B.string(),id:B.string().optional(),timestamp:B.string().optional()}),e8=B.object({type:B.literal("agent"),text:B.string(),id:B.string().optional(),timestamp:B.string().optional(),model:B.string().optional()}),_9=B.object({type:B.literal("thinking"),text:B.string(),id:B.string().optional(),timestamp:B.string().optional(),model:B.string().optional()}),j4=B.object({type:B.literal("tool-call"),toolName:B.string().nullable(),input:B.unknown().optional(),output:B.unknown().optional(),error:B.string().optional(),isError:B.union([B.boolean(),B.string()]).optional(),id:B.string().optional(),timestamp:B.string().optional(),model:B.string().optional()}),s=B.discriminatedUnion("type",[a8,t8,e8,_9,j4]),H1=B.object({inputTokens:B.number(),cachedInputTokens:B.number(),outputTokens:B.number(),reasoningOutputTokens:B.number(),totalTokens:B.number()}),L0=j4,Y9=L0.extend({toolName:B.literal("Write"),input:B.object({file_path:B.string(),content:B.string().optional()}).passthrough().optional(),output:B.object({type:B.string().optional()}).passthrough().optional()}),X9=L0.extend({toolName:B.literal("Read"),input:B.object({file_path:B.string()}).passthrough().optional(),output:B.union([B.string(),B.object({type:B.string().optional(),file:B.object({content:B.string().optional(),numLines:B.number().optional(),startLine:B.number().optional(),totalLines:B.number().optional()}).passthrough().optional()}).passthrough()]).optional()}),J9=L0.extend({toolName:B.literal("Edit"),input:B.object({file_path:B.string(),diff:B.string().optional()}).passthrough().optional(),output:B.union([B.string(),B.object({userModified:B.boolean().optional()}).passthrough()]).optional()}),N4=B.object({filenames:B.array(B.string()),durationMs:B.number().optional(),truncated:B.boolean().optional()}).passthrough(),H9=L0.extend({toolName:B.literal("Glob"),input:B.object({pattern:B.string().optional()}).passthrough().optional(),output:N4.optional()}),Q9=L0.extend({toolName:B.literal("Grep"),input:B.unknown().optional(),output:N4.extend({mode:B.string().optional(),numMatches:B.number().optional()}).passthrough().optional()}),q9=L0.extend({toolName:B.literal("Bash"),input:B.unknown().optional(),output:B.union([B.string(),B.object({stdout:B.string().optional(),stderr:B.string().optional(),interrupted:B.boolean().optional(),isImage:B.boolean().optional()}).passthrough()]).optional()}),$9=L0.extend({toolName:B.literal("BashOutput"),input:B.object({bash_id:B.string().optional()}).passthrough().optional(),output:B.object({command:B.string().optional(),exitCode:B.number().optional(),shellId:B.string().optional(),status:B.string().optional(),stderr:B.string().optional(),stdout:B.string().optional(),timestamp:B.string().optional()}).passthrough().optional()}),G9=L0.extend({toolName:B.literal("Task"),input:B.unknown().optional(),output:B.object({status:B.string().optional(),totalDurationMs:B.number().optional(),totalToolUseCount:B.number().optional(),content:B.array(B.object({type:B.string().optional(),text:B.string().optional()}).passthrough()).optional(),usage:H1.optional()}).passthrough().optional()}),J1=B.object({content:B.string(),status:B.string().optional()}).passthrough(),W9=L0.extend({toolName:B.literal("TodoWrite"),input:B.object({todos:B.array(J1).optional()}).passthrough().optional(),output:B.object({oldTodos:B.array(J1).optional(),newTodos:B.array(J1).optional()}).passthrough().optional()}),L9=[Y9,X9,J9,H9,Q9,q9,$9,G9,W9],B9=L0,A4=B.union([...L9,B9]),O2=B.object({model:B.string(),usage:H1}),B0=B.object({relativeCwd:B.string().nullable(),branch:B.string().nullable(),repo:B.string().nullable()}).strict().nullable(),U2=B.object({v:B.literal(1),id:B.string(),source:B.enum(["claude-code","codex","opencode","unknown"]),timestamp:B.coerce.date(),preview:B.string().nullable(),model:B.string().nullable(),blendedTokens:B.number(),costUsd:B.number(),messageCount:B.number(),tokenUsage:H1,modelUsage:B.array(O2),git:B0,cwd:B.string().nullable(),messages:B.array(s)});var V9=200000,U9=["anthropic/","claude-3-5-","claude-3-","claude-","openai/","azure/","openrouter/openai/"],O4=new Set(["[request interrupted by user]","[request aborted by user]","[request cancelled by user]"]),E9=/^<\/?(?:command|local)-[a-z-]+>/i,I4=/^[α-ωΑ-Ω]\s/i,P4=["npm ","npm:","npm error","node:","node.js","error:","fatal:","warning:","traceback (most recent call last):","usage:","hint:","note:","code:","requirestack"],F9=new RegExp("\\b("+["fix","please","should","update","change","add","remove","create","write","implement","refactor","investigate","explain","help","why","what","how","need","ensure","make","build","let's","optimize","review","check"].join("|")+")\\b","i"),R9=3;function k4(_,Y={}){let X=f9(_);if(X.records.size===0)return null;let J=j9(X.records,X.children);if(!J)return null;let H=N9(J,X.records);if(H.length===0)return null;let Q=A9(H),q=w9(Q),$=z9(Q),G=y9(q),W=Q.map((M)=>{let R=M.message?.usage;if(!R)return null;return{model:M.message?.model??null,usage:R}}).filter((M)=>M!==null),L=g9(W,Y.pricing),V=O9(H),E=V.length>0?k9(V[0]):null,N=b4(J.timestamp)??Y.now??new Date,v=v9(H),Z=b9($),S=T9(H),O=$1(H),c=O?k0(O):"",{messages:u,blobs:K}=u9(H),d={v:1,id:v??J.uuid,source:"claude-code",timestamp:N,preview:E,model:Z,blendedTokens:G,costUsd:L,messageCount:H.length,tokenUsage:q,modelUsage:Array.from($.entries()).map(([M,R])=>({model:M,usage:R})),git:S,cwd:c,messages:u};return{transcript:U2.parse(d),blobs:K}}function f9(_){let Y=new Map,X=new Map;for(let J of _){let H=typeof J.type==="string"?J.type:"";if(H==="summary")continue;let Q=typeof J.uuid==="string"?J.uuid:null;if(!Q)continue;let q={uuid:Q,type:H,timestamp:typeof J.timestamp==="string"?J.timestamp:void 0,parentUuid:typeof J.parentUuid==="string"||J.parentUuid===null?J.parentUuid:void 0,logicalParentUuid:typeof J.logicalParentUuid==="string"||J.logicalParentUuid===null?J.logicalParentUuid:void 0,isSidechain:Boolean(J.isSidechain),isMeta:Boolean(J.isMeta),isCompactSummary:Boolean(J.isCompactSummary),sessionId:typeof J.sessionId==="string"?J.sessionId:void 0,cwd:typeof J.cwd==="string"?J.cwd:void 0,gitBranch:typeof J.gitBranch==="string"?J.gitBranch:void 0,costUSD:typeof J.costUSD==="number"?J.costUSD:void 0,message:K9(J.message),raw:J};if(Y.set(Q,q),q.parentUuid){let $=X.get(q.parentUuid)??new Set;$.add(Q),X.set(q.parentUuid,$)}}return{records:Y,children:X}}function K9(_){if(!_||typeof _!=="object")return;let Y=_,X=typeof Y.id==="string"?Y.id:void 0,J=typeof Y.role==="string"?Y.role:void 0,H=Y.content,Q=typeof Y.model==="string"?Y.model:void 0,q=D9(Y.usage);return{id:X,role:J,content:H,model:Q,usage:q}}function D9(_){if(!_||typeof _!=="object")return null;let Y=_,X={};if(typeof Y.input_tokens==="number")X.input_tokens=Y.input_tokens;if(typeof Y.cache_creation_input_tokens==="number")X.cache_creation_input_tokens=Y.cache_creation_input_tokens;if(typeof Y.cache_read_input_tokens==="number")X.cache_read_input_tokens=Y.cache_read_input_tokens;if(typeof Y.output_tokens==="number")X.output_tokens=Y.output_tokens;if(typeof Y.reasoning_output_tokens==="number")X.reasoning_output_tokens=Y.reasoning_output_tokens;return Object.keys(X).length>0?X:null}function j9(_,Y){let X=[];for(let J of _.values())if(!Y.has(J.uuid))X.push(J);if(X.length===0)return null;return X.sort((J,H)=>{let Q=S4(J.timestamp)??0,q=S4(H.timestamp)??0;if(Q===q)return J.uuid.localeCompare(H.uuid);return q-Q}),X[0]}function N9(_,Y){let X=[],J=new Set,H=_;while(H){if(J.has(H.uuid))break;J.add(H.uuid),X.unshift(H);let Q=H.parentUuid??H.logicalParentUuid??void 0;if(!Q)break;H=Y.get(Q)}return X}function A9(_){let Y=new Map;for(let X of _){if(X.type!=="assistant")continue;if(!X.message?.usage)continue;let H=S9(X);Y.set(H,X)}return Array.from(Y.values())}function S9(_){let Y=_.message,X=w4(Y?.id),J=w4(_.raw.requestId);if(X&&J)return`${X}:${J}`;if(X)return X;if(J)return J;return _.uuid}function w9(_){let Y={inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0};for(let X of _){let J=X.message?.usage;if(!J)continue;let H=a(J.input_tokens),Q=a(J.cache_creation_input_tokens),q=a(J.cache_read_input_tokens),$=a(J.output_tokens),G=a(J.reasoning_output_tokens);Y.inputTokens+=H+Q+q,Y.cachedInputTokens+=q,Y.outputTokens+=$,Y.reasoningOutputTokens+=G,Y.totalTokens+=H+Q+q+$+G}return Y}function z9(_){let Y=new Map;for(let X of _){let J=X.message?.model,H=X.message?.usage;if(!J||!H)continue;let Q=Y.get(J)??{inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0},q=a(H.input_tokens),$=a(H.cache_creation_input_tokens),G=a(H.cache_read_input_tokens),W=a(H.output_tokens),L=a(H.reasoning_output_tokens);Q.inputTokens+=q+$+G,Q.cachedInputTokens+=G,Q.outputTokens+=W,Q.reasoningOutputTokens+=L,Q.totalTokens+=q+$+G+W+L,Y.set(J,Q)}return Y}function O9(_){let Y=[];for(let X of _){if(!I9(X))continue;Y.push(X)}return Y}function I9(_){if(_.type!=="user")return!1;if(_.isSidechain)return!1;if(_.isMeta)return!1;let Y=_.raw;if(Y&&typeof Y==="object"){if("toolUseResult"in Y)return!1}let X=_.message?.content;if(Array.isArray(X)){if(X.some((Q)=>P9(Q)))return!1}let J=T4(_);if(!J)return!1;let H=J.toLowerCase();if(O4.has(H))return!1;if(C4(J))return!1;if(I4.test(J))return!1;if(P4.some((Q)=>H.startsWith(Q))){if(!v4(J))return!1}return!0}function P9(_){if(!_||typeof _!=="object")return!1;let Y=_;if(Y.type==="tool_result")return!0;if(typeof Y.tool_use_id==="string")return!0;return!1}function C4(_){return E9.test(_)}function k9(_,Y=80){let X=T4(_);if(!X)return null;return C9(X,Y)}function C9(_,Y){let X=t0(_);if(X.length<=Y)return X;if(Y<=1)return X.slice(0,Y);return`${X.slice(0,Y-1)}…`}function $1(_){for(let Y of _)if(Y.cwd)return Y.cwd;return}function T9(_){let Y=$1(_),X=_.find((Q)=>Q.gitBranch)?.gitBranch??null;if(!Y)return B0.parse({relativeCwd:null,branch:X,repo:null});let J=Y.split(/[\\/]+/).filter(Boolean);if(J.length===0)return B0.parse({relativeCwd:null,branch:X,repo:null});let H=J.findIndex((Q)=>{let q=Q.toLowerCase();return q.includes("github")||q.includes("gitlab")||q.includes("bitbucket")});if(H>=0){let Q=J[H]?.toLowerCase()??"",q=Q.includes("gitlab")?"gitlab.com":Q.includes("bitbucket")?"bitbucket.org":"github.com",$=J[H+1],G=J[H+2]?.replace(/\.git$/i,"");if($&&G){let W=J.slice(H+3),L=W.length>0?W.join("/"):".";return B0.parse({relativeCwd:j2(L),branch:X,repo:`${q}/${$}/${G}`})}}return B0.parse({relativeCwd:null,branch:X,repo:null})}function v9(_){for(let Y of _){let X=typeof Y.sessionId==="string"?Y.sessionId.trim():"";if(X.length>0)return X}return null}function b9(_){let Y=null,X=-1;for(let[J,H]of _){let Q=H.totalTokens>0?H.totalTokens:H.inputTokens+H.outputTokens;if(Q>X)X=Q,Y=J}return Y}function T4(_){return Z9(_.message)[0]??null}function Z9(_){if(!_)return[];let Y=_.content;if(typeof Y==="string"){let X=Q1(Y);return X?[X]:[]}if(Array.isArray(Y)){let X=[];for(let J of Y){if(typeof J==="string"){let H=Q1(J);if(H)X.push(H);continue}if(J&&typeof J==="object"){let H=J,Q=["content","text"];for(let q of Q){let $=H[q];if(typeof $==="string"){let G=Q1($);if(G)X.push(G)}}}}return X}return[]}function Q1(_,Y=R9){let X=x9(_);if(X.length===0)return null;let H=X.slice(0,Y).join(" "),Q=t0(H);return Q.length>0?Q:null}function x9(_){let Y=[];for(let X of _.split(/\r?\n/)){let J=X.trim();if(!J)continue;let H=J.toLowerCase();if(O4.has(H))continue;if(C4(J))continue;if(I4.test(J))continue;if(P4.some((Q)=>H.startsWith(Q))){if(!v4(J))continue}if(!/[a-z]/i.test(J)&&!/\d/.test(J))continue;Y.push(J)}return Y}function t0(_){return _.replace(/\s+/g," ").trim()}function v4(_){let Y=_.toLowerCase();if(F9.test(Y))return!0;if(Y.includes("?"))return!0;return["can you","can we","could you","could we","would you","would we","should we","should i","let's","let us"].some((J)=>Y.includes(J))}function y9(_){return Math.max(0,_.inputTokens-_.cachedInputTokens)+_.outputTokens+_.reasoningOutputTokens}function b4(_){if(!_)return null;let Y=new Date(_);return Number.isNaN(Y.getTime())?null:Y}function S4(_){let Y=b4(_);return Y?Y.getTime():null}function a(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function w4(_){if(typeof _!=="string")return;let Y=_.trim();return Y.length>0?Y:void 0}function h9(_){return M9.createHash("sha256").update(_).digest("hex")}function q1(_,Y){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>q1(X,Y));if(typeof _==="object"){let X=_;if(X.type==="image"&&X.source&&typeof X.source==="object"){let H=X.source;if(typeof H.data==="string"&&H.data.length>0){let Q=H.data,q=typeof H.mediaType==="string"?H.mediaType:typeof H.media_type==="string"?H.media_type:"image/unknown",$=Buffer.from(Q,"base64"),G=h9($);if(!Y.has(G))Y.set(G,{data:$,mediaType:q});return{type:"image",source:{type:"sha256",mediaType:q,sha256:G}}}}let J={};for(let[H,Q]of Object.entries(X))J[H]=q1(Q,Y);return J}return _}function g9(_,Y){if(!Y||Object.keys(Y).length===0)return 0;let X=0;for(let J of _){let H=J.model;if(!H)continue;let Q=m9(H,Y);if(!Q)continue;let q=c9({input_tokens:a(J.usage.input_tokens),output_tokens:a(J.usage.output_tokens),cache_creation_input_tokens:a(J.usage.cache_creation_input_tokens),cache_read_input_tokens:a(J.usage.cache_read_input_tokens)},Q);X+=q}return X}function m9(_,Y){let X=_.trim();if(!X)return null;let J=new Set;J.add(X);for(let Q of U9)J.add(`${Q}${X}`);for(let Q of J){let q=Y[Q];if(q)return q}let H=X.toLowerCase();for(let[Q,q]of Object.entries(Y)){let $=Q.toLowerCase();if($.includes(H)||H.includes($))return q}return null}function c9(_,Y){let X=($,G,W,L=V9)=>{if($==null||$<=0)return 0;if($>L&&W!=null){let V=Math.min($,L),N=Math.max(0,$-L)*W;if(G!=null)N+=V*G;return N}if(G!=null)return $*G;return 0},J=X(_.input_tokens,Y.input_cost_per_token,Y.input_cost_per_token_above_200k_tokens),H=X(_.output_tokens,Y.output_cost_per_token,Y.output_cost_per_token_above_200k_tokens),Q=X(_.cache_creation_input_tokens,Y.cache_creation_input_token_cost,Y.cache_creation_input_token_cost_above_200k_tokens),q=X(_.cache_read_input_tokens,Y.cache_read_input_token_cost,Y.cache_read_input_token_cost_above_200k_tokens);return J+H+Q+q}function u9(_){let Y=[],X=new Map,J=new Map,H=$1(_);for(let Q of _){if(Q.isMeta)continue;let q=d9(Q),$=Q.type;if($==="user"){let{texts:G,toolResults:W}=l9(Q);for(let L of G){if(!L.trim())continue;Y.push(s.parse({type:Q.isCompactSummary?"compaction-summary":"user",text:L.trim(),id:Q.uuid,timestamp:q.timestamp}))}for(let L of W){let V=L.callId?J.get(L.callId):void 0;if(V){let E=Y[V.index];if(E.output=q1(L.output,X),L.error)E.error=L.error;if(typeof L.isError<"u")E.isError=L.isError;let N=z4(E,H);Y[V.index]=N}}continue}if($==="assistant"){let G=Q.message?.content;if(!Array.isArray(G))continue;for(let W of G){if(!W||typeof W!=="object")continue;let L=W;if(L.type==="thinking"&&typeof L.thinking==="string"){Y.push(s.parse({type:"thinking",text:L.thinking,...q}));continue}if(L.type==="text"&&typeof L.text==="string"){Y.push(s.parse({type:"agent",text:L.text,...q}));continue}if(L.type==="tool_use"){let V=typeof L.id==="string"?L.id:"",E=typeof L.name==="string"?L.name:null,N=L.input??void 0,v={type:"tool-call",toolName:E,...q,input:N},Z=s.parse(v),S=z4(Z,H);if(Y.push(S),V)J.set(V,{index:Y.length-1,toolName:E});continue}if(L.type==="image")continue}}}return{messages:Y,blobs:X}}function l9(_){let Y=_.message;if(!Y)return{texts:[],toolResults:[]};let X=Y.content;if(typeof X==="string"){let Q=t0(X);return Q?{texts:[Q],toolResults:[]}:{texts:[],toolResults:[]}}if(!Array.isArray(X))return{texts:[],toolResults:[]};let J=[],H=[];for(let Q of X){if(!Q||typeof Q!=="object")continue;if(typeof Q==="string"){let G=t0(Q);if(G)J.push(G);continue}let q=Q,$=typeof q.type==="string"?q.type:void 0;if($==="tool_result"){let G=q,W=typeof G.tool_use_id==="string"?G.tool_use_id:void 0,L=G.content,V=_.raw.toolUseResult??_.raw.tool_use_result;if(V)L=V;let E=typeof G.error==="string"?G.error:void 0,N=G.is_error??G.isError,v=typeof N==="boolean"?N:typeof G.success==="boolean"?!G.success:void 0;H.push({callId:W,output:L,error:E,isError:v});continue}if($==="text"&&typeof q.text==="string"){let G=t0(q.text);if(G)J.push(G);continue}for(let G of["content","text"]){let W=q[G];if(typeof W==="string"){let L=t0(W);if(L)J.push(L)}}}return{texts:J,toolResults:H}}function d9(_){return{id:_.message?.id,timestamp:_.timestamp,model:_.message?.model}}function z4(_,Y){if(!Y)return _;let X=Y.endsWith("/")?Y:`${Y}/`,J=(M)=>{if(M.startsWith(X))return`./${M.slice(X.length)}`;return M},H=(M)=>typeof M==="object"&&M!==null&&!Array.isArray(M),Q=(M)=>H(M)?{...M}:void 0,q=(M,R)=>{let z={...M};for(let k of R)delete z[k];return z},$=(M,R)=>{if(typeof M[R]==="string")M[R]=J(M[R])},G=(M)=>typeof M==="number"&&Number.isFinite(M)?M:0,W=(M)=>{if(!Array.isArray(M))return M;return M.map((R)=>{if(H(R)){let z={...R};return delete z.activeForm,z}return R})},{toolName:L,input:V,output:E}=_,N=V,v=E,Z=!1,S=!1,O=_.isError;switch(L){case"Write":{let M=Q(V);if(M)$(M,"file_path"),N=M,Z=!0;let R=Q(E);if(R){let z={};if(R.type!==void 0)z.type=R.type;v=z,S=!0}break}case"Read":{let M=Q(V);if(M)$(M,"file_path"),N=M,Z=!0;let R=Q(E);if(R){let z={};if(typeof R.type==="string")z.type=R.type;if(R.file&&H(R.file)){let k=R.file,C={};if(typeof k.content==="string")C.content=k.content;if(typeof k.numLines==="number")C.numLines=k.numLines;if(typeof k.startLine==="number")C.startLine=k.startLine;if(typeof k.totalLines==="number")C.totalLines=k.totalLines;if(Object.keys(C).length>0)z.file=C}v=z,S=!0}break}case"Edit":{let M=Q(V),R=Q(E),z;if(R&&Array.isArray(R.structuredPatch)){let k=[];for(let C of R.structuredPatch)if(H(C)&&Array.isArray(C.lines)){for(let j of C.lines)if(typeof j==="string")k.push(j)}if(k.length>0)z=`${k.join(`
30
+ `)}
31
+ `}if(M){$(M,"file_path");let k=typeof M.old_string==="string"?M.old_string:typeof M.oldString==="string"?M.oldString:void 0,C=typeof M.new_string==="string"?M.new_string:typeof M.newString==="string"?M.newString:void 0,j=O===!0||O==="true"||typeof E==="string"||R&&typeof R.type==="string"&&R.type==="error";if(!z&&!j&&k!==void 0&&C!==void 0){let y=k.split(`
32
+ `),I=C.split(`
33
+ `),h=[];for(let p of y)h.push(`-${p}`);for(let p of I)h.push(`+${p}`);z=`${h.join(`
34
+ `)}
35
+ `}if(delete M.old_string,delete M.new_string,delete M.oldString,delete M.newString,z)M.diff=z;N=M,Z=!0}if(R){let k=q(R,["filePath","newString","oldString","originalFile","structuredPatch","replaceAll"]);v=Object.keys(k).length>0?k:void 0,S=!0}break}case"Glob":case"Grep":{let M=Q(E);if(M&&Array.isArray(M.filenames))M.filenames=M.filenames.map((R)=>typeof R==="string"?J(R):R),delete M.numFiles,v=M,S=!0;break}case"Bash":{let M=Q(E);if(M)delete M.stdoutLines,delete M.stderrLines,v=M,S=!0;break}case"Task":{let M=Q(V);if(M)N=M,Z=!0;let R=Q(E);if(R){let z={};for(let[k,C]of Object.entries(R)){if(k==="usage"&&H(C)){let j=C,y=G(j.input_tokens??j.inputTokens),I=G(j.cached_input_tokens??j.cachedInputTokens)+G(j.cache_creation_input_tokens??j.cacheCreationInputTokens)+G(j.cache_read_input_tokens??j.cacheReadInputTokens),h=G(j.output_tokens??j.outputTokens),p=G(j.reasoning_output_tokens??j.reasoningOutputTokens),r=j.total_tokens??j.totalTokens,x1=typeof r==="number"&&Number.isFinite(r)?r:y+I+h+p;z.usage={inputTokens:y,cachedInputTokens:I,outputTokens:h,reasoningOutputTokens:p,totalTokens:x1};continue}if(k==="usage"||k==="totalTokens"||k==="prompt")continue;z[k]=C}v=z,S=!0}break}case"TodoWrite":{let M=Q(V);if(M){if(Array.isArray(M.todos))M.todos=W(M.todos);N=M,Z=!0}let R=Q(E);if(R){let z={...R},k=!1;if(Array.isArray(z.newTodos))z.newTodos=W(z.newTodos),k=!0;if(Array.isArray(z.oldTodos))z.oldTodos=W(z.oldTodos),k=!0;v=k?z:R,S=k}break}case"BashOutput":{let M=Q(E);if(M)delete M.stdoutLines,delete M.stderrLines,v=M,S=!0;break}default:break}if(L==="KillShell"&&typeof O==="boolean")O=String(O);let c={..._};if(Z)if(typeof N>"u")delete c.input;else c.input=N;if(S)if(typeof v>"u")delete c.output;else c.output=v;if(typeof O>"u"){if(typeof c.error==="string"&&c.error.trim())O=!0;else if(typeof v==="string"&&/^error:/i.test(v.trim()))O=!0}if(typeof O<"u")c.isError=O;let u={},K=["id","input","model","output","timestamp","toolName","error","isError","type"];for(let M of K)if(Object.prototype.hasOwnProperty.call(c,M))u[M]=c[M];for(let M of Object.keys(c))if(!Object.prototype.hasOwnProperty.call(u,M))u[M]=c[M];return A4.parse(u)}import G1 from"node:path";var W1={inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0},p9=["anthropic/","claude-3-5-","claude-3-","claude-","openai/","azure/","openrouter/openai/"],n9=200000,i9={shell:"Bash"},r9=["<user_instructions","<environment_context"];function V1(_,Y={}){let X=o9(_);if(X.length===0)return null;let J=new Map,H=new Set,Q=[],q=[],$=null,G=null,W=null,L,V={...W1},E={...W1};for(let d of X){if(!d)continue;let{type:M,payload:R,timestamp:z}=d;if(z&&(!L||MY(z,L)>0))L=z;if(M==="session_meta"&&R){if($=s9(R),!G)G=$.cwd;continue}if(M==="turn_context"&&R){let C=x(R.cwd);if(C)G=C;let j=x(R.model);if(j)W=j;continue}if(M==="event_msg"&&R){if(x(R.type)==="token_count"){let j=Z4(R.info,"last_token_usage"),y=Z4(R.info,"total_token_usage"),I=null;if(j)I=j;else if(y)I={inputTokens:Math.max(0,y.inputTokens-E.inputTokens),cachedInputTokens:Math.max(0,y.cachedInputTokens-E.cachedInputTokens),outputTokens:Math.max(0,y.outputTokens-E.outputTokens),reasoningOutputTokens:Math.max(0,y.reasoningOutputTokens-E.reasoningOutputTokens),totalTokens:Math.max(0,y.totalTokens-E.totalTokens)};if(I)V={inputTokens:V.inputTokens+I.inputTokens,cachedInputTokens:V.cachedInputTokens+I.cachedInputTokens,outputTokens:V.outputTokens+I.outputTokens,reasoningOutputTokens:V.reasoningOutputTokens+I.reasoningOutputTokens,totalTokens:V.totalTokens+I.totalTokens};if(y)E=y}continue}if(M!=="response_item"||!R)continue;switch(x(R.type)){case"message":{let C=x(R.role),j=a9(R.content);if(j.length===0)break;let y=e0(j.join(`
36
+
37
+ `));if(!y)break;if(C==="user"){if(qY(y))break;q.push(y);let I=x(R.id),h={type:"user",timestamp:z,text:y};if(I)h.id=I;B1(h,Q,H)}else if(C==="assistant"){let I=x(R.id),h={type:"agent",timestamp:z,model:W??void 0,text:y};if(I)h.id=I;B1(h,Q,H)}break}case"reasoning":{let C=t9(R);for(let j of C){let y=x(R.id),I={type:"thinking",timestamp:z,model:W??void 0,text:j};if(y)I.id=y;B1(I,Q,H)}break}case"function_call":{let C=x(R.call_id)??x(R.id)??void 0,j=x(R.name),y=y4(j),I=L1(R.arguments),h=e9(I,G),p=s.parse({type:"tool-call",id:C,timestamp:z,model:W??void 0,toolName:y,input:h}),r=M1(p,G,j);J.set(C??"",{index:Q.push(r)-1,rawName:j});break}case"function_call_output":{let C=x(R.call_id);if(!C)break;let j=J.get(C);if(!j)break;let y=L1(R.output),I=x4(Q[j.index],y,G,j.rawName);Q[j.index]=I;break}case"custom_tool_call":{let C=x(R.call_id)??x(R.id)??void 0,j=x(R.name),y=y4(j),I=_Y(j,R.input,G),h=s.parse({type:"tool-call",id:C,timestamp:z,model:W??void 0,toolName:y,input:I}),p=M1(h,G,j);J.set(C??"",{index:Q.push(p)-1,rawName:j});break}case"custom_tool_call_output":{let C=x(R.call_id);if(!C)break;let j=J.get(C);if(!j)break;let y=L1(R.output),I=x4(Q[j.index],y,G,j.rawName);Q[j.index]=I;break}default:break}}if(Q.length===0)return null;let N=VY(L)??Y.now??new Date,v=$Y(q),Z=V??{...W1},S=QY(Z),O=EY(W,Z,Y.pricing),c=Y.gitContext!==void 0?Y.gitContext:GY($,G),u=G?k0(G):"";return{transcript:U2.parse({v:1,id:$?.id??Q[0]?.id??UY(N),source:"codex",timestamp:N,preview:v,model:W,blendedTokens:S,costUsd:O,messageCount:Q.length,tokenUsage:Z,modelUsage:W?[O2.parse({model:W,usage:Z})]:[],git:c,cwd:u,messages:Q}),blobs:new Map}}function o9(_){let Y=[];for(let X of _){if(!X||typeof X!=="object")continue;let J=X,H=x(J.type);if(!H)continue;let Q=x(J.timestamp)??void 0,q=J.payload&&typeof J.payload==="object"?J.payload:null;Y.push({type:H,timestamp:Q,payload:q})}return Y}function s9(_){let Y=_.git??{};return{id:x(_.id),cwd:x(_.cwd),git:{branch:x(Y.branch),repositoryUrl:x(Y.repository_url??Y.repositoryUrl)}}}function Z4(_,Y="total_token_usage"){if(!_||typeof _!=="object")return null;let X=_,J;if(Y==="last_token_usage")J=X.last_token_usage??X.lastTokenUsage??X.total_token_usage??X.totalTokenUsage;else J=X.total_token_usage??X.totalTokenUsage??X.last_token_usage??X.lastTokenUsage;if(!J||typeof J!=="object")return null;let H=J;return{inputTokens:R0(H.input_tokens??H.inputTokens),cachedInputTokens:R0(H.cached_input_tokens??H.cachedInputTokens),outputTokens:R0(H.output_tokens??H.outputTokens),reasoningOutputTokens:R0(H.reasoning_output_tokens??H.reasoningOutputTokens),totalTokens:R0(H.total_tokens??H.totalTokens)}}function a9(_){if(typeof _==="string"){let X=e0(_);return X?[X]:[]}if(!Array.isArray(_))return[];let Y=[];for(let X of _){if(!X)continue;if(typeof X==="string"){let J=e0(X);if(J)Y.push(J);continue}if(typeof X==="object"){let J=X,H=x(J.text??J.content);if(H){let Q=e0(H);if(Q)Y.push(Q)}}}return Y}function t9(_){let Y=[],X=_.summary;if(Array.isArray(X)){for(let H of X)if(H&&typeof H==="object"){let Q=x(H.text);if(Q){let q=e0(Q);if(q)Y.push(q)}}}let J=_.content;if(Array.isArray(J)){for(let H of J)if(H&&typeof H==="object"){let Q=H;if(x(Q.type)==="reasoning"||x(Q.type)==="text"){let q=x(Q.text??Q.content);if(q){let $=e0(q);if($)Y.push($)}}}}return Y}function L1(_){let Y=x(_);if(!Y)return _;try{return JSON.parse(Y)}catch{return _}}function e9(_,Y){if(!_||typeof _!=="object")return _;let X={..._};if(typeof X.workdir==="string"&&Y)X.workdir=_2(X.workdir,Y);return X}function _Y(_,Y,X){if(!Y)return Y;if(_==="apply_patch"){let J=x(Y);if(!J)return Y;let H=HY(J,X);if(H.diff||H.file_path)return H}return Y}function x4(_,Y,X,J){if(_.type!=="tool-call")return _;let H=Y;if(J==="shell")H=XY(Y);else if(J==="apply_patch")H=JY(Y);let Q={..._,output:H};if(J==="shell"){let q=YY(Q,X);if(q)return q}return M1(Q,X,J)}function YY(_,Y){if(_.type!=="tool-call"||!_.input)return null;let J=_.input.command;if(!Array.isArray(J)||J.length<3)return null;let H=J[0];if(H!=="bash"&&H!=="zsh"||J[1]!=="-lc")return null;let Q=x(J[2]);if(!Q)return null;let q=Q.match(/^cat\s+<<'EOF'\s+>\s+(\S+)\s*\n([\s\S]*?)EOF$/);if(q){let[,G,W]=q,L=Y?_2(`${Y}/${G}`,Y):`./${G}`;return s.parse({..._,toolName:"Write",input:{file_path:L,content:W||""},output:void 0})}let $=Q.match(/^cat\s+(\S+)$/);if($){let[,G]=$,W=Y?_2(`${Y}/${G}`,Y):`./${G}`,L;if(_.output&&typeof _.output==="object"){let V=_.output;L=x(V.stdout)??void 0}return s.parse({..._,toolName:"Read",input:{file_path:W},output:L})}return null}function M1(_,Y,X){if(_.type!=="tool-call")return _;let{toolName:J,input:H,output:Q}=_;if(X==="shell"){if(J="Bash",H&&typeof H==="object"){let q={...H};if(typeof q.workdir==="string"&&Y)q.workdir=_2(q.workdir,Y);H=q}}if(X==="apply_patch"){if(J="Edit",H&&typeof H==="object"){let q={...H},$=x(q.file_path);if($&&Y)q.file_path=_2($,Y);H=q}}return s.parse({..._,toolName:J,input:H,output:Q})}function XY(_){if(!_||typeof _!=="object")return _;let Y=_,X={},J=x(Y.output??Y.stdout);if(typeof Y.stdout==="string")X.stdout=Y.stdout;else if(J)X.stdout=J;let H=x(Y.stderr);if(H)X.stderr=H;let Q=Y.metadata&&typeof Y.metadata==="object"?Y.metadata:{},q=R0(Q.exit_code??Q.exitCode??Y.exit_code??Y.exitCode);if(Number.isFinite(q))X.exitCode=q;let $=R0(Q.duration_seconds??Q.durationSeconds);if(Number.isFinite($)&&$>0)X.durationSeconds=$;return Object.keys(X).length>0?X:void 0}function JY(_){if(!_||typeof _!=="object")return _;let Y=_,X={},J=x(Y.output);if(J)X.message=J;let H=Y.metadata&&typeof Y.metadata==="object"?Y.metadata:null;if(H){let Q=R0(H.exit_code??H.exitCode);if(Number.isFinite(Q))X.exitCode=Q;let q=R0(H.duration_seconds??H.durationSeconds);if(Number.isFinite(q)&&q>0)X.durationSeconds=q}return Object.keys(X).length>0?X:void 0}function HY(_,Y){let X=_.split(/\r?\n/),J=null,H=[];for(let $ of X){if($.startsWith("*** ")){let G=$.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/);if(G&&G[1])J=G[1].trim();continue}H.push($)}let Q=H.join(`
38
+ `).trim(),q={};if(J)q.file_path=Y?_2(J,Y):J;if(Q)q.diff=Q.endsWith(`
39
+ `)?Q:`${Q}
40
+ `;return q}function _2(_,Y){if(!_)return _;let X=G1.isAbsolute(_),J=_.replace(/\\/g,"/");if(!X){if(J==="."||J==="./")return".";if(J.startsWith("./")||J.startsWith("../"))return J;return`./${J}`}try{let H=G1.relative(Y,_).replace(/\\/g,"/");if(H==="")return".";if(H.startsWith("..")||G1.isAbsolute(H))return _;return H==="."?".":`./${H}`}catch{return _}}function QY(_){return Math.max(0,_.inputTokens-_.cachedInputTokens)+_.outputTokens+_.reasoningOutputTokens}function qY(_){let Y=_.trim().toLowerCase();return r9.some((X)=>Y.startsWith(X))}function $Y(_){for(let Y of _){let X=Y.trim();if(!X)continue;if(X.startsWith("<user_instructions>")||X.startsWith("<environment_context>"))continue;return h4(X,80)}return _.length>0?h4(_[0],80):null}function GY(_,Y){let X=Y??_?.cwd??null;if(!_)return B0.parse({repo:null,branch:null,relativeCwd:null});let J=WY(_.git.repositoryUrl),H=_.git.branch,Q=J?J.split("/").pop()??null:null,q=LY(X,Q);return B0.parse({repo:J,branch:H,relativeCwd:j2(q)})}function WY(_){if(!_)return null;let Y=_.match(/git@([^:]+):(.+?)(?:\.git)?$/);if(Y)return`${Y[1]}/${Y[2]}`.replace(/\\/g,"/");let X=_.match(/https?:\/\/([^/]+)\/(.+?)(?:\.git)?$/);if(X)return`${X[1]}/${X[2]}`.replace(/\\/g,"/");return null}function LY(_,Y){if(!_)return null;let J=_.replace(/\\/g,"/").split("/").filter(Boolean);if(J.length===0)return null;if(Y){let H=J.lastIndexOf(Y);if(H>=0){let Q=J.slice(H+1).join("/");return Q.length>0?Q:"."}}return null}function B1(_,Y,X){let J=BY(_);if(J&&X.has(J))return;let H=s.parse(_);if(Y.push(H),J)X.add(J)}function BY(_){if("text"in _&&typeof _.text==="string")return`${_.type}|${_.timestamp??""}|${_.text}`;if(_.type==="tool-call")return`${_.type}|${_.timestamp??""}|${_.id??""}|${_.toolName??""}`;return null}function y4(_){if(!_)return _;return i9[_]??_}function MY(_,Y){let X=Date.parse(_),J=Date.parse(Y);if(Number.isNaN(X)||Number.isNaN(J))return 0;return X===J?0:X>J?1:-1}function VY(_){if(!_)return null;let Y=new Date(_);return Number.isNaN(Y.getTime())?null:Y}function R0(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function x(_){if(typeof _!=="string")return null;let Y=_.trim();return Y.length>0?Y:null}function e0(_){return _.replace(/\s+/g," ").trim()}function h4(_,Y){if(_.length<=Y)return _;if(Y<=1)return _.slice(0,Y);return`${_.slice(0,Y-1)}…`}function UY(_){return`codex-${_.getTime()}`}function EY(_,Y,X){if(!X||!_)return 0;let J=FY(_,X);if(!J)return 0;return RY({input_tokens:Math.max(0,Y.inputTokens-Y.cachedInputTokens),output_tokens:Y.outputTokens+Y.reasoningOutputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:Y.cachedInputTokens},J)}function FY(_,Y){let X=_.trim();if(!X)return null;let J=new Set;J.add(X);for(let Q of p9)J.add(`${Q}${X}`);for(let Q of J){let q=Y[Q];if(q)return q}let H=X.toLowerCase();for(let[Q,q]of Object.entries(Y)){let $=Q.toLowerCase();if($.includes(H)||H.includes($))return q}return null}function RY(_,Y){let X=($,G,W,L=n9)=>{if($==null||$<=0)return 0;if($>L&&W!=null){let V=Math.min($,L),N=Math.max(0,$-L)*W;if(G!=null)N+=V*G;return N}if(G!=null)return $*G;return 0},J=X(_.input_tokens,Y.input_cost_per_token,Y.input_cost_per_token_above_200k_tokens),H=X(_.output_tokens,Y.output_cost_per_token,Y.output_cost_per_token_above_200k_tokens),Q=X(_.cache_creation_input_tokens,Y.cache_creation_input_token_cost,Y.cache_creation_input_token_cost_above_200k_tokens),q=X(_.cache_read_input_tokens,Y.cache_read_input_token_cost,Y.cache_read_input_token_cost_above_200k_tokens);return J+H+Q+q}var fY="https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json",KY=200000,DY=B.object({input_cost_per_token:B.number().optional(),output_cost_per_token:B.number().optional(),cache_creation_input_token_cost:B.number().optional(),cache_read_input_token_cost:B.number().optional(),max_tokens:B.number().optional(),max_input_tokens:B.number().optional(),max_output_tokens:B.number().optional(),input_cost_per_token_above_200k_tokens:B.number().optional(),output_cost_per_token_above_200k_tokens:B.number().optional(),cache_creation_input_token_cost_above_200k_tokens:B.number().optional(),cache_read_input_token_cost_above_200k_tokens:B.number().optional(),input_cost_per_token_above_128k_tokens:B.number().optional(),output_cost_per_token_above_128k_tokens:B.number().optional()}),jY=["anthropic/","claude-3-5-","claude-3-","claude-","openai/","azure/","openrouter/openai/"];function NY(_){if(_!=null)return _;return{debug:()=>{},error:()=>{},info:()=>{},warn:()=>{}}}class U1{cachedPricing=null;logger;offline;offlineLoader;url;providerPrefixes;constructor(_={}){this.logger=NY(_.logger),this.offline=Boolean(_.offline),this.offlineLoader=_.offlineLoader,this.url=_.url??fY,this.providerPrefixes=_.providerPrefixes??jY}[Symbol.dispose](){this.clearCache()}clearCache(){this.cachedPricing=null}async loadOfflinePricing(){if(this.offlineLoader==null)throw Error("Offline loader was not provided");let _=new Map(Object.entries(await this.offlineLoader()));return this.cachedPricing=_,_}async fetchRemotePricing(){this.logger.warn("Fetching latest model pricing from LiteLLM...");let _=await fetch(this.url);if(!_.ok)throw Error(`Failed to fetch pricing data: ${_.statusText}`);let Y=await _.json(),X=new Map;for(let[J,H]of Object.entries(Y)){if(typeof H!=="object"||H==null)continue;let Q=DY.safeParse(H);if(!Q.success)continue;X.set(J,Q.data)}return this.cachedPricing=X,this.logger.info(`Loaded pricing for ${X.size} models`),X}async ensurePricingLoaded(){if(this.cachedPricing!=null)return this.cachedPricing;if(this.offline)return this.loadOfflinePricing();try{return await this.fetchRemotePricing()}catch(_){if(this.logger.warn("Failed to fetch model pricing from LiteLLM, falling back to offline loader (if available)."),this.offlineLoader!=null)return this.loadOfflinePricing();throw _}}async fetchModelPricing(){return this.ensurePricingLoaded()}createMatchingCandidates(_){let Y=new Set;Y.add(_);for(let X of this.providerPrefixes)Y.add(`${X}${_}`);return Array.from(Y)}async getModelPricing(_){let Y=await this.ensurePricingLoaded();for(let J of this.createMatchingCandidates(_)){let H=Y.get(J);if(H!=null)return H}let X=_.toLowerCase();for(let[J,H]of Y){let Q=J.toLowerCase();if(Q.includes(X)||X.includes(Q))return H}return null}async getModelContextLimit(_){return(await this.getModelPricing(_))?.max_input_tokens??null}calculateCostFromPricing(_,Y){let X=($,G,W,L=KY)=>{if($==null||$<=0)return 0;if($>L&&W!=null){let V=Math.min($,L),N=Math.max(0,$-L)*W;if(G!=null)N+=V*G;return N}if(G!=null)return $*G;return 0},J=X(_.input_tokens,Y.input_cost_per_token,Y.input_cost_per_token_above_200k_tokens),H=X(_.output_tokens,Y.output_cost_per_token,Y.output_cost_per_token_above_200k_tokens),Q=X(_.cache_creation_input_tokens,Y.cache_creation_input_token_cost,Y.cache_creation_input_token_cost_above_200k_tokens),q=X(_.cache_read_input_tokens,Y.cache_read_input_token_cost,Y.cache_read_input_token_cost_above_200k_tokens);return J+H+Q+q}async calculateCostFromTokens(_,Y){if(Y==null||Y==="")return 0;let X=await this.getModelPricing(Y);if(X==null)throw Error(`Model pricing not found for ${Y}`);return this.calculateCostFromPricing(_,X)}}import{execSync as AY}from"child_process";import{resolve as SY}from"path";var wY="http://localhost:3000",zY=1e4;async function OY(_,Y,X){try{return(await fetch(`${Y}/api/blobs/${_}`,{method:"HEAD",headers:{...X&&{Authorization:`Bearer ${X}`}},signal:AbortSignal.timeout(5000)})).ok}catch{return!1}}async function IY(_,Y,X){if(!_||_.length===0)return;let H=(await Promise.all(_.map(async(Q)=>({blob:Q,exists:await OY(Q.sha256,Y,X)})))).filter((Q)=>!Q.exists).map((Q)=>Q.blob);return H.length>0?H:void 0}async function g4(_,Y={}){let X=Y.serverUrl??process.env.VI_SERVER_URL??wY,J=Y.authToken??null,H=Y.timeoutMs??zY,Q=await IY(_.blobs,X,J),q=new FormData,$=`${_.unifiedTranscript.id||"transcript"}.jsonl`;if(q.set("sha256",_.sha256),q.set("unifiedTranscript",JSON.stringify(_.unifiedTranscript)),q.set("transcript",new Blob([_.rawTranscript],{type:"application/jsonl"}),$),Q)for(let G of Q){let W=G.data.buffer.slice(G.data.byteOffset,G.data.byteOffset+G.data.byteLength);q.append(`blob:${G.sha256}`,new Blob([W],{type:G.mediaType}),`${G.sha256}.blob`)}try{let G=await fetch(`${X}/api/ingest`,{method:"POST",headers:{...J&&{Authorization:`Bearer ${J}`}},body:q,signal:AbortSignal.timeout(H)});if(!G.ok)return console.error(`Upload failed: ${G.status} ${G.statusText}`),{success:!1};let W=await G.json();if(PY(W))return{success:!0,transcriptId:W.transcriptId};return console.error("Upload succeeded but response had unexpected shape:",W),{success:!1}}catch(G){if(G instanceof Error)console.error("Upload error:",G.message);return{success:!1}}}function PY(_){if(typeof _!=="object"||_===null)return!1;let Y=_;return typeof Y.success==="boolean"&&(Y.success===!1||typeof Y.transcriptId==="string")&&(Y.eventsReceived===void 0||typeof Y.eventsReceived==="number")}function m4(_){let Y=SY(_),X=k0(Y);try{let J=AY("git remote get-url origin",{cwd:Y,encoding:"utf8",timeout:2000,stdio:["pipe","pipe","ignore"]}).trim(),H=kY(J),Q=H.split("/").pop()||"unknown";return{repoId:H,repoName:Q,cwd:X}}catch{return{repoId:null,repoName:Y.split("/").pop()||"unknown",cwd:X}}}function kY(_){let Y=/^(?<user>[^@]+)@(?<host>[^:]+):(?<path>.+)$/,X=_.match(Y);if(X?.groups)return`${X.groups.host}/${X.groups.path.replace(/\.git$/i,"")}`;try{let J=new URL(_),H=J.pathname.replace(/\.git$/i,"").replace(/^\//,"");return`${J.host}/${H}`}catch{return _.replace(/\.git$/i,"")}}async function A0(_,Y={}){let{transcriptPath:X,sessionId:J,source:H="claude-code"}=_;if(!X)throw Error("No transcript path provided.");if(!E1(X))throw Error(`Transcript file not found at path: ${X}`);let Q=TY(X,"utf8"),q=Q.split(/\r?\n/),$=[],G=0;for(let R of q){let z=R.trim();if(!z)continue;try{let k=JSON.parse(z);if(typeof k==="object"&&k!==null)$.push(k);else G+=1}catch{G+=1}}if(G>0)console.warn(`Skipped ${G} line(s) that were not valid JSON.`);if($.length===0)throw Error("No transcript events found in the specified file.");let L=await new U1().fetchModelPricing(),E={pricing:Object.fromEntries(L)},N=_.cwdOverride&&_.cwdOverride.trim().length>0?_.cwdOverride.trim():xY($)??process.cwd(),v=H==="codex"?V1($,E):k4($,E);if(!v)throw Error(`Unable to convert ${H} transcript to unified format.`);let{transcript:Z,blobs:S}=v,O=J??Z.id;if(!O)throw Error("Transcript did not include a session identifier.");if(J&&J!==Z.id)throw Error(`Provided sessionId (${J}) does not match unified transcript id (${Z.id}).`);let c=$.length,u=CY("sha256").update(Q).digest("hex"),K=[];for(let[R,z]of S)K.push({sha256:R,data:new Uint8Array(z.data),mediaType:z.mediaType});let d={sha256:u,rawTranscript:Q,unifiedTranscript:Z,blobs:K.length>0?K:void 0};return{...await g4(d,Y),eventCount:c,invalidLines:G,sessionId:O,unifiedTranscript:Z,sha256:u,source:H,cwd:N}}function c4(_){if(!_)return null;if(bY(_))return E1(_)?_:null;let Y=new Set,X=(Q)=>{if(!Q)return null;let q=ZY(Q,_);if(Y.has(q))return null;return Y.add(q),E1(q)?q:null},J=X(process.cwd())??X(process.env.INIT_CWD)??X(process.env.PWD);if(J)return J;let H=process.cwd();while(!0){let Q=X(H);if(Q)return Q;let q=vY(H);if(q===H)break;H=q}return null}function xY(_){for(let Y of _){let X=typeof Y.cwd==="string"?Y.cwd.trim():"";if(X)return X}return null}var yY=D2(),m=J4("cli",{logFilePath:yY,logToFile:!0,disableConsole:!0});async function u4(){let _=Date.now(),Y,X;try{let{preview:J,full:H}=await uY();if(m.info(`Hook invoked (stdin: ${H.length} bytes)`),!H.trim())m.warn("Hook received empty stdin - ignoring"),process.exit(0);let Q=J.includes('"PreToolUse"'),q=J.includes("git")&&J.includes("commit");if(Q&&!q){let W={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};process.stdout.write(JSON.stringify(W));let L=Date.now()-_;m.info(`Hook completed: PreToolUse (fast path, ${L}ms)`),process.exit(0)}let $;try{$=JSON.parse(H)}catch(W){m.error("Hook failed to parse stdin JSON",{error:W instanceof Error?W.message:W}),process.exit(1)}if(Y=$.hook_event_name,X=$.session_id||"unknown",!Y)m.error("Hook missing event name",{sessionId:X}),process.exit(1);if(m.info(`Hook: ${Y} (session: ${X.substring(0,8)}...)`),Y==="PreToolUse")await hY($);else if(Y==="SessionEnd")await gY($);else if(Y==="Stop")await mY($);else m.debug(`Hook: skipping unsupported event ${Y}`);let G=Date.now()-_;m.info(`Hook completed: ${Y} (${G}ms)`,{sessionId:X.substring(0,8)}),process.exit(0)}catch(J){let H=Date.now()-_;m.error(`Hook failed: ${Y||"unknown"} (${H}ms)`,{sessionId:X?.substring(0,8),error:J instanceof Error?J.message:String(J)}),process.exit(1)}}async function hY(_){let Y=_.session_id||"unknown",X=!1,J=!1,{command:H,updateCommand:Q}=lY(_),q=typeof _.tool_name==="string"?_.tool_name:_.tool;if((q?q.toLowerCase()==="bash":Boolean(H))&&H&&dY(H)){X=!0;let W=pY(H,Y);if(W!==H)Q(W),J=!0}let G=J?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:_.tool_input}}:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};if(process.stdout.write(JSON.stringify(G)),X)await rY({sessionId:Y,transcriptPath:_.transcript_path,cwd:typeof _.cwd==="string"?_.cwd:void 0}),await iY({sessionId:Y,repoPath:nY(_),timestamp:new Date().toISOString()});m.info("PreToolUse handled",{sessionId:Y.substring(0,8),shouldTrack:X,modified:J})}async function gY(_){let Y=_.transcript_path,X=_.session_id||"unknown";if(!Y){m.error("SessionEnd: missing transcript_path",{sessionId:X});return}let J=t(),H=process.env.VI_SERVER_URL??process.env.VIBEINSIGHTS_BASE_URL??J.baseURL??"http://localhost:3000",Q=e();if(!Q){m.error("SessionEnd: no auth token found. Run the CLI login flow first.",{sessionId:X});return}let q={};if(H)q.serverUrl=H;q.authToken=Q;try{let $=await A0({transcriptPath:Y,sessionId:_.session_id,cwdOverride:_.cwd},q);if($.success)m.info(`SessionEnd: uploaded ${$.eventCount} events`,{transcriptId:$.transcriptId,sessionId:X.substring(0,8)});else m.error("SessionEnd: upload failed",{sessionId:X})}catch($){m.error("SessionEnd: upload error",{sessionId:X,error:$ instanceof Error?$.message:String($)})}}async function mY(_){let Y=_.transcript_path,X=_.session_id||"unknown";if(!Y){m.error("Stop: missing transcript_path",{sessionId:X});return}if(_.stop_hook_active){m.debug("Stop: skipped (stop_hook_active=true)",{sessionId:X});return}let J=t(),H=process.env.VI_SERVER_URL??process.env.VIBEINSIGHTS_BASE_URL??J.baseURL??"http://localhost:3000",Q=e();if(!Q){m.error("Stop: no auth token found. Run the CLI login flow first.",{sessionId:X});return}let q={};if(H)q.serverUrl=H;q.authToken=Q;try{let $=await A0({transcriptPath:Y,sessionId:_.session_id,cwdOverride:_.cwd},q);if($.success)m.info(`Stop: uploaded ${$.eventCount} events`,{transcriptId:$.transcriptId,sessionId:X.substring(0,8)});else m.error("Stop: upload failed",{sessionId:X})}catch($){m.error("Stop: upload error",{sessionId:X,error:$ instanceof Error?$.message:String($)})}}var cY=2048;function uY(){return new Promise((_,Y)=>{let X="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(J)=>{X+=J}),process.stdin.on("end",()=>{_({preview:X.slice(0,cY),full:X})}),process.stdin.on("error",(J)=>Y(J))})}function lY(_){if(_.tool_input&&typeof _.tool_input==="object"&&typeof _.tool_input.command==="string")return{command:_.tool_input.command,updateCommand:(Y)=>{if(_.tool_input)_.tool_input.command=Y}};if(typeof _.command==="string")return{command:_.command,updateCommand:(Y)=>{_.command=Y}};return{command:void 0,updateCommand:()=>{}}}function dY(_){return/\bgit\s+commit\b/.test(_)}function pY(_,Y){let X=`\uD83D\uDD2E View transcript: https://agentlogs.ai/s/${Y}`;if(_.includes(X))return _;let J=`
41
+
42
+ ${X}`,H=[{regex:/(\s--message=)"([^"]*)"/,quote:'"',equalsForm:!0},{regex:/(\s--message=)'([^']*)'/,quote:"'",equalsForm:!0},{regex:/(\s(?:-m|--message|-am))\s+"([^"]*)"/,quote:'"',equalsForm:!1},{regex:/(\s(?:-m|--message|-am))\s+'([^']*)'/,quote:"'",equalsForm:!1}];for(let{regex:Q,quote:q,equalsForm:$}of H){let G=_.match(Q);if(G){let W=G[1],L=G[2];if($)return _.replace(Q,`${W}${q}${L}${J}${q}`);return _.replace(Q,`${W} ${q}${L}${J}${q}`)}}return _}function nY(_){if(typeof _.repo_path==="string")return _.repo_path;if(typeof _.cwd==="string")return _.cwd;return""}async function iY(_){let Y=t(),X=process.env.VI_SERVER_URL??process.env.VIBEINSIGHTS_BASE_URL??Y.baseURL??"http://localhost:3000",J=e();if(!J){m.warn("Commit tracking skipped: no auth token. Run 'agentlogs login' first.",{sessionId:_.sessionId.substring(0,8)});return}try{let H=new AbortController,Q=setTimeout(()=>H.abort(),5000),q=await fetch(new URL("/api/commit-track",X),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${J}`},body:JSON.stringify({session_id:_.sessionId,repo_path:_.repoPath,timestamp:_.timestamp}),signal:H.signal});if(clearTimeout(Q),!q.ok){m.warn("Commit tracking request failed",{sessionId:_.sessionId.substring(0,8),status:q.status});return}m.info("Commit tracking recorded",{sessionId:_.sessionId.substring(0,8),repoPath:_.repoPath})}catch(H){if(H instanceof Error&&H.name==="AbortError"){m.warn("Commit tracking request timed out after 5s",{sessionId:_.sessionId.substring(0,8)});return}m.error("Commit tracking request error",{sessionId:_.sessionId.substring(0,8),error:H instanceof Error?H.message:String(H)})}}async function rY(_){if(!_.transcriptPath){m.warn("Commit tracking transcript upload skipped: missing transcript_path",{sessionId:_.sessionId.substring(0,8)});return}let Y=t(),X=process.env.VI_SERVER_URL??process.env.VIBEINSIGHTS_BASE_URL??Y.baseURL??"http://localhost:3000",J=e();if(!J){m.warn("Commit tracking transcript upload skipped: no auth token. Run 'agentlogs login' first.",{sessionId:_.sessionId.substring(0,8)});return}let H={};if(X)H.serverUrl=X;H.authToken=J;try{let Q=await A0({transcriptPath:_.transcriptPath,sessionId:_.sessionId,cwdOverride:_.cwd},H);if(Q.success)m.info("Commit tracking: uploaded partial transcript",{transcriptId:Q.transcriptId,sessionId:_.sessionId.substring(0,8),eventCount:Q.eventCount});else m.error("Commit tracking: transcript upload failed",{sessionId:_.sessionId.substring(0,8)})}catch(Q){m.error("Commit tracking: transcript upload error",{sessionId:_.sessionId.substring(0,8),error:Q instanceof Error?Q.message:String(Q)})}}import z1 from"node:process";import{Buffer as e4}from"node:buffer";import _6 from"node:path";import{fileURLToPath as DX}from"node:url";import{promisify as jX}from"node:util";import Y6 from"node:child_process";import NX,{constants as AX}from"node:fs/promises";import n4 from"node:process";import i4,{constants as YX}from"node:fs/promises";import p4 from"node:process";import eY from"node:os";import _X from"node:fs";import aY from"node:fs";import l4 from"node:fs";var F1;function oY(){try{return l4.statSync("/.dockerenv"),!0}catch{return!1}}function sY(){try{return l4.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function R1(){if(F1===void 0)F1=oY()||sY();return F1}var f1,tY=()=>{try{return aY.statSync("/run/.containerenv"),!0}catch{return!1}};function Y2(){if(f1===void 0)f1=tY()||R1();return f1}var d4=()=>{if(p4.platform!=="linux")return!1;if(eY.release().toLowerCase().includes("microsoft")){if(Y2())return!1;return!0}try{return _X.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!Y2():!1}catch{return!1}},S0=p4.env.__IS_WSL_TEST__?d4:d4();var XX=(()=>{let Y;return async function(){if(Y)return Y;let X="/etc/wsl.conf",J=!1;try{await i4.access(X,YX.F_OK),J=!0}catch{}if(!J)return"/mnt/";let H=await i4.readFile(X,{encoding:"utf8"}),Q=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(H);if(!Q)return"/mnt/";return Y=Q.groups.mountPoint.trim(),Y=Y.endsWith("/")?Y:`${Y}/`,Y}})(),JX=async()=>{return`${await XX()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},K1=async()=>{if(S0)return JX();return`${n4.env.SYSTEMROOT||n4.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`};function w0(_,Y,X){let J=(H)=>Object.defineProperty(_,Y,{value:H,enumerable:!0,writable:!0});return Object.defineProperty(_,Y,{configurable:!0,enumerable:!0,get(){let H=X();return J(H),H},set(H){J(H)}}),_}import{promisify as FX}from"node:util";import S1 from"node:process";import{execFile as RX}from"node:child_process";import{promisify as HX}from"node:util";import QX from"node:process";import{execFile as qX}from"node:child_process";var $X=HX(qX);async function D1(){if(QX.platform!=="darwin")throw Error("macOS only");let{stdout:_}=await $X("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(_)?.groups.id??"com.apple.Safari"}import GX from"node:process";import{promisify as WX}from"node:util";import{execFile as LX,execFileSync as rH}from"node:child_process";var BX=WX(LX);async function r4(_,{humanReadableOutput:Y=!0,signal:X}={}){if(GX.platform!=="darwin")throw Error("macOS only");let J=Y?[]:["-ss"],H={};if(X)H.signal=X;let{stdout:Q}=await BX("osascript",["-e",_,J],H);return Q.trim()}async function j1(_){return r4(`tell application "Finder" to set app_path to application file id "${_}" as string
43
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as MX}from"node:util";import{execFile as VX}from"node:child_process";var UX=MX(VX),EX={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}};class N1 extends Error{}async function A1(_=UX){let{stdout:Y}=await _("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),X=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(Y);if(!X)throw new N1(`Cannot find Windows browser in stdout: ${JSON.stringify(Y)}`);let{id:J}=X.groups,H=EX[J];if(!H)throw new N1(`Unknown browser ID: ${J}`);return H}var fX=FX(RX),KX=(_)=>_.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(Y)=>Y.toUpperCase());async function w1(){if(S1.platform==="darwin"){let _=await D1();return{name:await j1(_),id:_}}if(S1.platform==="linux"){let{stdout:_}=await fX("xdg-mime",["query","default","x-scheme-handler/http"]),Y=_.trim();return{name:KX(Y.replace(/.desktop$/,"").replace("-"," ")),id:Y}}if(S1.platform==="win32")return A1();throw Error("Only macOS, Linux, and Windows are supported")}var SX=jX(Y6.execFile),O1=_6.dirname(DX(import.meta.url)),o4=_6.join(O1,"xdg-open"),{platform:X2,arch:s4}=z1;async function wX(){let _=await K1(),Y=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,X=e4.from(Y,"utf16le").toString("base64"),{stdout:J}=await SX(_,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",X],{encoding:"utf8"}),H=J.trim(),Q={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return Q[H]?{id:Q[H]}:{}}var a4=async(_,Y)=>{let X;for(let J of _)try{return await Y(J)}catch(H){X=H}throw X},I2=async(_)=>{if(_={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,..._},Array.isArray(_.app))return a4(_.app,($)=>I2({..._,app:$}));let{name:Y,arguments:X=[]}=_.app??{};if(X=[...X],Array.isArray(Y))return a4(Y,($)=>I2({..._,app:{name:$,arguments:X}}));if(Y==="browser"||Y==="browserPrivate"){let $={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},G={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},W=S0?await wX():await w1();if(W.id in $){let L=$[W.id];if(Y==="browserPrivate")X.push(G[L]);return I2({..._,app:{name:x0[L],arguments:X}})}throw Error(`${W.name} is not supported as a default browser`)}let J,H=[],Q={};if(X2==="darwin"){if(J="open",_.wait)H.push("--wait-apps");if(_.background)H.push("--background");if(_.newInstance)H.push("--new");if(Y)H.push("-a",Y)}else if(X2==="win32"||S0&&!Y2()&&!Y){if(J=await K1(),H.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),!S0)Q.windowsVerbatimArguments=!0;let $=["Start"];if(_.wait)$.push("-Wait");if(Y){if($.push(`"\`"${Y}\`""`),_.target)X.push(_.target)}else if(_.target)$.push(`"${_.target}"`);if(X.length>0)X=X.map((G)=>`"\`"${G}\`""`),$.push("-ArgumentList",X.join(","));_.target=e4.from($.join(" "),"utf16le").toString("base64")}else{if(Y)J=Y;else{let $=!O1||O1==="/",G=!1;try{await NX.access(o4,AX.X_OK),G=!0}catch{}J=z1.versions.electron??(X2==="android"||$||!G)?"xdg-open":o4}if(X.length>0)H.push(...X);if(!_.wait)Q.stdio="ignore",Q.detached=!0}if(X2==="darwin"&&X.length>0)H.push("--args",...X);if(_.target)H.push(_.target);let q=Y6.spawn(J,H,Q);if(_.wait)return new Promise(($,G)=>{q.once("error",G),q.once("close",(W)=>{if(!_.allowNonzeroExitCode&&W>0){G(Error(`Exited with code ${W}`));return}$(q)})});return q.unref(),q},zX=(_,Y)=>{if(typeof _!=="string")throw TypeError("Expected a `target`");return I2({...Y,target:_})};function t4(_){if(typeof _==="string"||Array.isArray(_))return _;let{[s4]:Y}=_;if(!Y)throw Error(`${s4} is not supported`);return Y}function P2({[X2]:_},{wsl:Y}){if(Y&&S0)return t4(Y);if(!_)throw Error(`${X2} is not supported`);return t4(_)}var x0={};w0(x0,"chrome",()=>P2({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));w0(x0,"brave",()=>P2({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));w0(x0,"firefox",()=>P2({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));w0(x0,"edge",()=>P2({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));w0(x0,"browser",()=>"browser");w0(x0,"browserPrivate",()=>"browserPrivate");var X6=zX;var{defineProperty:OX,defineProperties:IX,getOwnPropertyDescriptors:PX,getOwnPropertySymbols:J6}=Object,kX=Object.prototype.hasOwnProperty,CX=Object.prototype.propertyIsEnumerable,H6=(_,Y,X)=>(Y in _)?OX(_,Y,{enumerable:!0,configurable:!0,writable:!0,value:X}):_[Y]=X,Q0=(_,Y)=>{for(var X in Y||(Y={}))if(kX.call(Y,X))H6(_,X,Y[X]);if(J6){for(var X of J6(Y))if(CX.call(Y,X))H6(_,X,Y[X])}return _},M0=(_,Y)=>IX(_,PX(Y)),TX=class extends Error{constructor(_,Y,X){super(Y||_.toString(),{cause:X});this.status=_,this.statusText=Y,this.error=X}},vX=async(_,Y)=>{var X,J,H,Q,q,$;let G=Y||{},W={onRequest:[Y==null?void 0:Y.onRequest],onResponse:[Y==null?void 0:Y.onResponse],onSuccess:[Y==null?void 0:Y.onSuccess],onError:[Y==null?void 0:Y.onError],onRetry:[Y==null?void 0:Y.onRetry]};if(!Y||!(Y==null?void 0:Y.plugins))return{url:_,options:G,hooks:W};for(let L of(Y==null?void 0:Y.plugins)||[]){if(L.init){let V=await((X=L.init)==null?void 0:X.call(L,_.toString(),Y));G=V.options||G,_=V.url}W.onRequest.push((J=L.hooks)==null?void 0:J.onRequest),W.onResponse.push((H=L.hooks)==null?void 0:H.onResponse),W.onSuccess.push((Q=L.hooks)==null?void 0:Q.onSuccess),W.onError.push((q=L.hooks)==null?void 0:q.onError),W.onRetry.push(($=L.hooks)==null?void 0:$.onRetry)}return{url:_,options:G,hooks:W}},Q6=class{constructor(_){this.options=_}shouldAttemptRetry(_,Y){if(this.options.shouldRetry)return Promise.resolve(_<this.options.attempts&&this.options.shouldRetry(Y));return Promise.resolve(_<this.options.attempts)}getDelay(){return this.options.delay}},bX=class{constructor(_){this.options=_}shouldAttemptRetry(_,Y){if(this.options.shouldRetry)return Promise.resolve(_<this.options.attempts&&this.options.shouldRetry(Y));return Promise.resolve(_<this.options.attempts)}getDelay(_){return Math.min(this.options.maxDelay,this.options.baseDelay*2**_)}};function ZX(_){if(typeof _==="number")return new Q6({type:"linear",attempts:_,delay:1000});switch(_.type){case"linear":return new Q6(_);case"exponential":return new bX(_);default:throw Error("Invalid retry strategy")}}var xX=async(_)=>{let Y={},X=async(J)=>typeof J==="function"?await J():J;if(_==null?void 0:_.auth){if(_.auth.type==="Bearer"){let J=await X(_.auth.token);if(!J)return Y;Y.authorization=`Bearer ${J}`}else if(_.auth.type==="Basic"){let J=X(_.auth.username),H=X(_.auth.password);if(!J||!H)return Y;Y.authorization=`Basic ${btoa(`${J}:${H}`)}`}else if(_.auth.type==="Custom"){let J=X(_.auth.value);if(!J)return Y;Y.authorization=`${X(_.auth.prefix)} ${J}`}}return Y},yX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function hX(_){let Y=_.headers.get("content-type"),X=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!Y)return"json";let J=Y.split(";").shift()||"";if(yX.test(J))return"json";if(X.has(J)||J.startsWith("text/"))return"text";return"blob"}function gX(_){try{return JSON.parse(_),!0}catch(Y){return!1}}function G6(_){if(_===void 0)return!1;let Y=typeof _;if(Y==="string"||Y==="number"||Y==="boolean"||Y===null)return!0;if(Y!=="object")return!1;if(Array.isArray(_))return!0;if(_.buffer)return!1;return _.constructor&&_.constructor.name==="Object"||typeof _.toJSON==="function"}function q6(_){try{return JSON.parse(_)}catch(Y){return _}}function $6(_){return typeof _==="function"}function mX(_){if(_==null?void 0:_.customFetchImpl)return _.customFetchImpl;if(typeof globalThis<"u"&&$6(globalThis.fetch))return globalThis.fetch;if(typeof window<"u"&&$6(window.fetch))return window.fetch;throw Error("No fetch implementation found")}async function cX(_){let Y=new Headers(_==null?void 0:_.headers),X=await xX(_);for(let[J,H]of Object.entries(X||{}))Y.set(J,H);if(!Y.has("content-type")){let J=uX(_==null?void 0:_.body);if(J)Y.set("content-type",J)}return Y}function uX(_){if(G6(_))return"application/json";return null}function lX(_){if(!(_==null?void 0:_.body))return null;let Y=new Headers(_==null?void 0:_.headers);if(G6(_.body)&&!Y.has("content-type")){for(let[X,J]of Object.entries(_==null?void 0:_.body))if(J instanceof Date)_.body[X]=J.toISOString();return JSON.stringify(_.body)}return _.body}function dX(_,Y){var X;if(Y==null?void 0:Y.method)return Y.method.toUpperCase();if(_.startsWith("@")){let J=(X=_.split("@")[1])==null?void 0:X.split("/")[0];if(!W6.includes(J))return(Y==null?void 0:Y.body)?"POST":"GET";return J.toUpperCase()}return(Y==null?void 0:Y.body)?"POST":"GET"}function pX(_,Y){let X;if(!(_==null?void 0:_.signal)&&(_==null?void 0:_.timeout))X=setTimeout(()=>Y==null?void 0:Y.abort(),_==null?void 0:_.timeout);return{abortTimeout:X,clearTimeout:()=>{if(X)clearTimeout(X)}}}var nX=class _ extends Error{constructor(Y,X){super(X||JSON.stringify(Y,null,2));this.issues=Y,Object.setPrototypeOf(this,_.prototype)}};async function k2(_,Y){let X=await _["~standard"].validate(Y);if(X.issues)throw new nX(X.issues);return X.value}var W6=["get","post","put","patch","delete"];var iX=(_)=>({id:"apply-schema",name:"Apply Schema",version:"1.0.0",async init(Y,X){var J,H,Q,q;let $=((H=(J=_.plugins)==null?void 0:J.find((G)=>{var W;return((W=G.schema)==null?void 0:W.config)?Y.startsWith(G.schema.config.baseURL||"")||Y.startsWith(G.schema.config.prefix||""):!1}))==null?void 0:H.schema)||_.schema;if($){let G=Y;if((Q=$.config)==null?void 0:Q.prefix){if(G.startsWith($.config.prefix)){if(G=G.replace($.config.prefix,""),$.config.baseURL)Y=Y.replace($.config.prefix,$.config.baseURL)}}if((q=$.config)==null?void 0:q.baseURL){if(G.startsWith($.config.baseURL))G=G.replace($.config.baseURL,"")}let W=$.schema[G];if(W){let L=M0(Q0({},X),{method:W.method,output:W.output});if(!(X==null?void 0:X.disableValidation))L=M0(Q0({},L),{body:W.input?await k2(W.input,X==null?void 0:X.body):X==null?void 0:X.body,params:W.params?await k2(W.params,X==null?void 0:X.params):X==null?void 0:X.params,query:W.query?await k2(W.query,X==null?void 0:X.query):X==null?void 0:X.query});return{url:Y,options:L}}}return{url:Y,options:X}}}),L6=(_)=>{async function Y(X,J){let H=M0(Q0(Q0({},_),J),{plugins:[...(_==null?void 0:_.plugins)||[],iX(_||{})]});if(_==null?void 0:_.catchAllError)try{return await I1(X,H)}catch(Q){return{data:null,error:{status:500,statusText:"Fetch Error",message:"Fetch related error. Captured by catchAllError option. See error property for more details.",error:Q}}}return await I1(X,H)}return Y};function rX(_,Y){let{baseURL:X,params:J,query:H}=Y||{query:{},params:{},baseURL:""},Q=_.startsWith("http")?_.split("/").slice(0,3).join("/"):X||"";if(_.startsWith("@")){let V=_.toString().split("@")[1].split("/")[0];if(W6.includes(V))_=_.replace(`@${V}/`,"/")}if(!Q.endsWith("/"))Q+="/";let[q,$]=_.replace(Q,"").split("?"),G=new URLSearchParams($);for(let[V,E]of Object.entries(H||{})){if(E==null)continue;G.set(V,String(E))}if(J)if(Array.isArray(J)){let V=q.split("/").filter((E)=>E.startsWith(":"));for(let[E,N]of V.entries()){let v=J[E];q=q.replace(N,v)}}else for(let[V,E]of Object.entries(J))q=q.replace(`:${V}`,String(E));if(q=q.split("/").map(encodeURIComponent).join("/"),q.startsWith("/"))q=q.slice(1);let W=G.toString();if(W=W.length>0?`?${W}`.replace(/\+/g,"%20"):"",!Q.startsWith("http"))return`${Q}${q}${W}`;return new URL(`${q}${W}`,Q)}var I1=async(_,Y)=>{var X,J,H,Q,q,$,G,W;let{hooks:L,url:V,options:E}=await vX(_,Y),N=mX(E),v=new AbortController,Z=(X=E.signal)!=null?X:v.signal,S=rX(V,E),O=lX(E),c=await cX(E),u=dX(V,E),K=M0(Q0({},E),{url:S,headers:c,body:O,method:u,signal:Z});for(let I of L.onRequest)if(I){let h=await I(K);if(h instanceof Object)K=h}if("pipeTo"in K&&typeof K.pipeTo==="function"||typeof((J=Y==null?void 0:Y.body)==null?void 0:J.pipe)==="function"){if(!("duplex"in K))K.duplex="half"}let{clearTimeout:d}=pX(E,v),M=await N(K.url,K);d();let R={response:M,request:K};for(let I of L.onResponse)if(I){let h=await I(M0(Q0({},R),{response:((H=Y==null?void 0:Y.hookOptions)==null?void 0:H.cloneResponse)?M.clone():M}));if(h instanceof Response)M=h;else if(h instanceof Object)M=h.response}if(M.ok){if(K.method==="HEAD")return{data:"",error:null};let h=hX(M),p={data:"",response:M,request:K};if(h==="json"||h==="text"){let r=await M.text(),P6=await((Q=K.jsonParser)!=null?Q:q6)(r);p.data=P6}else p.data=await M[h]();if(K==null?void 0:K.output){if(K.output&&!K.disableValidation)p.data=await k2(K.output,p.data)}for(let r of L.onSuccess)if(r)await r(M0(Q0({},p),{response:((q=Y==null?void 0:Y.hookOptions)==null?void 0:q.cloneResponse)?M.clone():M}));if(Y==null?void 0:Y.throw)return p.data;return{data:p.data,error:null}}let z=($=Y==null?void 0:Y.jsonParser)!=null?$:q6,k=await M.text(),C=gX(k),j=C?await z(k):null,y={response:M,responseText:k,request:K,error:M0(Q0({},j),{status:M.status,statusText:M.statusText})};for(let I of L.onError)if(I)await I(M0(Q0({},y),{response:((G=Y==null?void 0:Y.hookOptions)==null?void 0:G.cloneResponse)?M.clone():M}));if(Y==null?void 0:Y.retry){let I=ZX(Y.retry),h=(W=Y.retryAttempt)!=null?W:0;if(await I.shouldAttemptRetry(h,M)){for(let r of L.onRetry)if(r)await r(R);let p=I.getDelay(h);return await new Promise((r)=>setTimeout(r,p)),await I1(_,M0(Q0({},Y),{retryAttempt:h+1}))}}if(Y==null?void 0:Y.throw)throw new TX(M.status,M.statusText,C?j:k);return{data:null,error:M0(Q0({},j),{status:M.status,statusText:M.statusText})}};var C2=Object.create(null),E2=(_)=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(_?C2:globalThis),z0=new Proxy(C2,{get(_,Y){return E2()[Y]??C2[Y]},has(_,Y){let X=E2();return Y in X||Y in C2},set(_,Y,X){let J=E2(!0);return J[Y]=X,!0},deleteProperty(_,Y){if(!Y)return!1;let X=E2(!0);return delete X[Y],!0},ownKeys(){let _=E2(!0);return Object.keys(_)}});var SQ=typeof process<"u"&&process.env&&"production"||"";class J2 extends Error{constructor(_,Y){super(_);this.name="BetterAuthError",this.message=_,this.cause=Y,this.stack=""}}function oX(_){try{return(new URL(_).pathname.replace(/\/+$/,"")||"/")!=="/"}catch(Y){throw new J2(`Invalid base URL: ${_}. Please provide a valid base URL.`)}}function F2(_,Y="/api/auth"){if(oX(_))return _;let J=_.replace(/\/+$/,"");if(!Y||Y==="/")return J;return Y=Y.startsWith("/")?Y:`/${Y}`,`${J}${Y}`}function B6(_,Y,X,J){if(_)return F2(_,Y);if(J!==!1){let q=z0.BETTER_AUTH_URL||z0.NEXT_PUBLIC_BETTER_AUTH_URL||z0.PUBLIC_BETTER_AUTH_URL||z0.NUXT_PUBLIC_BETTER_AUTH_URL||z0.NUXT_PUBLIC_AUTH_URL||(z0.BASE_URL!=="/"?z0.BASE_URL:void 0);if(q)return F2(q,Y)}let H=X?.headers.get("x-forwarded-host"),Q=X?.headers.get("x-forwarded-proto");if(H&&Q)return F2(`${Q}://${H}`,Y);if(X){let q=sX(X.url);if(!q)throw new J2("Could not get origin from request. Please provide a valid base URL.");return F2(q,Y)}if(typeof window<"u"&&window.location)return F2(window.location.origin,Y);return}function sX(_){try{return new URL(_).origin}catch(Y){return null}}var q0=[],O0=0,T2=4,aX=0,R2=(_)=>{let Y=[],X={get(){if(!X.lc)X.listen(()=>{})();return X.value},lc:0,listen(J){return X.lc=Y.push(J),()=>{for(let Q=O0+T2;Q<q0.length;)if(q0[Q]===J)q0.splice(Q,T2);else Q+=T2;let H=Y.indexOf(J);if(~H){if(Y.splice(H,1),!--X.lc)X.off()}}},notify(J,H){aX++;let Q=!q0.length;for(let q of Y)q0.push(q,X.value,J,H);if(Q){for(O0=0;O0<q0.length;O0+=T2)q0[O0](q0[O0+1],q0[O0+2],q0[O0+3]);q0.length=0}},off(){},set(J){let H=X.value;if(H!==J)X.value=J,X.notify(H)},subscribe(J){let H=X.listen(J);return J(X.value),H},value:_};return X};var tX=5,v2=6,b2=10,eX=(_,Y,X,J)=>{if(_.events=_.events||{},!_.events[X+b2])_.events[X+b2]=J((H)=>{_.events[X].reduceRight((Q,q)=>(q(Q),Q),{shared:{},...H})});return _.events[X]=_.events[X]||[],_.events[X].push(Y),()=>{let H=_.events[X],Q=H.indexOf(Y);if(H.splice(Q,1),!H.length)delete _.events[X],_.events[X+b2](),delete _.events[X+b2]}};var M6=1000,P1=(_,Y)=>{return eX(_,(J)=>{let H=Y(J);if(H)_.events[v2].push(H)},tX,(J)=>{let H=_.listen;_.listen=(...q)=>{if(!_.lc&&!_.active)_.active=!0,J();return H(...q)};let Q=_.off;return _.events[v2]=[],_.off=()=>{Q(),setTimeout(()=>{if(_.active&&!_.lc){_.active=!1;for(let q of _.events[v2])q();_.events[v2]=[]}},M6)},()=>{_.listen=H,_.off=Q}})};var _5=typeof window>"u",Z2=(_,Y,X,J)=>{let H=R2({data:null,error:null,isPending:!0,isRefetching:!1,refetch:($)=>{return Q($)}}),Q=($)=>{let G=typeof J==="function"?J({data:H.get().data,error:H.get().error,isPending:H.get().isPending}):J;X(Y,{...G,query:{...G?.query,...$?.query},async onSuccess(W){H.set({data:W.data,error:null,isPending:!1,isRefetching:!1,refetch:H.value.refetch}),await G?.onSuccess?.(W)},async onError(W){let{request:L}=W,V=typeof L.retry==="number"?L.retry:L.retry?.attempts,E=L.retryAttempt||0;if(V&&E<V)return;H.set({error:W.error,data:null,isPending:!1,isRefetching:!1,refetch:H.value.refetch}),await G?.onError?.(W)},async onRequest(W){let L=H.get();H.set({isPending:L.data===null,data:L.data,error:null,isRefetching:!0,refetch:H.value.refetch}),await G?.onRequest?.(W)}}).catch((W)=>{H.set({error:W,data:null,isPending:!1,isRefetching:!1,refetch:H.value.refetch})})};_=Array.isArray(_)?_:[_];let q=!1;for(let $ of _)$.subscribe(()=>{if(_5)return;if(q)Q();else P1(H,()=>{let G=setTimeout(()=>{if(!q)Q(),q=!0},0);return()=>{H.off(),$.off(),clearTimeout(G)}})});return H};var Y5={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},X5=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,V6={true:!0,false:!1,null:null,undefined:void 0,nan:Number.NaN,infinity:Number.POSITIVE_INFINITY,"-infinity":Number.NEGATIVE_INFINITY},J5=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function H5(_){return _ instanceof Date&&!isNaN(_.getTime())}function Q5(_){let Y=J5.exec(_);if(!Y)return null;let[,X,J,H,Q,q,$,G,W,L,V]=Y,E=new Date(Date.UTC(parseInt(X,10),parseInt(J,10)-1,parseInt(H,10),parseInt(Q,10),parseInt(q,10),parseInt($,10),G?parseInt(G.padEnd(3,"0"),10):0));if(W){let N=(parseInt(L,10)*60+parseInt(V,10))*(W==="+"?-1:1);E.setUTCMinutes(E.getUTCMinutes()+N)}return H5(E)?E:null}function q5(_,Y={}){let{strict:X=!1,warnings:J=!1,reviver:H,parseDates:Q=!0}=Y;if(typeof _!=="string")return _;let q=_.trim();if(q.length>0&&q[0]==='"'&&q.endsWith('"')&&!q.slice(1,-1).includes('"'))return q.slice(1,-1);let $=q.toLowerCase();if($.length<=9&&$ in V6)return V6[$];if(!X5.test(q)){if(X)throw SyntaxError("[better-json] Invalid JSON");return _}if(Object.entries(Y5).some(([W,L])=>{let V=L.test(q);if(V&&J)console.warn(`[better-json] Detected potential prototype pollution attempt using ${W} pattern`);return V})&&X)throw Error("[better-json] Potential prototype pollution attempt detected");try{return JSON.parse(q,(L,V)=>{if(L==="__proto__"||L==="constructor"&&V&&typeof V==="object"&&"prototype"in V){if(J)console.warn(`[better-json] Dropping "${L}" key to prevent prototype pollution`);return}if(Q&&typeof V==="string"){let E=Q5(V);if(E)return E}return H?H(L,V):V})}catch(W){if(X)throw W;return _}}function U6(_,Y={strict:!0}){return q5(_,Y)}var $5={id:"redirect",name:"Redirect",hooks:{onSuccess(_){if(_.data?.url&&_.data?.redirect){if(typeof window<"u"&&window.location){if(window.location)try{window.location.href=_.data.url}catch{}}}}}};function G5(_){let Y=R2(!1);return{session:Z2(Y,"/get-session",_,{method:"GET"}),$sessionSignal:Y}}var E6=(_,Y)=>{let X="credentials"in Request.prototype,J=B6(_?.baseURL,_?.basePath,void 0,Y)??"/api/auth",H=_?.plugins?.flatMap((K)=>K.fetchPlugins).filter((K)=>K!==void 0)||[],Q={id:"lifecycle-hooks",name:"lifecycle-hooks",hooks:{onSuccess:_?.fetchOptions?.onSuccess,onError:_?.fetchOptions?.onError,onRequest:_?.fetchOptions?.onRequest,onResponse:_?.fetchOptions?.onResponse}},{onSuccess:q,onError:$,onRequest:G,onResponse:W,...L}=_?.fetchOptions||{},V=L6({baseURL:J,...X?{credentials:"include"}:{},method:"GET",jsonParser(K){if(!K)return null;return U6(K,{strict:!1})},customFetchImpl:fetch,...L,plugins:[Q,...L.plugins||[],..._?.disableDefaultFetchPlugins?[]:[$5],...H]}),{$sessionSignal:E,session:N}=G5(V),v=_?.plugins||[],Z={},S={$sessionSignal:E,session:N},O={"/sign-out":"POST","/revoke-sessions":"POST","/revoke-other-sessions":"POST","/delete-user":"POST"},c=[{signal:"$sessionSignal",matcher(K){return K==="/sign-out"||K==="/update-user"||K.startsWith("/sign-in")||K.startsWith("/sign-up")||K==="/delete-user"||K==="/verify-email"}}];for(let K of v){if(K.getAtoms)Object.assign(S,K.getAtoms?.(V));if(K.pathMethods)Object.assign(O,K.pathMethods);if(K.atomListeners)c.push(...K.atomListeners)}let u={notify:(K)=>{S[K].set(!S[K].get())},listen:(K,d)=>{S[K].subscribe(d)},atoms:S};for(let K of v)if(K.getActions)Object.assign(Z,K.getActions?.(V,u,_));return{get baseURL(){return J},pluginsActions:Z,pluginsAtoms:S,pluginPathMethods:O,atomListeners:c,$fetch:V,$store:u}};function W5(_){return typeof _==="object"&&_!==null&&"get"in _&&typeof _.get==="function"&&"lc"in _&&typeof _.lc==="number"}function L5(_,Y,X){let J=Y[_],{fetchOptions:H,query:Q,...q}=X||{};if(J)return J;if(H?.method)return H.method;if(q&&Object.keys(q).length>0)return"POST";return"GET"}function F6(_,Y,X,J,H){function Q(q=[]){return new Proxy(function(){},{get($,G){if(typeof G!=="string")return;if(G==="then"||G==="catch"||G==="finally")return;let W=[...q,G],L=_;for(let V of W)if(L&&typeof L==="object"&&V in L)L=L[V];else{L=void 0;break}if(typeof L==="function")return L;if(W5(L))return L;return Q(W)},apply:async($,G,W)=>{let L="/"+q.map((c)=>c.replace(/[A-Z]/g,(u)=>`-${u.toLowerCase()}`)).join("/"),V=W[0]||{},E=W[1]||{},{query:N,fetchOptions:v,...Z}=V,S={...E,...v},O=L5(L,X,V);return await Y(L,{...S,body:O==="GET"?void 0:{...Z,...S?.body||{}},query:N||S?.query,method:O,async onSuccess(c){await S?.onSuccess?.(c);let u=H?.find((M)=>M.matcher(L));if(!u)return;let K=J[u.signal];if(!K)return;let d=K.get();setTimeout(()=>{K.set(!d)},10)}})}})}return Q()}function R6(_){return _.charAt(0).toUpperCase()+_.slice(1)}function k1(_){let{pluginPathMethods:Y,pluginsActions:X,pluginsAtoms:J,$fetch:H,atomListeners:Q,$store:q}=E6(_),$={};for(let[L,V]of Object.entries(J))$[`use${R6(L)}`]=V;let G={...X,...$,$fetch:H,$store:q};return F6(G,H,Y,J,Q)}function B5(_){return{authorize(Y,X="AND"){let J=!1;for(let[H,Q]of Object.entries(Y)){let q=_[H];if(!q)return{success:!1,error:`You are not allowed to access resource: ${H}`};if(Array.isArray(Q))J=Q.every(($)=>q.includes($));else if(typeof Q==="object"){let $=Q;if($.connector==="OR")J=$.actions.some((G)=>q.includes(G));else J=$.actions.every((G)=>q.includes(G))}else throw new J2("Invalid access control request");if(J&&X==="OR")return{success:J};if(!J&&X==="AND")return{success:!1,error:`unauthorized to access resource "${H}"`}}if(J)return{success:J};return{success:!1,error:"Not authorized"}},statements:_}}function x2(_){return{newRole(Y){return B5(Y)},statements:_}}var M5={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]},C1=x2(M5),V5=C1.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"],team:["create","update","delete"],ac:["create","read","update","delete"]}),U5=C1.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"],team:["create","update","delete"],ac:["create","read","update","delete"]}),E5=C1.newRole({organization:[],member:[],invitation:[],team:[],ac:["read"]});class D6{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let Y=Error("Cancelling existing WebAuthn API call for new one");Y.name="AbortError",this.controller.abort(Y)}let _=new AbortController;return this.controller=_,_.signal}cancelCeremony(){if(this.controller){let _=Error("Manually cancelling existing WebAuthn API call");_.name="AbortError",this.controller.abort(_),this.controller=void 0}}}var j6=new D6;var D5={user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]},N6=x2(D5),j5=N6.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","get","update"],session:["list","revoke","delete"]}),N5=N6.newRole({user:[],session:[]});var v1=()=>{return{id:"device-authorization",$InferServerPlugin:{},pathMethods:{"/device/code":"POST","/device/token":"POST","/device":"GET","/device/approve":"POST","/device/deny":"POST"}}};function A5(){return"https://agentlogs.ai"}var H2=k1({baseURL:A5(),plugins:[v1()]});async function A6(){console.log("\uD83D\uDD10 AgentLogs Device Authorization"),console.log("⏳ Requesting device authorization...");try{let{data:_,error:Y}=await H2.device.code({client_id:"agentlogs-cli",scope:"openid profile email"});if(Y||!_)console.error("❌ Error:",Y?.error_description||"Failed to request device code"),process.exit(1);let{device_code:X,user_code:J,verification_uri:H,verification_uri_complete:Q,interval:q=5}=_;console.log(`
44
+ \uD83D\uDCF1 Device Authorization in Progress`),console.log(`Please visit: ${H}`),console.log(`Enter code: ${J}
45
+ `);let $=Q||H;if($)console.log("\uD83C\uDF10 Opening browser..."),await X6($);console.log(`⏳ Waiting for authorization... (polling every ${q}s)`),await S5(X,q)}catch(_){console.error("❌ Error:",_ instanceof Error?_.message:"Unknown error"),process.exit(1)}}async function S5(_,Y){let X=Y;return new Promise((J)=>{let H=async()=>{try{let{data:Q,error:q}=await H2.device.token({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:_,client_id:"agentlogs-cli"});if(Q?.access_token){console.log(`
46
+ ✅ Authorization Successful!`),console.log("\uD83D\uDD11 Access token received!");let{data:$}=await H2.getSession({fetchOptions:{headers:{Authorization:`Bearer ${Q.access_token}`}}});if($?.user){G4($.user.email,Q.access_token);let G=t();$4({...G,user:{id:$.user.id,email:$.user.email,name:$.user.name},lastLoginTime:new Date().toISOString()}),console.log(`\uD83D\uDC4B Hello, ${$.user.name}!`),console.log(`\uD83D\uDCE7 Logged in as: ${$.user.email}`)}else console.log("⚠️ Warning: Could not retrieve user session");J(),process.exit(0)}else if(q)switch(q.error){case"authorization_pending":break;case"slow_down":X+=5,console.log(`⚠️ Slowing down polling to ${X}s`);break;case"access_denied":console.error("❌ Access was denied by the user"),process.exit(1);break;case"expired_token":console.error("❌ The device code has expired. Please try again."),process.exit(1);break;default:console.error("❌ Error:",q.error_description||q.error),process.exit(1)}}catch(Q){console.error("❌ Error:",Q instanceof Error?Q.message:"Unknown error"),process.exit(1)}setTimeout(H,X*1000)};setTimeout(H,X*1000)})}import{unlinkSync as w5}from"fs";import{homedir as z5}from"os";import{join as O5}from"path";function S6(){if(!t().user){console.log("ℹ️ Not currently logged in");return}try{W4();let Y=O5(z5(),".config","agentlogs","config.json");w5(Y),console.log("✅ Logged out successfully")}catch(Y){console.error("⚠️ Warning: Could not completely clear credentials:",Y instanceof Error?Y.message:"Unknown error"),console.log("You may need to manually delete ~/.config/agentlogs/config.json")}}function I5(){return"https://agentlogs.ai"}async function w6(){let _=e();if(!_)console.log("❌ Not logged in"),console.log("Run `bun run src/index.ts login` to authenticate"),process.exit(1);try{let{data:Y,error:X}=await H2.getSession({fetchOptions:{headers:{Authorization:`Bearer ${_}`}}});if(X||!Y?.user)console.log("❌ Not logged in (token invalid or expired)"),console.log("Run `bun run src/index.ts login` to authenticate"),process.exit(1);let J=t(),H=I5();if(console.log("✅ Logged in"),console.log(`\uD83D\uDC64 Name: ${Y.user.name}`),console.log(`\uD83D\uDCE7 Email: ${Y.user.email}`),console.log(`\uD83C\uDF10 Server: ${H}`),console.log(`\uD83D\uDD27 Environment: ${N2}`),J.lastLoginTime){let Q=new Date(J.lastLoginTime);console.log(`\uD83D\uDD50 Last login: ${Q.toLocaleString()}`)}}catch(Y){console.error("❌ Error verifying session:",Y instanceof Error?Y.message:"Unknown error"),console.log("Run `bun run src/index.ts login` to authenticate"),process.exit(1)}}import{createHash as k5}from"crypto";import{promises as y2}from"fs";import{homedir as C5}from"os";import{basename as T5,extname as v5,join as h2,relative as b5,resolve as Z5}from"path";async function z6(_={}){let Y=_.serverUrl??process.env.VI_SERVER_URL??"http://localhost:3000",X=_.authToken??null,J=_.timeoutMs??1e4;try{let H=await fetch(`${Y}/api/transcripts`,{method:"GET",headers:{...X&&{Authorization:`Bearer ${X}`}},signal:AbortSignal.timeout(J)});if(!H.ok)return console.error(`Failed to fetch transcript metadata: ${H.status} ${H.statusText}`),[];let Q=await H.json();if(P5(Q))return Q.transcripts;return console.error("Transcript metadata response had unexpected shape:",Q),[]}catch(H){if(H instanceof Error)console.error("Failed to fetch transcript metadata:",H.message);return[]}}function P5(_){if(typeof _!=="object"||_===null||!("transcripts"in _))return!1;let{transcripts:Y}=_;if(!Array.isArray(Y))return!1;return Y.every((X)=>{if(typeof X!=="object"||X===null)return!1;let J=X;return typeof J.transcriptId==="string"&&J.transcriptId.length>0&&typeof J.sha256==="string"&&J.sha256.length>0&&typeof J.repoId==="string"&&J.repoId.length>0})}var x5=h2(C5(),".claude");async function O6(_={}){let{repoFilter:Y,claudeDir:X}=_,J=e();if(!J)console.error("You must be logged in to sync transcripts. Run `bun run src/index.ts login` first."),process.exit(1);let H="https://agentlogs.ai",Q=X?Z5(X):process.env.CLAUDE_HOME??x5,q=h2(Q,"projects"),$=await y5(q);if($.length===0){console.log(`No local Claude Code transcripts were found under ${q}. Nothing to sync.`);return}let G=Y?$.filter((S)=>S.repoId===Y):$;if(Y&&G.length===0){let S=$.filter((O)=>O.repoId===null).length;if(console.log(`No local Claude Code transcripts matched repo ${Y}.`),S>0)console.log(`${S} transcript(s) were skipped because their repo could not be determined.`);return}let W=await z6({serverUrl:H,authToken:J}),L=Y?W.filter((S)=>S.repoId===Y):W,V=new Map;for(let S of L)V.set(S.transcriptId,S.sha256);let E=G.filter((S)=>{let O=V.get(S.transcriptId);return!O||O!==S.sha256});if(E.length===0){console.log("All local Claude Code transcripts are up to date on the server.");return}console.log(`Preparing to upload ${E.length} transcript(s) out of ${G.length} matching local transcript(s).`);let N=0,v=0,Z=[];for(let[S,O]of E.entries()){let c=`${S+1}/${E.length}`,u=O.repoId?` • ${O.repoId}`:"",K=`${O.transcriptId} – ${O.displayPath}${u}`;try{let d=await A0({transcriptPath:O.path,sessionId:O.transcriptId,cwdOverride:O.cwd??void 0},{serverUrl:H,authToken:J});if(d.success)N+=1,console.log(`[${c}] ✓ ${K} • ${d.eventCount} events${d.transcriptId?` → ${d.transcriptId}`:""}`);else{v+=1;let M="Upload returned unsuccessful response.";console.error(`[${c}] ✗ ${K} • ${M}`),Z.push({transcriptId:O.transcriptId,displayPath:O.displayPath,reason:M})}}catch(d){v+=1;let M=d instanceof Error?d.message:String(d);console.error(`[${c}] ✗ ${K} • ${M}`),Z.push({transcriptId:O.transcriptId,displayPath:O.displayPath,reason:M})}}if(console.log(`Sync complete. Successful uploads: ${N}. Failed uploads: ${v}.`),Z.length>0){console.error("Failed transcript details:");for(let S of Z.slice(0,10))console.error(` - ${S.transcriptId} (${S.displayPath}): ${S.reason}`);if(Z.length>10)console.error(` …and ${Z.length-10} more failures.`)}if(v>0)process.exit(1)}async function y5(_){if(!await I6(_))return[];let Y=await y2.readdir(_,{withFileTypes:!0}),X=[];for(let J of Y){if(!J.isDirectory())continue;let H=h2(_,J.name),Q=await y2.readdir(H,{withFileTypes:!0});for(let q of Q){if(!q.isFile()||v5(q.name)!==".jsonl")continue;let $=h2(H,q.name),G=T5(q.name,".jsonl");try{let W=await y2.readFile($,"utf8"),L=k5("sha256").update(W).digest("hex"),V=h5(W),E=await g5(V);X.push({transcriptId:G,path:$,sha256:L,cwd:V,repoId:E,displayPath:b5(_,$)||q.name})}catch(W){console.warn(`Skipped transcript at ${$}: ${W.message}`)}}}return X}async function I6(_){try{return(await y2.stat(_)).isDirectory()}catch{return!1}}function h5(_){let Y=_.split(/\r?\n/);for(let X of Y){let J=X.trim();if(!J)continue;try{let Q=JSON.parse(J)?.cwd;if(typeof Q==="string"&&Q.length>0)return Q}catch{continue}}return null}async function g5(_){if(!_)return null;if(!await I6(_))return null;try{return m4(_).repoId}catch{return null}}async function b1(_,Y="claude-code"){if(!_)console.error("The upload command expects a <transcript> argument."),process.exit(1);let X=c4(_);if(!X)console.error(`Transcript file not found for path: ${_}`),process.exit(1);let J="https://agentlogs.ai",H=e();if(!H)console.error("You must be logged in to upload transcripts. Run `bun run src/index.ts login` first."),process.exit(1);let Q={};if(J)Q.serverUrl=J;Q.authToken=H;try{console.log(`Uploading ${Y==="codex"?"Codex":"Claude Code"} transcript events from ${X} to AgentLogs...`);let $=await A0({transcriptPath:X,source:Y},Q);if($.success){console.log(`✓ Upload successful (${$.eventCount} events${$.transcriptId?`, transcript ID: ${$.transcriptId}`:""})`);return}console.error("✗ Failed to upload transcript to AgentLogs server.")}catch(q){console.error(q instanceof Error?q.message:"Unexpected error occurred while uploading transcript.")}process.exit(1)}var I0=new _4;I0.name("agentlogs").description("CLI tools for working with AgentLogs accounts and transcripts from Claude Code and Codex");I0.command("login").description("Authenticate with AgentLogs using device authorization").action(async()=>{await A6()});I0.command("status").description("Check your current login status").action(async()=>{await w6()});I0.command("logout").description("Log out and clear stored credentials").action(async()=>{await S6()});var Z1=I0.command("claudecode").description("Claude Code transcript utilities for AgentLogs");Z1.command("upload").argument("<transcript>","Path or alias for a transcript JSONL file").description("Upload a transcript JSONL file to AgentLogs").action(async(_)=>{await b1(_,"claude-code")});Z1.command("hook").description("Process Claude Code hook input from stdin").action(async()=>{await u4()});var m5=I0.command("codex").description("Codex transcript utilities for AgentLogs");m5.command("upload").argument("<transcript>","Path or alias for a Codex transcript JSONL file").description("Upload a Codex transcript JSONL file to AgentLogs").action(async(_)=>{await b1(_,"codex")});Z1.command("sync").argument("[claudeDir]","Optional Claude data directory (defaults to ~/.claude)").option("-r, --repo <repoId>","Only sync transcripts for the provided repo identifier").description("Upload all local Claude Code transcripts that are missing or outdated on the server").action(async(_,Y)=>{await O6({claudeDir:_,repoFilter:Y.repo})});I0.showHelpAfterError("(add --help for additional information)");I0.parseAsync().catch((_)=>{console.error("CLI encountered an unexpected error."),console.error(_),process.exit(1)});
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "agentlogs",
3
+ "version": "0.0.1",
4
+ "bin": {
5
+ "agentlogs": "src/index.ts"
6
+ },
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "type": "module",
11
+ "main": "src/index.ts",
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "bin": {
15
+ "agentlogs": "dist/index.js"
16
+ },
17
+ "main": "dist/index.js"
18
+ },
19
+ "scripts": {
20
+ "start": "bun run src/index.ts",
21
+ "build": "bun build ./src/index.ts --outdir ./dist --target node --external @napi-rs/keyring --production --define '__NODE_ENV__=\"production\"' --define 'process.env.SERVER_URL=\"https://agentlogs.ai\"'",
22
+ "prepublishOnly": "bun run build",
23
+ "test:e2e": "bun test ./test/e2e/*.e2e.ts",
24
+ "check": "tsgo --project tsconfig.json"
25
+ },
26
+ "dependencies": {
27
+ "@napi-rs/keyring": "^1.2.0",
28
+ "commander": "^14.0.0"
29
+ },
30
+ "devDependencies": {
31
+ "@agentlogs/shared": "0.1.0",
32
+ "better-auth": "^1.3.27",
33
+ "open": "^10.2.0"
34
+ }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { hookCommand } from "./commands/hook";
4
+ import { loginCommand } from "./commands/login";
5
+ import { logoutCommand } from "./commands/logout";
6
+ import { statusCommand } from "./commands/status";
7
+ import { syncCommand } from "./commands/sync";
8
+ import { uploadCommand } from "./commands/upload";
9
+
10
+ const program = new Command();
11
+
12
+ program
13
+ .name("agentlogs")
14
+ .description("CLI tools for working with AgentLogs accounts and transcripts from Claude Code and Codex");
15
+
16
+ program
17
+ .command("login")
18
+ .description("Authenticate with AgentLogs using device authorization")
19
+ .action(async () => {
20
+ await loginCommand();
21
+ });
22
+
23
+ program
24
+ .command("status")
25
+ .description("Check your current login status")
26
+ .action(async () => {
27
+ await statusCommand();
28
+ });
29
+
30
+ program
31
+ .command("logout")
32
+ .description("Log out and clear stored credentials")
33
+ .action(async () => {
34
+ await logoutCommand();
35
+ });
36
+
37
+ const claudecode = program.command("claudecode").description("Claude Code transcript utilities for AgentLogs");
38
+
39
+ claudecode
40
+ .command("upload")
41
+ .argument("<transcript>", "Path or alias for a transcript JSONL file")
42
+ .description("Upload a transcript JSONL file to AgentLogs")
43
+ .action(async (transcript: string) => {
44
+ await uploadCommand(transcript, "claude-code");
45
+ });
46
+
47
+ claudecode
48
+ .command("hook")
49
+ .description("Process Claude Code hook input from stdin")
50
+ .action(async () => {
51
+ await hookCommand();
52
+ });
53
+
54
+ const codex = program.command("codex").description("Codex transcript utilities for AgentLogs");
55
+
56
+ codex
57
+ .command("upload")
58
+ .argument("<transcript>", "Path or alias for a Codex transcript JSONL file")
59
+ .description("Upload a Codex transcript JSONL file to AgentLogs")
60
+ .action(async (transcript: string) => {
61
+ await uploadCommand(transcript, "codex");
62
+ });
63
+
64
+ claudecode
65
+ .command("sync")
66
+ .argument("[claudeDir]", "Optional Claude data directory (defaults to ~/.claude)")
67
+ .option("-r, --repo <repoId>", "Only sync transcripts for the provided repo identifier")
68
+ .description("Upload all local Claude Code transcripts that are missing or outdated on the server")
69
+ .action(async (claudeDir: string | undefined, options: { repo?: string }) => {
70
+ await syncCommand({
71
+ claudeDir,
72
+ repoFilter: options.repo,
73
+ });
74
+ });
75
+
76
+ program.showHelpAfterError("(add --help for additional information)");
77
+
78
+ program.parseAsync().catch((error) => {
79
+ console.error("CLI encountered an unexpected error.");
80
+ console.error(error);
81
+ process.exit(1);
82
+ });