@agiflowai/agent-cli 0.0.7 → 0.0.9

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.
@@ -1,129 +0,0 @@
1
- "use strict";var zr=Object.create;var Lt=Object.defineProperty;var Mr=Object.getOwnPropertyDescriptor;var Gr=Object.getOwnPropertyNames;var Lr=Object.getPrototypeOf,jr=Object.prototype.hasOwnProperty;var Wr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Gr(e))!jr.call(t,i)&&i!==n&&Lt(t,i,{get:()=>e[i],enumerable:!(r=Mr(e,i))||r.enumerable});return t};var dt=(t,e,n)=>(n=t!=null?zr(Lr(t)):{},Wr(e||!t||!t.__esModule?Lt(n,"default",{value:t,enumerable:!0}):n,t));const D=require("./AgentHttpService-MFVF-74l.js"),Zr=require("node:events"),Vr=require("node:child_process"),$n=require("node:path"),Hr=require("node:fs"),Y=require("node:process"),T=require("fs"),C=require("path"),ae=require("os"),On=require("crypto"),pe=require("fs/promises"),_e=require("ws"),Kr=require("node-pty"),xn=require("ulidx"),ie=require("child_process"),qr=require("events"),et=require("@inquirer/prompts"),Yr=require("node:crypto"),Jr=require("node:os"),Qr=require("util");function Be(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Xr=Be($n),ei=Be(T),ti=Be(Kr),ni=Be(Yr),fe=Be(Jr);var oe={},We={},Ze={},jt;function ot(){if(jt)return Ze;jt=1;class t extends Error{constructor(r,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=r,this.nestedError=void 0}}class e extends t{constructor(r){super(1,"commander.invalidArgument",r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}return Ze.CommanderError=t,Ze.InvalidArgumentError=e,Ze}var Wt;function Ot(){if(Wt)return We;Wt=1;const{InvalidArgumentError:t}=ot();class e{constructor(i,s){switch(this.description=s||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(i,s){return s===this.defaultValue||!Array.isArray(s)?[i]:s.concat(i)}default(i,s){return this.defaultValue=i,this.defaultValueDescription=s,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(s,o)=>{if(!this.argChoices.includes(s))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(s,o):s},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function n(r){const i=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+i+">":"["+i+"]"}return We.Argument=e,We.humanReadableArgName=n,We}var gt={},ft={},Zt;function Pn(){if(Zt)return ft;Zt=1;const{humanReadableArgName:t}=Ot();class e{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(r){const i=r.commands.filter(o=>!o._hidden),s=r._getHelpCommand();return s&&!s._hidden&&i.push(s),this.sortSubcommands&&i.sort((o,a)=>o.name().localeCompare(a.name())),i}compareOptions(r,i){const s=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return s(r).localeCompare(s(i))}visibleOptions(r){const i=r.options.filter(o=>!o.hidden),s=r._getHelpOption();if(s&&!s.hidden){const o=s.short&&r._findOption(s.short),a=s.long&&r._findOption(s.long);!o&&!a?i.push(s):s.long&&!a?i.push(r.createOption(s.long,s.description)):s.short&&!o&&i.push(r.createOption(s.short,s.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(r){if(!this.showGlobalOptions)return[];const i=[];for(let s=r.parent;s;s=s.parent){const o=s.options.filter(a=>!a.hidden);i.push(...o)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(r){return r._argsDescription&&r.registeredArguments.forEach(i=>{i.description=i.description||r._argsDescription[i.name()]||""}),r.registeredArguments.find(i=>i.description)?r.registeredArguments:[]}subcommandTerm(r){const i=r.registeredArguments.map(s=>t(s)).join(" ");return r._name+(r._aliases[0]?"|"+r._aliases[0]:"")+(r.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(r){return r.flags}argumentTerm(r){return r.name()}longestSubcommandTermLength(r,i){return i.visibleCommands(r).reduce((s,o)=>Math.max(s,i.subcommandTerm(o).length),0)}longestOptionTermLength(r,i){return i.visibleOptions(r).reduce((s,o)=>Math.max(s,i.optionTerm(o).length),0)}longestGlobalOptionTermLength(r,i){return i.visibleGlobalOptions(r).reduce((s,o)=>Math.max(s,i.optionTerm(o).length),0)}longestArgumentTermLength(r,i){return i.visibleArguments(r).reduce((s,o)=>Math.max(s,i.argumentTerm(o).length),0)}commandUsage(r){let i=r._name;r._aliases[0]&&(i=i+"|"+r._aliases[0]);let s="";for(let o=r.parent;o;o=o.parent)s=o.name()+" "+s;return s+i+" "+r.usage()}commandDescription(r){return r.description()}subcommandDescription(r){return r.summary()||r.description()}optionDescription(r){const i=[];return r.argChoices&&i.push(`choices: ${r.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),r.defaultValue!==void 0&&(r.required||r.optional||r.isBoolean()&&typeof r.defaultValue=="boolean")&&i.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),r.presetArg!==void 0&&r.optional&&i.push(`preset: ${JSON.stringify(r.presetArg)}`),r.envVar!==void 0&&i.push(`env: ${r.envVar}`),i.length>0?`${r.description} (${i.join(", ")})`:r.description}argumentDescription(r){const i=[];if(r.argChoices&&i.push(`choices: ${r.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),r.defaultValue!==void 0&&i.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),i.length>0){const s=`(${i.join(", ")})`;return r.description?`${r.description} ${s}`:s}return r.description}formatHelp(r,i){const s=i.padWidth(r,i),o=i.helpWidth||80,a=2,l=2;function g(c,h){if(h){const d=`${c.padEnd(s+l)}${h}`;return i.wrap(d,o-a,s+l)}return c}function p(c){return c.join(`
2
- `).replace(/^/gm," ".repeat(a))}let E=[`Usage: ${i.commandUsage(r)}`,""];const m=i.commandDescription(r);m.length>0&&(E=E.concat([i.wrap(m,o,0),""]));const F=i.visibleArguments(r).map(c=>g(i.argumentTerm(c),i.argumentDescription(c)));F.length>0&&(E=E.concat(["Arguments:",p(F),""]));const k=i.visibleOptions(r).map(c=>g(i.optionTerm(c),i.optionDescription(c)));if(k.length>0&&(E=E.concat(["Options:",p(k),""])),this.showGlobalOptions){const c=i.visibleGlobalOptions(r).map(h=>g(i.optionTerm(h),i.optionDescription(h)));c.length>0&&(E=E.concat(["Global Options:",p(c),""]))}const u=i.visibleCommands(r).map(c=>g(i.subcommandTerm(c),i.subcommandDescription(c)));return u.length>0&&(E=E.concat(["Commands:",p(u),""])),E.join(`
3
- `)}padWidth(r,i){return Math.max(i.longestOptionTermLength(r,i),i.longestGlobalOptionTermLength(r,i),i.longestSubcommandTermLength(r,i),i.longestArgumentTermLength(r,i))}wrap(r,i,s,o=40){const a=" \\f\\t\\v   -    \uFEFF",l=new RegExp(`[\\n][${a}]+`);if(r.match(l))return r;const g=i-s;if(g<o)return r;const p=r.slice(0,s),E=r.slice(s).replace(`\r
4
- `,`
5
- `),m=" ".repeat(s),k="\\s​",u=new RegExp(`
6
- |.{1,${g-1}}([${k}]|$)|[^${k}]+?([${k}]|$)`,"g"),c=E.match(u)||[];return p+c.map((h,d)=>h===`
7
- `?"":(d>0?m:"")+h.trimEnd()).join(`
8
- `)}}return ft.Help=e,ft}var Ve={},Vt;function Rn(){if(Vt)return Ve;Vt=1;const{InvalidArgumentError:t}=ot();class e{constructor(o,a){this.flags=o,this.description=a||"",this.required=o.includes("<"),this.optional=o.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(o),this.mandatory=!1;const l=i(o);this.short=l.shortFlag,this.long=l.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(o,a){return this.defaultValue=o,this.defaultValueDescription=a,this}preset(o){return this.presetArg=o,this}conflicts(o){return this.conflictsWith=this.conflictsWith.concat(o),this}implies(o){let a=o;return typeof o=="string"&&(a={[o]:!0}),this.implied=Object.assign(this.implied||{},a),this}env(o){return this.envVar=o,this}argParser(o){return this.parseArg=o,this}makeOptionMandatory(o=!0){return this.mandatory=!!o,this}hideHelp(o=!0){return this.hidden=!!o,this}_concatValue(o,a){return a===this.defaultValue||!Array.isArray(a)?[o]:a.concat(o)}choices(o){return this.argChoices=o.slice(),this.parseArg=(a,l)=>{if(!this.argChoices.includes(a))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(a,l):a},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return r(this.name().replace(/^no-/,""))}is(o){return this.short===o||this.long===o}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class n{constructor(o){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,o.forEach(a=>{a.negate?this.negativeOptions.set(a.attributeName(),a):this.positiveOptions.set(a.attributeName(),a)}),this.negativeOptions.forEach((a,l)=>{this.positiveOptions.has(l)&&this.dualOptions.add(l)})}valueFromOption(o,a){const l=a.attributeName();if(!this.dualOptions.has(l))return!0;const g=this.negativeOptions.get(l).presetArg,p=g!==void 0?g:!1;return a.negate===(p===o)}}function r(s){return s.split("-").reduce((o,a)=>o+a[0].toUpperCase()+a.slice(1))}function i(s){let o,a;const l=s.split(/[ |,]+/);return l.length>1&&!/^[[<]/.test(l[1])&&(o=l.shift()),a=l.shift(),!o&&/^-[^-]$/.test(a)&&(o=a,a=void 0),{shortFlag:o,longFlag:a}}return Ve.Option=e,Ve.DualOptions=n,Ve}var pt={},Ht;function ri(){if(Ht)return pt;Ht=1;const t=3;function e(r,i){if(Math.abs(r.length-i.length)>t)return Math.max(r.length,i.length);const s=[];for(let o=0;o<=r.length;o++)s[o]=[o];for(let o=0;o<=i.length;o++)s[0][o]=o;for(let o=1;o<=i.length;o++)for(let a=1;a<=r.length;a++){let l=1;r[a-1]===i[o-1]?l=0:l=1,s[a][o]=Math.min(s[a-1][o]+1,s[a][o-1]+1,s[a-1][o-1]+l),a>1&&o>1&&r[a-1]===i[o-2]&&r[a-2]===i[o-1]&&(s[a][o]=Math.min(s[a][o],s[a-2][o-2]+1))}return s[r.length][i.length]}function n(r,i){if(!i||i.length===0)return"";i=Array.from(new Set(i));const s=r.startsWith("--");s&&(r=r.slice(2),i=i.map(g=>g.slice(2)));let o=[],a=t;const l=.4;return i.forEach(g=>{if(g.length<=1)return;const p=e(r,g),E=Math.max(r.length,g.length);(E-p)/E>l&&(p<a?(a=p,o=[g]):p===a&&o.push(g))}),o.sort((g,p)=>g.localeCompare(p)),s&&(o=o.map(g=>`--${g}`)),o.length>1?`
9
- (Did you mean one of ${o.join(", ")}?)`:o.length===1?`
10
- (Did you mean ${o[0]}?)`:""}return pt.suggestSimilar=n,pt}var Kt;function ii(){if(Kt)return gt;Kt=1;const t=Zr.EventEmitter,e=Vr,n=$n,r=Hr,i=Y,{Argument:s,humanReadableArgName:o}=Ot(),{CommanderError:a}=ot(),{Help:l}=Pn(),{Option:g,DualOptions:p}=Rn(),{suggestSimilar:E}=ri();class m extends t{constructor(u){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=u||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:c=>i.stdout.write(c),writeErr:c=>i.stderr.write(c),getOutHelpWidth:()=>i.stdout.isTTY?i.stdout.columns:void 0,getErrHelpWidth:()=>i.stderr.isTTY?i.stderr.columns:void 0,outputError:(c,h)=>h(c)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(u){return this._outputConfiguration=u._outputConfiguration,this._helpOption=u._helpOption,this._helpCommand=u._helpCommand,this._helpConfiguration=u._helpConfiguration,this._exitCallback=u._exitCallback,this._storeOptionsAsProperties=u._storeOptionsAsProperties,this._combineFlagAndOptionalValue=u._combineFlagAndOptionalValue,this._allowExcessArguments=u._allowExcessArguments,this._enablePositionalOptions=u._enablePositionalOptions,this._showHelpAfterError=u._showHelpAfterError,this._showSuggestionAfterError=u._showSuggestionAfterError,this}_getCommandAndAncestors(){const u=[];for(let c=this;c;c=c.parent)u.push(c);return u}command(u,c,h){let d=c,f=h;typeof d=="object"&&d!==null&&(f=d,d=null),f=f||{};const[,_,O]=u.match(/([^ ]+) *(.*)/),A=this.createCommand(_);return d&&(A.description(d),A._executableHandler=!0),f.isDefault&&(this._defaultCommandName=A._name),A._hidden=!!(f.noHelp||f.hidden),A._executableFile=f.executableFile||null,O&&A.arguments(O),this._registerCommand(A),A.parent=this,A.copyInheritedSettings(this),d?this:A}createCommand(u){return new m(u)}createHelp(){return Object.assign(new l,this.configureHelp())}configureHelp(u){return u===void 0?this._helpConfiguration:(this._helpConfiguration=u,this)}configureOutput(u){return u===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,u),this)}showHelpAfterError(u=!0){return typeof u!="string"&&(u=!!u),this._showHelpAfterError=u,this}showSuggestionAfterError(u=!0){return this._showSuggestionAfterError=!!u,this}addCommand(u,c){if(!u._name)throw new Error(`Command passed to .addCommand() must have a name
11
- - specify the name in Command constructor or using .name()`);return c=c||{},c.isDefault&&(this._defaultCommandName=u._name),(c.noHelp||c.hidden)&&(u._hidden=!0),this._registerCommand(u),u.parent=this,u._checkForBrokenPassThrough(),this}createArgument(u,c){return new s(u,c)}argument(u,c,h,d){const f=this.createArgument(u,c);return typeof h=="function"?f.default(d).argParser(h):f.default(h),this.addArgument(f),this}arguments(u){return u.trim().split(/ +/).forEach(c=>{this.argument(c)}),this}addArgument(u){const c=this.registeredArguments.slice(-1)[0];if(c&&c.variadic)throw new Error(`only the last argument can be variadic '${c.name()}'`);if(u.required&&u.defaultValue!==void 0&&u.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${u.name()}'`);return this.registeredArguments.push(u),this}helpCommand(u,c){if(typeof u=="boolean")return this._addImplicitHelpCommand=u,this;u=u??"help [command]";const[,h,d]=u.match(/([^ ]+) *(.*)/),f=c??"display help for command",_=this.createCommand(h);return _.helpOption(!1),d&&_.arguments(d),f&&_.description(f),this._addImplicitHelpCommand=!0,this._helpCommand=_,this}addHelpCommand(u,c){return typeof u!="object"?(this.helpCommand(u,c),this):(this._addImplicitHelpCommand=!0,this._helpCommand=u,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(u,c){const h=["preSubcommand","preAction","postAction"];if(!h.includes(u))throw new Error(`Unexpected value for event passed to hook : '${u}'.
12
- Expecting one of '${h.join("', '")}'`);return this._lifeCycleHooks[u]?this._lifeCycleHooks[u].push(c):this._lifeCycleHooks[u]=[c],this}exitOverride(u){return u?this._exitCallback=u:this._exitCallback=c=>{if(c.code!=="commander.executeSubCommandAsync")throw c},this}_exit(u,c,h){this._exitCallback&&this._exitCallback(new a(u,c,h)),i.exit(u)}action(u){const c=h=>{const d=this.registeredArguments.length,f=h.slice(0,d);return this._storeOptionsAsProperties?f[d]=this:f[d]=this.opts(),f.push(this),u.apply(this,f)};return this._actionHandler=c,this}createOption(u,c){return new g(u,c)}_callParseArg(u,c,h,d){try{return u.parseArg(c,h)}catch(f){if(f.code==="commander.invalidArgument"){const _=`${d} ${f.message}`;this.error(_,{exitCode:f.exitCode,code:f.code})}throw f}}_registerOption(u){const c=u.short&&this._findOption(u.short)||u.long&&this._findOption(u.long);if(c){const h=u.long&&this._findOption(u.long)?u.long:u.short;throw new Error(`Cannot add option '${u.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${h}'
13
- - already used by option '${c.flags}'`)}this.options.push(u)}_registerCommand(u){const c=d=>[d.name()].concat(d.aliases()),h=c(u).find(d=>this._findCommand(d));if(h){const d=c(this._findCommand(h)).join("|"),f=c(u).join("|");throw new Error(`cannot add command '${f}' as already have command '${d}'`)}this.commands.push(u)}addOption(u){this._registerOption(u);const c=u.name(),h=u.attributeName();if(u.negate){const f=u.long.replace(/^--no-/,"--");this._findOption(f)||this.setOptionValueWithSource(h,u.defaultValue===void 0?!0:u.defaultValue,"default")}else u.defaultValue!==void 0&&this.setOptionValueWithSource(h,u.defaultValue,"default");const d=(f,_,O)=>{f==null&&u.presetArg!==void 0&&(f=u.presetArg);const A=this.getOptionValue(h);f!==null&&u.parseArg?f=this._callParseArg(u,f,A,_):f!==null&&u.variadic&&(f=u._concatValue(f,A)),f==null&&(u.negate?f=!1:u.isBoolean()||u.optional?f=!0:f=""),this.setOptionValueWithSource(h,f,O)};return this.on("option:"+c,f=>{const _=`error: option '${u.flags}' argument '${f}' is invalid.`;d(f,_,"cli")}),u.envVar&&this.on("optionEnv:"+c,f=>{const _=`error: option '${u.flags}' value '${f}' from env '${u.envVar}' is invalid.`;d(f,_,"env")}),this}_optionEx(u,c,h,d,f){if(typeof c=="object"&&c instanceof g)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const _=this.createOption(c,h);if(_.makeOptionMandatory(!!u.mandatory),typeof d=="function")_.default(f).argParser(d);else if(d instanceof RegExp){const O=d;d=(A,x)=>{const P=O.exec(A);return P?P[0]:x},_.default(f).argParser(d)}else _.default(d);return this.addOption(_)}option(u,c,h,d){return this._optionEx({},u,c,h,d)}requiredOption(u,c,h,d){return this._optionEx({mandatory:!0},u,c,h,d)}combineFlagAndOptionalValue(u=!0){return this._combineFlagAndOptionalValue=!!u,this}allowUnknownOption(u=!0){return this._allowUnknownOption=!!u,this}allowExcessArguments(u=!0){return this._allowExcessArguments=!!u,this}enablePositionalOptions(u=!0){return this._enablePositionalOptions=!!u,this}passThroughOptions(u=!0){return this._passThroughOptions=!!u,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(u=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!u,this}getOptionValue(u){return this._storeOptionsAsProperties?this[u]:this._optionValues[u]}setOptionValue(u,c){return this.setOptionValueWithSource(u,c,void 0)}setOptionValueWithSource(u,c,h){return this._storeOptionsAsProperties?this[u]=c:this._optionValues[u]=c,this._optionValueSources[u]=h,this}getOptionValueSource(u){return this._optionValueSources[u]}getOptionValueSourceWithGlobals(u){let c;return this._getCommandAndAncestors().forEach(h=>{h.getOptionValueSource(u)!==void 0&&(c=h.getOptionValueSource(u))}),c}_prepareUserArgs(u,c){if(u!==void 0&&!Array.isArray(u))throw new Error("first parameter to parse must be array or undefined");if(c=c||{},u===void 0&&c.from===void 0){i.versions?.electron&&(c.from="electron");const d=i.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(c.from="eval")}u===void 0&&(u=i.argv),this.rawArgs=u.slice();let h;switch(c.from){case void 0:case"node":this._scriptPath=u[1],h=u.slice(2);break;case"electron":i.defaultApp?(this._scriptPath=u[1],h=u.slice(2)):h=u.slice(1);break;case"user":h=u.slice(0);break;case"eval":h=u.slice(1);break;default:throw new Error(`unexpected parse option { from: '${c.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",h}parse(u,c){const h=this._prepareUserArgs(u,c);return this._parseCommand([],h),this}async parseAsync(u,c){const h=this._prepareUserArgs(u,c);return await this._parseCommand([],h),this}_executeSubCommand(u,c){c=c.slice();let h=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function f(P,M){const j=n.resolve(P,M);if(r.existsSync(j))return j;if(d.includes(n.extname(M)))return;const w=d.find(z=>r.existsSync(`${j}${z}`));if(w)return`${j}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let _=u._executableFile||`${this._name}-${u._name}`,O=this._executableDir||"";if(this._scriptPath){let P;try{P=r.realpathSync(this._scriptPath)}catch{P=this._scriptPath}O=n.resolve(n.dirname(P),O)}if(O){let P=f(O,_);if(!P&&!u._executableFile&&this._scriptPath){const M=n.basename(this._scriptPath,n.extname(this._scriptPath));M!==this._name&&(P=f(O,`${M}-${u._name}`))}_=P||_}h=d.includes(n.extname(_));let A;i.platform!=="win32"?h?(c.unshift(_),c=F(i.execArgv).concat(c),A=e.spawn(i.argv[0],c,{stdio:"inherit"})):A=e.spawn(_,c,{stdio:"inherit"}):(c.unshift(_),c=F(i.execArgv).concat(c),A=e.spawn(i.execPath,c,{stdio:"inherit"})),A.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(M=>{i.on(M,()=>{A.killed===!1&&A.exitCode===null&&A.kill(M)})});const x=this._exitCallback;A.on("close",P=>{P=P??1,x?x(new a(P,"commander.executeSubCommandAsync","(close)")):i.exit(P)}),A.on("error",P=>{if(P.code==="ENOENT"){const M=O?`searched for local subcommand relative to directory '${O}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",j=`'${_}' does not exist
14
- - if '${u._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
15
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
16
- - ${M}`;throw new Error(j)}else if(P.code==="EACCES")throw new Error(`'${_}' not executable`);if(!x)i.exit(1);else{const M=new a(1,"commander.executeSubCommandAsync","(error)");M.nestedError=P,x(M)}}),this.runningCommand=A}_dispatchSubcommand(u,c,h){const d=this._findCommand(u);d||this.help({error:!0});let f;return f=this._chainOrCallSubCommandHook(f,d,"preSubcommand"),f=this._chainOrCall(f,()=>{if(d._executableHandler)this._executeSubCommand(d,c.concat(h));else return d._parseCommand(c,h)}),f}_dispatchHelpCommand(u){u||this.help();const c=this._findCommand(u);return c&&!c._executableHandler&&c.help(),this._dispatchSubcommand(u,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((u,c)=>{u.required&&this.args[c]==null&&this.missingArgument(u.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){const u=(h,d,f)=>{let _=d;if(d!==null&&h.parseArg){const O=`error: command-argument value '${d}' is invalid for argument '${h.name()}'.`;_=this._callParseArg(h,d,f,O)}return _};this._checkNumberOfArguments();const c=[];this.registeredArguments.forEach((h,d)=>{let f=h.defaultValue;h.variadic?d<this.args.length?(f=this.args.slice(d),h.parseArg&&(f=f.reduce((_,O)=>u(h,O,_),h.defaultValue))):f===void 0&&(f=[]):d<this.args.length&&(f=this.args[d],h.parseArg&&(f=u(h,f,h.defaultValue))),c[d]=f}),this.processedArgs=c}_chainOrCall(u,c){return u&&u.then&&typeof u.then=="function"?u.then(()=>c()):c()}_chainOrCallHooks(u,c){let h=u;const d=[];return this._getCommandAndAncestors().reverse().filter(f=>f._lifeCycleHooks[c]!==void 0).forEach(f=>{f._lifeCycleHooks[c].forEach(_=>{d.push({hookedCommand:f,callback:_})})}),c==="postAction"&&d.reverse(),d.forEach(f=>{h=this._chainOrCall(h,()=>f.callback(f.hookedCommand,this))}),h}_chainOrCallSubCommandHook(u,c,h){let d=u;return this._lifeCycleHooks[h]!==void 0&&this._lifeCycleHooks[h].forEach(f=>{d=this._chainOrCall(d,()=>f(this,c))}),d}_parseCommand(u,c){const h=this.parseOptions(c);if(this._parseOptionsEnv(),this._parseOptionsImplied(),u=u.concat(h.operands),c=h.unknown,this.args=u.concat(c),u&&this._findCommand(u[0]))return this._dispatchSubcommand(u[0],u.slice(1),c);if(this._getHelpCommand()&&u[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(u[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(c),this._dispatchSubcommand(this._defaultCommandName,u,c);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(h.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{h.unknown.length>0&&this.unknownOption(h.unknown[0])},f=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let _;return _=this._chainOrCallHooks(_,"preAction"),_=this._chainOrCall(_,()=>this._actionHandler(this.processedArgs)),this.parent&&(_=this._chainOrCall(_,()=>{this.parent.emit(f,u,c)})),_=this._chainOrCallHooks(_,"postAction"),_}if(this.parent&&this.parent.listenerCount(f))d(),this._processArguments(),this.parent.emit(f,u,c);else if(u.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",u,c);this.listenerCount("command:*")?this.emit("command:*",u,c):this.commands.length?this.unknownCommand():(d(),this._processArguments())}else this.commands.length?(d(),this.help({error:!0})):(d(),this._processArguments())}_findCommand(u){if(u)return this.commands.find(c=>c._name===u||c._aliases.includes(u))}_findOption(u){return this.options.find(c=>c.is(u))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(u=>{u.options.forEach(c=>{c.mandatory&&u.getOptionValue(c.attributeName())===void 0&&u.missingMandatoryOptionValue(c)})})}_checkForConflictingLocalOptions(){const u=this.options.filter(h=>{const d=h.attributeName();return this.getOptionValue(d)===void 0?!1:this.getOptionValueSource(d)!=="default"});u.filter(h=>h.conflictsWith.length>0).forEach(h=>{const d=u.find(f=>h.conflictsWith.includes(f.attributeName()));d&&this._conflictingOption(h,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(u=>{u._checkForConflictingLocalOptions()})}parseOptions(u){const c=[],h=[];let d=c;const f=u.slice();function _(A){return A.length>1&&A[0]==="-"}let O=null;for(;f.length;){const A=f.shift();if(A==="--"){d===h&&d.push(A),d.push(...f);break}if(O&&!_(A)){this.emit(`option:${O.name()}`,A);continue}if(O=null,_(A)){const x=this._findOption(A);if(x){if(x.required){const P=f.shift();P===void 0&&this.optionMissingArgument(x),this.emit(`option:${x.name()}`,P)}else if(x.optional){let P=null;f.length>0&&!_(f[0])&&(P=f.shift()),this.emit(`option:${x.name()}`,P)}else this.emit(`option:${x.name()}`);O=x.variadic?x:null;continue}}if(A.length>2&&A[0]==="-"&&A[1]!=="-"){const x=this._findOption(`-${A[1]}`);if(x){x.required||x.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${x.name()}`,A.slice(2)):(this.emit(`option:${x.name()}`),f.unshift(`-${A.slice(2)}`));continue}}if(/^--[^=]+=/.test(A)){const x=A.indexOf("="),P=this._findOption(A.slice(0,x));if(P&&(P.required||P.optional)){this.emit(`option:${P.name()}`,A.slice(x+1));continue}}if(_(A)&&(d=h),(this._enablePositionalOptions||this._passThroughOptions)&&c.length===0&&h.length===0){if(this._findCommand(A)){c.push(A),f.length>0&&h.push(...f);break}else if(this._getHelpCommand()&&A===this._getHelpCommand().name()){c.push(A),f.length>0&&c.push(...f);break}else if(this._defaultCommandName){h.push(A),f.length>0&&h.push(...f);break}}if(this._passThroughOptions){d.push(A),f.length>0&&d.push(...f);break}d.push(A)}return{operands:c,unknown:h}}opts(){if(this._storeOptionsAsProperties){const u={},c=this.options.length;for(let h=0;h<c;h++){const d=this.options[h].attributeName();u[d]=d===this._versionOptionName?this._version:this[d]}return u}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((u,c)=>Object.assign(u,c.opts()),{})}error(u,c){this._outputConfiguration.outputError(`${u}
17
- `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
18
- `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
19
- `),this.outputHelp({error:!0}));const h=c||{},d=h.exitCode||1,f=h.code||"commander.error";this._exit(d,f,u)}_parseOptionsEnv(){this.options.forEach(u=>{if(u.envVar&&u.envVar in i.env){const c=u.attributeName();(this.getOptionValue(c)===void 0||["default","config","env"].includes(this.getOptionValueSource(c)))&&(u.required||u.optional?this.emit(`optionEnv:${u.name()}`,i.env[u.envVar]):this.emit(`optionEnv:${u.name()}`))}})}_parseOptionsImplied(){const u=new p(this.options),c=h=>this.getOptionValue(h)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(h));this.options.filter(h=>h.implied!==void 0&&c(h.attributeName())&&u.valueFromOption(this.getOptionValue(h.attributeName()),h)).forEach(h=>{Object.keys(h.implied).filter(d=>!c(d)).forEach(d=>{this.setOptionValueWithSource(d,h.implied[d],"implied")})})}missingArgument(u){const c=`error: missing required argument '${u}'`;this.error(c,{code:"commander.missingArgument"})}optionMissingArgument(u){const c=`error: option '${u.flags}' argument missing`;this.error(c,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(u){const c=`error: required option '${u.flags}' not specified`;this.error(c,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(u,c){const h=_=>{const O=_.attributeName(),A=this.getOptionValue(O),x=this.options.find(M=>M.negate&&O===M.attributeName()),P=this.options.find(M=>!M.negate&&O===M.attributeName());return x&&(x.presetArg===void 0&&A===!1||x.presetArg!==void 0&&A===x.presetArg)?x:P||_},d=_=>{const O=h(_),A=O.attributeName();return this.getOptionValueSource(A)==="env"?`environment variable '${O.envVar}'`:`option '${O.flags}'`},f=`error: ${d(u)} cannot be used with ${d(c)}`;this.error(f,{code:"commander.conflictingOption"})}unknownOption(u){if(this._allowUnknownOption)return;let c="";if(u.startsWith("--")&&this._showSuggestionAfterError){let d=[],f=this;do{const _=f.createHelp().visibleOptions(f).filter(O=>O.long).map(O=>O.long);d=d.concat(_),f=f.parent}while(f&&!f._enablePositionalOptions);c=E(u,d)}const h=`error: unknown option '${u}'${c}`;this.error(h,{code:"commander.unknownOption"})}_excessArguments(u){if(this._allowExcessArguments)return;const c=this.registeredArguments.length,h=c===1?"":"s",f=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${c} argument${h} but got ${u.length}.`;this.error(f,{code:"commander.excessArguments"})}unknownCommand(){const u=this.args[0];let c="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(f=>{d.push(f.name()),f.alias()&&d.push(f.alias())}),c=E(u,d)}const h=`error: unknown command '${u}'${c}`;this.error(h,{code:"commander.unknownCommand"})}version(u,c,h){if(u===void 0)return this._version;this._version=u,c=c||"-V, --version",h=h||"output the version number";const d=this.createOption(c,h);return this._versionOptionName=d.attributeName(),this._registerOption(d),this.on("option:"+d.name(),()=>{this._outputConfiguration.writeOut(`${u}
20
- `),this._exit(0,"commander.version",u)}),this}description(u,c){return u===void 0&&c===void 0?this._description:(this._description=u,c&&(this._argsDescription=c),this)}summary(u){return u===void 0?this._summary:(this._summary=u,this)}alias(u){if(u===void 0)return this._aliases[0];let c=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(c=this.commands[this.commands.length-1]),u===c._name)throw new Error("Command alias can't be the same as its name");const h=this.parent?._findCommand(u);if(h){const d=[h.name()].concat(h.aliases()).join("|");throw new Error(`cannot add alias '${u}' to command '${this.name()}' as already have command '${d}'`)}return c._aliases.push(u),this}aliases(u){return u===void 0?this._aliases:(u.forEach(c=>this.alias(c)),this)}usage(u){if(u===void 0){if(this._usage)return this._usage;const c=this.registeredArguments.map(h=>o(h));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?c:[]).join(" ")}return this._usage=u,this}name(u){return u===void 0?this._name:(this._name=u,this)}nameFromFilename(u){return this._name=n.basename(u,n.extname(u)),this}executableDir(u){return u===void 0?this._executableDir:(this._executableDir=u,this)}helpInformation(u){const c=this.createHelp();return c.helpWidth===void 0&&(c.helpWidth=u&&u.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),c.formatHelp(this,c)}_getHelpContext(u){u=u||{};const c={error:!!u.error};let h;return c.error?h=d=>this._outputConfiguration.writeErr(d):h=d=>this._outputConfiguration.writeOut(d),c.write=u.write||h,c.command=this,c}outputHelp(u){let c;typeof u=="function"&&(c=u,u=void 0);const h=this._getHelpContext(u);this._getCommandAndAncestors().reverse().forEach(f=>f.emit("beforeAllHelp",h)),this.emit("beforeHelp",h);let d=this.helpInformation(h);if(c&&(d=c(d),typeof d!="string"&&!Buffer.isBuffer(d)))throw new Error("outputHelp callback must return a string or a Buffer");h.write(d),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",h),this._getCommandAndAncestors().forEach(f=>f.emit("afterAllHelp",h))}helpOption(u,c){return typeof u=="boolean"?(u?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(u=u??"-h, --help",c=c??"display help for command",this._helpOption=this.createOption(u,c),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(u){return this._helpOption=u,this}help(u){this.outputHelp(u);let c=i.exitCode||0;c===0&&u&&typeof u!="function"&&u.error&&(c=1),this._exit(c,"commander.help","(outputHelp)")}addHelpText(u,c){const h=["beforeAll","before","after","afterAll"];if(!h.includes(u))throw new Error(`Unexpected value for position to addHelpText.
21
- Expecting one of '${h.join("', '")}'`);const d=`${u}Help`;return this.on(d,f=>{let _;typeof c=="function"?_=c({error:f.error,command:f.command}):_=c,_&&f.write(`${_}
22
- `)}),this}_outputHelpIfRequested(u){const c=this._getHelpOption();c&&u.find(d=>c.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function F(k){return k.map(u=>{if(!u.startsWith("--inspect"))return u;let c,h="127.0.0.1",d="9229",f;return(f=u.match(/^(--inspect(-brk)?)$/))!==null?c=f[1]:(f=u.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(c=f[1],/^\d+$/.test(f[3])?d=f[3]:h=f[3]):(f=u.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(c=f[1],h=f[3],d=f[4]),c&&d!=="0"?`${c}=${h}:${parseInt(d)+1}`:u})}return gt.Command=m,gt}var qt;function si(){if(qt)return oe;qt=1;const{Argument:t}=Ot(),{Command:e}=ii(),{CommanderError:n,InvalidArgumentError:r}=ot(),{Help:i}=Pn(),{Option:s}=Rn();return oe.program=new e,oe.createCommand=o=>new e(o),oe.createOption=(o,a)=>new s(o,a),oe.createArgument=(o,a)=>new t(o,a),oe.Command=e,oe.Option=s,oe.Argument=t,oe.Help=i,oe.CommanderError=n,oe.InvalidArgumentError=r,oe.InvalidOptionArgumentError=r,oe}var oi=si();const ai=D.getDefaultExportFromCjs(oi),{program:wh,createCommand:Ch,createArgument:bh,createOption:Ah,CommanderError:Th,InvalidArgumentError:kh,InvalidOptionArgumentError:Ih,Command:ui,Argument:$h,Option:Oh,Help:xh}=ai;var de={exports:{}};const ci="17.2.1",li={version:ci};var Yt;function hi(){if(Yt)return de.exports;Yt=1;const t=T,e=C,n=ae,r=On,s=li.version,o=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 observe env with Radar: https://dotenvx.com/radar","📡 auto-backup env with Radar: https://dotenvx.com/radar","📡 version env with Radar: https://dotenvx.com/radar","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function a(){return o[Math.floor(Math.random()*o.length)]}function l(w){return typeof w=="string"?!["false","0","no","off",""].includes(w.toLowerCase()):!!w}function g(){return process.stdout.isTTY}function p(w){return g()?`\x1B[2m${w}\x1B[0m`:w}const E=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function m(w){const z={};let G=w.toString();G=G.replace(/\r\n?/mg,`
23
- `);let L;for(;(L=E.exec(G))!=null;){const ee=L[1];let W=L[2]||"";W=W.trim();const R=W[0];W=W.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),R==='"'&&(W=W.replace(/\\n/g,`
24
- `),W=W.replace(/\\r/g,"\r")),z[ee]=W}return z}function F(w){w=w||{};const z=f(w);w.path=z;const G=j.configDotenv(w);if(!G.parsed){const R=new Error(`MISSING_DATA: Cannot parse ${z} for an unknown reason`);throw R.code="MISSING_DATA",R}const L=h(w).split(","),ee=L.length;let W;for(let R=0;R<ee;R++)try{const te=L[R].trim(),ce=d(G,te);W=j.decrypt(ce.ciphertext,ce.key);break}catch(te){if(R+1>=ee)throw te}return j.parse(W)}function k(w){console.error(`[dotenv@${s}][WARN] ${w}`)}function u(w){console.log(`[dotenv@${s}][DEBUG] ${w}`)}function c(w){console.log(`[dotenv@${s}] ${w}`)}function h(w){return w&&w.DOTENV_KEY&&w.DOTENV_KEY.length>0?w.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function d(w,z){let G;try{G=new URL(z)}catch(te){if(te.code==="ERR_INVALID_URL"){const ce=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw ce.code="INVALID_DOTENV_KEY",ce}throw te}const L=G.password;if(!L){const te=new Error("INVALID_DOTENV_KEY: Missing key part");throw te.code="INVALID_DOTENV_KEY",te}const ee=G.searchParams.get("environment");if(!ee){const te=new Error("INVALID_DOTENV_KEY: Missing environment part");throw te.code="INVALID_DOTENV_KEY",te}const W=`DOTENV_VAULT_${ee.toUpperCase()}`,R=w.parsed[W];if(!R){const te=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${W} in your .env.vault file.`);throw te.code="NOT_FOUND_DOTENV_ENVIRONMENT",te}return{ciphertext:R,key:L}}function f(w){let z=null;if(w&&w.path&&w.path.length>0)if(Array.isArray(w.path))for(const G of w.path)t.existsSync(G)&&(z=G.endsWith(".vault")?G:`${G}.vault`);else z=w.path.endsWith(".vault")?w.path:`${w.path}.vault`;else z=e.resolve(process.cwd(),".env.vault");return t.existsSync(z)?z:null}function _(w){return w[0]==="~"?e.join(n.homedir(),w.slice(1)):w}function O(w){const z=l(process.env.DOTENV_CONFIG_DEBUG||w&&w.debug),G=l(process.env.DOTENV_CONFIG_QUIET||w&&w.quiet);(z||!G)&&c("Loading env from encrypted .env.vault");const L=j._parseVault(w);let ee=process.env;return w&&w.processEnv!=null&&(ee=w.processEnv),j.populate(ee,L,w),{parsed:L}}function A(w){const z=e.resolve(process.cwd(),".env");let G="utf8",L=process.env;w&&w.processEnv!=null&&(L=w.processEnv);let ee=l(L.DOTENV_CONFIG_DEBUG||w&&w.debug),W=l(L.DOTENV_CONFIG_QUIET||w&&w.quiet);w&&w.encoding?G=w.encoding:ee&&u("No encoding is specified. UTF-8 is used by default");let R=[z];if(w&&w.path)if(!Array.isArray(w.path))R=[_(w.path)];else{R=[];for(const le of w.path)R.push(_(le))}let te;const ce={};for(const le of R)try{const ye=j.parse(t.readFileSync(le,{encoding:G}));j.populate(ce,ye,w)}catch(ye){ee&&u(`Failed to load ${le} ${ye.message}`),te=ye}const ht=j.populate(L,ce,w);if(ee=l(L.DOTENV_CONFIG_DEBUG||ee),W=l(L.DOTENV_CONFIG_QUIET||W),ee||!W){const le=Object.keys(ht).length,ye=[];for(const Gt of R)try{const je=e.relative(process.cwd(),Gt);ye.push(je)}catch(je){ee&&u(`Failed to load ${Gt} ${je.message}`),te=je}c(`injecting env (${le}) from ${ye.join(",")} ${p(`-- tip: ${a()}`)}`)}return te?{parsed:ce,error:te}:{parsed:ce}}function x(w){if(h(w).length===0)return j.configDotenv(w);const z=f(w);return z?j._configVault(w):(k(`You set DOTENV_KEY but you are missing a .env.vault file at ${z}. Did you forget to build it?`),j.configDotenv(w))}function P(w,z){const G=Buffer.from(z.slice(-64),"hex");let L=Buffer.from(w,"base64");const ee=L.subarray(0,12),W=L.subarray(-16);L=L.subarray(12,-16);try{const R=r.createDecipheriv("aes-256-gcm",G,ee);return R.setAuthTag(W),`${R.update(L)}${R.final()}`}catch(R){const te=R instanceof RangeError,ce=R.message==="Invalid key length",ht=R.message==="Unsupported state or unable to authenticate data";if(te||ce){const le=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw le.code="INVALID_DOTENV_KEY",le}else if(ht){const le=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw le.code="DECRYPTION_FAILED",le}else throw R}}function M(w,z,G={}){const L=!!(G&&G.debug),ee=!!(G&&G.override),W={};if(typeof z!="object"){const R=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw R.code="OBJECT_REQUIRED",R}for(const R of Object.keys(z))Object.prototype.hasOwnProperty.call(w,R)?(ee===!0&&(w[R]=z[R],W[R]=z[R]),L&&u(ee===!0?`"${R}" is already defined and WAS overwritten`:`"${R}" is already defined and was NOT overwritten`)):(w[R]=z[R],W[R]=z[R]);return W}const j={configDotenv:A,_configVault:O,_parseVault:F,config:x,decrypt:P,parse:m,populate:M};return de.exports.configDotenv=j.configDotenv,de.exports._configVault=j._configVault,de.exports._parseVault=j._parseVault,de.exports.config=j.config,de.exports.decrypt=j.decrypt,de.exports.parse=j.parse,de.exports.populate=j.populate,de.exports=j,de.exports}var di=hi();const Nn=D.getDefaultExportFromCjs(di),mt=10,Jt=(t=0)=>e=>`\x1B[${e+t}m`,Qt=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,Xt=(t=0)=>(e,n,r)=>`\x1B[${38+t};2;${e};${n};${r}m`,V={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(V.modifier);const gi=Object.keys(V.color),fi=Object.keys(V.bgColor);[...gi,...fi];function pi(){const t=new Map;for(const[e,n]of Object.entries(V)){for(const[r,i]of Object.entries(n))V[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=V[r],t.set(i[0],i[1]);Object.defineProperty(V,e,{value:n,enumerable:!1})}return Object.defineProperty(V,"codes",{value:t,enumerable:!1}),V.color.close="\x1B[39m",V.bgColor.close="\x1B[49m",V.color.ansi=Jt(),V.color.ansi256=Qt(),V.color.ansi16m=Xt(),V.bgColor.ansi=Jt(mt),V.bgColor.ansi256=Qt(mt),V.bgColor.ansi16m=Xt(mt),Object.defineProperties(V,{rgbToAnsi256:{value(e,n,r){return e===n&&n===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(e){const n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(s=>s+s).join(""));const i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>V.rgbToAnsi256(...V.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,i;if(e>=232)n=((e-232)*10+8)/255,r=n,i=n;else{e-=16;const a=e%36;n=Math.floor(e/36)/5,r=Math.floor(a/6)/5,i=a%6/5}const s=Math.max(n,r,i)*2;if(s===0)return 30;let o=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>V.ansi256ToAnsi(V.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>V.ansi256ToAnsi(V.hexToAnsi256(e)),enumerable:!1}}),V}const ge=pi(),en=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),tn=en!==0&&{level:en},mi={stdout:tn,stderr:tn};function Di(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const i=e.length;let s=0,o="";do o+=t.slice(s,r)+e+n,s=r+i,r=t.indexOf(e,s);while(r!==-1);return o+=t.slice(s),o}function Ei(t,e,n,r){let i=0,s="";do{const o=t[r-1]==="\r";s+=t.slice(i,o?r-1:r)+e+(o?`\r
25
- `:`
26
- `)+n,i=r+1,r=t.indexOf(`
27
- `,i)}while(r!==-1);return s+=t.slice(i),s}const{stdout:nn,stderr:rn}=mi,St=Symbol("GENERATOR"),ke=Symbol("STYLER"),xe=Symbol("IS_EMPTY"),sn=["ansi","ansi","ansi256","ansi16m"],Ie=Object.create(null),vi=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const n=nn?nn.level:0;t.level=e.level===void 0?n:e.level},yi=t=>{const e=(...n)=>n.join(" ");return vi(e,t),Object.setPrototypeOf(e,Ue.prototype),e};function Ue(t){return yi(t)}Object.setPrototypeOf(Ue.prototype,Function.prototype);for(const[t,e]of Object.entries(ge))Ie[t]={get(){const n=tt(this,wt(e.open,e.close,this[ke]),this[xe]);return Object.defineProperty(this,t,{value:n}),n}};Ie.visible={get(){const t=tt(this,this[ke],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const Ft=(t,e,n,...r)=>t==="rgb"?e==="ansi16m"?ge[n].ansi16m(...r):e==="ansi256"?ge[n].ansi256(ge.rgbToAnsi256(...r)):ge[n].ansi(ge.rgbToAnsi(...r)):t==="hex"?Ft("rgb",e,n,...ge.hexToRgb(...r)):ge[n][t](...r),_i=["rgb","hex","ansi256"];for(const t of _i){Ie[t]={get(){const{level:n}=this;return function(...r){const i=wt(Ft(t,sn[n],"color",...r),ge.color.close,this[ke]);return tt(this,i,this[xe])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);Ie[e]={get(){const{level:n}=this;return function(...r){const i=wt(Ft(t,sn[n],"bgColor",...r),ge.bgColor.close,this[ke]);return tt(this,i,this[xe])}}}}const Si=Object.defineProperties(()=>{},{...Ie,level:{enumerable:!0,get(){return this[St].level},set(t){this[St].level=t}}}),wt=(t,e,n)=>{let r,i;return n===void 0?(r=t,i=e):(r=n.openAll+t,i=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:i,parent:n}},tt=(t,e,n)=>{const r=(...i)=>Fi(r,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(r,Si),r[St]=t,r[ke]=e,r[xe]=n,r},Fi=(t,e)=>{if(t.level<=0||!e)return t[xe]?"":e;let n=t[ke];if(n===void 0)return e;const{openAll:r,closeAll:i}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=Di(e,n.close,n.open),n=n.parent;const s=e.indexOf(`
28
- `);return s!==-1&&(e=Ei(e,i,r,s)),r+e+i};Object.defineProperties(Ue.prototype,Ie);const wi=Ue();Ue({level:rn?rn.level:0});const Ci=(t,e,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const i=Object.getOwnPropertyDescriptor(t,n),s=Object.getOwnPropertyDescriptor(e,n);!bi(i,s)&&r||Object.defineProperty(t,n,s)},bi=function(t,e){return t===void 0||t.configurable||t.writable===e.writable&&t.enumerable===e.enumerable&&t.configurable===e.configurable&&(t.writable||t.value===e.value)},Ai=(t,e)=>{const n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)},Ti=(t,e)=>`/* Wrapped ${t}*/
29
- ${e}`,ki=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Ii=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),$i=(t,e,n)=>{const r=n===""?"":`with ${n.trim()}() `,i=Ti.bind(null,r,e.toString());Object.defineProperty(i,"name",Ii);const{writable:s,enumerable:o,configurable:a}=ki;Object.defineProperty(t,"toString",{value:i,writable:s,enumerable:o,configurable:a})};function Oi(t,e,{ignoreNonConfigurable:n=!1}={}){const{name:r}=t;for(const i of Reflect.ownKeys(e))Ci(t,e,i,n);return Ai(t,e),$i(t,e,r),t}const nt=new WeakMap,Bn=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let n,r=0;const i=t.displayName||t.name||"<anonymous>",s=function(...o){if(nt.set(s,++r),r===1)n=t.apply(this,o),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return n};return Oi(s,t),nt.set(s,r),s};Bn.callCount=t=>{if(!nt.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return nt.get(t)};const Te=[];Te.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Te.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Te.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");const Xe=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",Dt=Symbol.for("signal-exit emitter"),Et=globalThis,xi=Object.defineProperty.bind(Object);class Pi{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Et[Dt])return Et[Dt];xi(Et,Dt,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,n){this.listeners[e].push(n)}removeListener(e,n){const r=this.listeners[e],i=r.indexOf(n);i!==-1&&(i===0&&r.length===1?r.length=0:r.splice(i,1))}emit(e,n,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(const s of this.listeners[e])i=s(n,r)===!0||i;return e==="exit"&&(i=this.emit("afterExit",n,r)||i),i}}class Un{}const Ri=t=>({onExit(e,n){return t.onExit(e,n)},load(){return t.load()},unload(){return t.unload()}});class Ni extends Un{onExit(){return()=>{}}load(){}unload(){}}class Bi extends Un{#o=Ct.platform==="win32"?"SIGINT":"SIGHUP";#n=new Pi;#e;#i;#d;#t={};#s=!1;constructor(e){super(),this.#e=e,this.#t={};for(const n of Te)this.#t[n]=()=>{const r=this.#e.listeners(n);let{count:i}=this.#n;const s=e;if(typeof s.__signal_exit_emitter__=="object"&&typeof s.__signal_exit_emitter__.count=="number"&&(i+=s.__signal_exit_emitter__.count),r.length===i){this.unload();const o=this.#n.emit("exit",null,n),a=n==="SIGHUP"?this.#o:n;o||e.kill(e.pid,a)}};this.#d=e.reallyExit,this.#i=e.emit}onExit(e,n){if(!Xe(this.#e))return()=>{};this.#s===!1&&this.load();const r=n?.alwaysLast?"afterExit":"exit";return this.#n.on(r,e),()=>{this.#n.removeListener(r,e),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#s){this.#s=!0,this.#n.count+=1;for(const e of Te)try{const n=this.#t[e];n&&this.#e.on(e,n)}catch{}this.#e.emit=(e,...n)=>this.#g(e,...n),this.#e.reallyExit=e=>this.#r(e)}}unload(){this.#s&&(this.#s=!1,Te.forEach(e=>{const n=this.#t[e];if(!n)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,n)}catch{}}),this.#e.emit=this.#i,this.#e.reallyExit=this.#d,this.#n.count-=1)}#r(e){return Xe(this.#e)?(this.#e.exitCode=e||0,this.#n.emit("exit",this.#e.exitCode,null),this.#d.call(this.#e,this.#e.exitCode)):0}#g(e,...n){const r=this.#i;if(e==="exit"&&Xe(this.#e)){typeof n[0]=="number"&&(this.#e.exitCode=n[0]);const i=r.call(this.#e,e,...n);return this.#n.emit("exit",this.#e.exitCode,null),i}else return r.call(this.#e,e,...n)}}const Ct=globalThis.process,{onExit:Ui}=Ri(Xe(Ct)?new Bi(Ct):new Ni),on=Y.stderr.isTTY?Y.stderr:Y.stdout.isTTY?Y.stdout:void 0,zi=on?Bn(()=>{Ui(()=>{on.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{};let rt=!1;const Fe={};Fe.show=(t=Y.stderr)=>{t.isTTY&&(rt=!1,t.write("\x1B[?25h"))};Fe.hide=(t=Y.stderr)=>{t.isTTY&&(zi(),rt=!0,t.write("\x1B[?25l"))};Fe.toggle=(t,e)=>{t!==void 0&&(rt=t),rt?Fe.show(e):Fe.hide(e)};const Mi={interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},Gi={interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},Li={interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},ji={interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},Wi={interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},Zi={interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},Vi={interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},Hi={interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},Ki={interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},qi={interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},Yi={interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},Ji={interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},Qi={interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},Xi={interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},es={interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},ts={interval:130,frames:["-","\\","|","/"]},ns={interval:100,frames:["⠂","-","–","—","–","-"]},rs={interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},is={interval:400,frames:[". ",".. ","..."," "]},ss={interval:200,frames:[". ",".. ","..."," .."," ."," "]},os={interval:70,frames:["✶","✸","✹","✺","✹","✷"]},as={interval:80,frames:["+","x","*"]},us={interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},cs={interval:100,frames:["☱","☲","☴"]},ls={interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},hs={interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},ds={interval:140,frames:[" ",".","o","O","@","*"," "]},gs={interval:120,frames:[".","o","O","°","O","o","."]},fs={interval:100,frames:["▓","▒","░"]},ps={interval:120,frames:["⠁","⠂","⠄","⠂"]},ms={interval:120,frames:["▖","▘","▝","▗"]},Ds={interval:100,frames:["▌","▀","▐","▄"]},Es={interval:50,frames:["◢","◣","◤","◥"]},vs={interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},ys={interval:100,frames:["◜","◠","◝","◞","◡","◟"]},_s={interval:120,frames:["◡","⊙","◠"]},Ss={interval:180,frames:["◰","◳","◲","◱"]},Fs={interval:120,frames:["◴","◷","◶","◵"]},ws={interval:50,frames:["◐","◓","◑","◒"]},Cs={interval:100,frames:["╫","╪"]},bs={interval:250,frames:["⊶","⊷"]},As={interval:80,frames:["▫","▪"]},Ts={interval:120,frames:["□","■"]},ks={interval:100,frames:["■","□","▪","▫"]},Is={interval:100,frames:["▮","▯"]},$s={interval:300,frames:["ဝ","၀"]},Os={interval:80,frames:["⦾","⦿"]},xs={interval:100,frames:["◍","◌"]},Ps={interval:100,frames:["◉","◎"]},Rs={interval:100,frames:["㊂","㊀","㊁"]},Ns={interval:50,frames:["⧇","⧆"]},Bs={interval:120,frames:["☗","☖"]},Us={interval:80,frames:["=","*","-"]},zs={interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},Ms={interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},Gs={interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},Ls={interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},js={interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},Ws={interval:200,frames:["😄 ","😝 "]},Zs={interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},Vs={interval:100,frames:["💛 ","💙 ","💜 ","💚 ","❤️ "]},Hs={interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},Ks={interval:180,frames:["🌍 ","🌎 ","🌏 "]},qs={interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},Ys={interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},Js={interval:140,frames:["🚶 ","🏃 "]},Qs={interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},Xs={interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},eo={interval:100,frames:["d","q","p","b"]},to={interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},no={interval:400,frames:["🌲","🎄"]},ro={interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},io={interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},so={interval:150,frames:["-","=","≡"]},oo={interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},ao={interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},uo={interval:80,frames:["🤜    🤛 ","🤜    🤛 ","🤜    🤛 "," 🤜  🤛  ","  🤜🤛   "," 🤜✨🤛   ","🤜 ✨ 🤛  "]},co={interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},lo={interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","  ","  ","  "]},ho={interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},go={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},fo={interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},po={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},mo={interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},Do={interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},Eo={interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]},vo={dots:Mi,dots2:Gi,dots3:Li,dots4:ji,dots5:Wi,dots6:Zi,dots7:Vi,dots8:Hi,dots9:Ki,dots10:qi,dots11:Yi,dots12:Ji,dots13:Qi,dots8Bit:Xi,sand:es,line:ts,line2:ns,pipe:rs,simpleDots:is,simpleDotsScrolling:ss,star:os,star2:as,flip:us,hamburger:cs,growVertical:ls,growHorizontal:hs,balloon:ds,balloon2:gs,noise:fs,bounce:ps,boxBounce:ms,boxBounce2:Ds,triangle:Es,binary:vs,arc:ys,circle:_s,squareCorners:Ss,circleQuarters:Fs,circleHalves:ws,squish:Cs,toggle:bs,toggle2:As,toggle3:Ts,toggle4:ks,toggle5:Is,toggle6:$s,toggle7:Os,toggle8:xs,toggle9:Ps,toggle10:Rs,toggle11:Ns,toggle12:Bs,toggle13:Us,arrow:zs,arrow2:Ms,arrow3:Gs,bouncingBar:Ls,bouncingBall:js,smiley:Ws,monkey:Zs,hearts:Vs,clock:Hs,earth:Ks,material:qs,moon:Ys,runner:Js,pong:Qs,shark:Xs,dqpb:eo,weather:to,christmas:no,grenade:ro,point:io,layer:so,betaWave:oo,fingerDance:ao,fistBump:uo,soccerHeader:co,mindblown:lo,speaker:ho,orangePulse:go,bluePulse:fo,orangeBluePulse:po,timeTravel:mo,aesthetic:Do,dwarfFortress:Eo};var vt,an;function yo(){if(an)return vt;an=1;const t=Object.assign({},vo),e=Object.keys(t);return Object.defineProperty(t,"random",{get(){const n=Math.floor(Math.random()*e.length),r=e[n];return t[r]}}),vt=t,vt}var _o=yo();const He=D.getDefaultExportFromCjs(_o),Ke={info:"ℹ️",success:"✅",warning:"⚠️",error:"❌️"};function So({onlyFirst:t=!1}={}){const i="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(i,t?void 0:"g")}const Fo=So();function we(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(Fo,"")}function wo(t){return t===161||t===164||t===167||t===168||t===170||t===173||t===174||t>=176&&t<=180||t>=182&&t<=186||t>=188&&t<=191||t===198||t===208||t===215||t===216||t>=222&&t<=225||t===230||t>=232&&t<=234||t===236||t===237||t===240||t===242||t===243||t>=247&&t<=250||t===252||t===254||t===257||t===273||t===275||t===283||t===294||t===295||t===299||t>=305&&t<=307||t===312||t>=319&&t<=322||t===324||t>=328&&t<=331||t===333||t===338||t===339||t===358||t===359||t===363||t===462||t===464||t===466||t===468||t===470||t===472||t===474||t===476||t===593||t===609||t===708||t===711||t>=713&&t<=715||t===717||t===720||t>=728&&t<=731||t===733||t===735||t>=768&&t<=879||t>=913&&t<=929||t>=931&&t<=937||t>=945&&t<=961||t>=963&&t<=969||t===1025||t>=1040&&t<=1103||t===1105||t===8208||t>=8211&&t<=8214||t===8216||t===8217||t===8220||t===8221||t>=8224&&t<=8226||t>=8228&&t<=8231||t===8240||t===8242||t===8243||t===8245||t===8251||t===8254||t===8308||t===8319||t>=8321&&t<=8324||t===8364||t===8451||t===8453||t===8457||t===8467||t===8470||t===8481||t===8482||t===8486||t===8491||t===8531||t===8532||t>=8539&&t<=8542||t>=8544&&t<=8555||t>=8560&&t<=8569||t===8585||t>=8592&&t<=8601||t===8632||t===8633||t===8658||t===8660||t===8679||t===8704||t===8706||t===8707||t===8711||t===8712||t===8715||t===8719||t===8721||t===8725||t===8730||t>=8733&&t<=8736||t===8739||t===8741||t>=8743&&t<=8748||t===8750||t>=8756&&t<=8759||t===8764||t===8765||t===8776||t===8780||t===8786||t===8800||t===8801||t>=8804&&t<=8807||t===8810||t===8811||t===8814||t===8815||t===8834||t===8835||t===8838||t===8839||t===8853||t===8857||t===8869||t===8895||t===8978||t>=9312&&t<=9449||t>=9451&&t<=9547||t>=9552&&t<=9587||t>=9600&&t<=9615||t>=9618&&t<=9621||t===9632||t===9633||t>=9635&&t<=9641||t===9650||t===9651||t===9654||t===9655||t===9660||t===9661||t===9664||t===9665||t>=9670&&t<=9672||t===9675||t>=9678&&t<=9681||t>=9698&&t<=9701||t===9711||t===9733||t===9734||t===9737||t===9742||t===9743||t===9756||t===9758||t===9792||t===9794||t===9824||t===9825||t>=9827&&t<=9829||t>=9831&&t<=9834||t===9836||t===9837||t===9839||t===9886||t===9887||t===9919||t>=9926&&t<=9933||t>=9935&&t<=9939||t>=9941&&t<=9953||t===9955||t===9960||t===9961||t>=9963&&t<=9969||t===9972||t>=9974&&t<=9977||t===9979||t===9980||t===9982||t===9983||t===10045||t>=10102&&t<=10111||t>=11094&&t<=11097||t>=12872&&t<=12879||t>=57344&&t<=63743||t>=65024&&t<=65039||t===65533||t>=127232&&t<=127242||t>=127248&&t<=127277||t>=127280&&t<=127337||t>=127344&&t<=127373||t===127375||t===127376||t>=127387&&t<=127404||t>=917760&&t<=917999||t>=983040&&t<=1048573||t>=1048576&&t<=1114109}function Co(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function bo(t){return t>=4352&&t<=4447||t===8986||t===8987||t===9001||t===9002||t>=9193&&t<=9196||t===9200||t===9203||t===9725||t===9726||t===9748||t===9749||t>=9776&&t<=9783||t>=9800&&t<=9811||t===9855||t>=9866&&t<=9871||t===9875||t===9889||t===9898||t===9899||t===9917||t===9918||t===9924||t===9925||t===9934||t===9940||t===9962||t===9970||t===9971||t===9973||t===9978||t===9981||t===9989||t===9994||t===9995||t===10024||t===10060||t===10062||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t===11035||t===11036||t===11088||t===11093||t>=11904&&t<=11929||t>=11931&&t<=12019||t>=12032&&t<=12245||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12353&&t<=12438||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12773||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=42124||t>=42128&&t<=42182||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=94176&&t<=94180||t===94192||t===94193||t>=94208&&t<=100343||t>=100352&&t<=101589||t>=101631&&t<=101640||t>=110576&&t<=110579||t>=110581&&t<=110587||t===110589||t===110590||t>=110592&&t<=110882||t===110898||t>=110928&&t<=110930||t===110933||t>=110948&&t<=110951||t>=110960&&t<=111355||t>=119552&&t<=119638||t>=119648&&t<=119670||t===126980||t===127183||t===127374||t>=127377&&t<=127386||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t===127568||t===127569||t>=127584&&t<=127589||t>=127744&&t<=127776||t>=127789&&t<=127797||t>=127799&&t<=127868||t>=127870&&t<=127891||t>=127904&&t<=127946||t>=127951&&t<=127955||t>=127968&&t<=127984||t===127988||t>=127992&&t<=128062||t===128064||t>=128066&&t<=128252||t>=128255&&t<=128317||t>=128331&&t<=128334||t>=128336&&t<=128359||t===128378||t===128405||t===128406||t===128420||t>=128507&&t<=128591||t>=128640&&t<=128709||t===128716||t>=128720&&t<=128722||t>=128725&&t<=128727||t>=128732&&t<=128735||t===128747||t===128748||t>=128756&&t<=128764||t>=128992&&t<=129003||t===129008||t>=129292&&t<=129338||t>=129340&&t<=129349||t>=129351&&t<=129535||t>=129648&&t<=129660||t>=129664&&t<=129673||t>=129679&&t<=129734||t>=129742&&t<=129756||t>=129759&&t<=129769||t>=129776&&t<=129784||t>=131072&&t<=196605||t>=196608&&t<=262141}function Ao(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function To(t,{ambiguousAsWide:e=!1}={}){return Ao(t),Co(t)||bo(t)||e&&wo(t)?2:1}const ko=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE89\uDE8F-\uDEC2\uDEC6\uDECE-\uDEDC\uDEDF-\uDEE9]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g,Io=new Intl.Segmenter,$o=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Oo(t,e={}){if(typeof t!="string"||t.length===0)return 0;const{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=e;if(r||(t=we(t)),t.length===0)return 0;let i=0;const s={ambiguousAsWide:!n};for(const{segment:o}of Io.segment(t)){const a=o.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!$o.test(o)){if(ko().test(o)){i+=2;continue}i+=To(a,s)}}return i}function xo({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function Po(){const{env:t}=Y,{TERM:e,TERM_PROGRAM:n}=t;return Y.platform!=="win32"?e!=="linux":!!t.WT_SESSION||!!t.TERMINUS_SUBLIME||t.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||t.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const Ro=3;class No{#o=0;start(){this.#o++,this.#o===1&&this.#n()}stop(){if(this.#o<=0)throw new Error("`stop` called more times than `start`");this.#o--,this.#o===0&&this.#e()}#n(){Y.platform==="win32"||!Y.stdin.isTTY||(Y.stdin.setRawMode(!0),Y.stdin.on("data",this.#i),Y.stdin.resume())}#e(){Y.stdin.isTTY&&(Y.stdin.off("data",this.#i),Y.stdin.pause(),Y.stdin.setRawMode(!1))}#i(e){e[0]===Ro&&Y.emit("SIGINT")}}const un=new No;class Bo{#o=0;#n=!1;#e=0;#i=-1;#d=0;#t;#s;#r;#g;#p;#c;#l;#h;#m;#a;#u;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Y.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#p=this.#t.interval,this.#r=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:xo({stream:this.#r}),this.#l=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Y.env.NODE_ENV==="test"&&(this._stream=this.#r,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#o},set(n){this.#o=n}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#i}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#h}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#h=e,this.#f()}get interval(){return this.#p??this.#s.interval??100}get spinner(){return this.#s}set spinner(e){if(this.#i=-1,this.#p=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#s=e}else if(!Po())this.#s=He.line;else if(e===void 0)this.#s=He.dots;else if(e!=="default"&&He[e])this.#s=He[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#m}set text(e=""){this.#m=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#u}set suffixText(e=""){this.#u=e,this.#f()}get isSpinning(){return this.#g!==void 0}#D(e=this.#a,n=" "){return typeof e=="string"&&e!==""?e+n:typeof e=="function"?e()+n:""}#E(e=this.#u,n=" "){return typeof e=="string"&&e!==""?n+e:typeof e=="function"?n+e():""}#f(){const e=this.#r.columns??80,n=this.#D(this.#a,"-"),r=this.#E(this.#u,"-"),i=" ".repeat(this.#h)+n+"--"+this.#m+"--"+r;this.#e=0;for(const s of we(i).split(`
30
- `))this.#e+=Math.max(1,Math.ceil(Oo(s,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#c&&!this.#l}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=e}get isSilent(){return this.#l}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#l=e}frame(){const e=Date.now();(this.#i===-1||e-this.#d>=this.interval)&&(this.#i=++this.#i%this.#s.frames.length,this.#d=e);const{frames:n}=this.#s;let r=n[this.#i];this.color&&(r=wi[this.color](r));const i=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",s=typeof this.text=="string"?" "+this.text:"",o=typeof this.#u=="string"&&this.#u!==""?" "+this.#u:"";return i+r+s+o}clear(){if(!this.#c||!this.#r.isTTY)return this;this.#r.cursorTo(0);for(let e=0;e<this.#o;e++)e>0&&this.#r.moveCursor(0,-1),this.#r.clearLine(1);return(this.#h||this.lastIndent!==this.#h)&&this.#r.cursorTo(this.#h),this.lastIndent=this.#h,this.#o=0,this}render(){return this.#l?this:(this.clear(),this.#r.write(this.frame()),this.#o=this.#e,this)}start(e){return e&&(this.text=e),this.#l?this:this.#c?this.isSpinning?this:(this.#t.hideCursor&&Fe.hide(this.#r),this.#t.discardStdin&&Y.stdin.isTTY&&(this.#n=!0,un.start()),this.render(),this.#g=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#r.write(`- ${this.text}
31
- `),this)}stop(){return this.#c?(clearInterval(this.#g),this.#g=void 0,this.#i=0,this.clear(),this.#t.hideCursor&&Fe.show(this.#r),this.#t.discardStdin&&Y.stdin.isTTY&&this.#n&&(un.stop(),this.#n=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Ke.success,text:e})}fail(e){return this.stopAndPersist({symbol:Ke.error,text:e})}warn(e){return this.stopAndPersist({symbol:Ke.warning,text:e})}info(e){return this.stopAndPersist({symbol:Ke.info,text:e})}stopAndPersist(e={}){if(this.#l)return this;const n=e.prefixText??this.#a,r=this.#D(n," "),i=e.symbol??" ",s=e.text??this.text,a=typeof s=="string"?(i?" ":"")+s:"",l=e.suffixText??this.#u,g=this.#E(l," "),p=r+i+a+g+`
32
- `;return this.stop(),this.#r.write(p),this}}function Uo(t){return new Bo(t)}class ze{spinner;createSpinner(e){return this.spinner=Uo(e),this.spinner}success(e){try{this.spinner?this.spinner.succeed(D.chalk.green(e)):console.log(D.chalk.green("✓"),e)}catch{try{process.stdout?.write?.(`✓ ${e}
33
- `)}catch{}}}error(e){try{this.spinner?this.spinner.fail(D.chalk.red(e)):console.error(D.chalk.red("✗"),e)}catch{try{process.stderr?.write?.(`✗ ${e}
34
- `)}catch{}}}info(e){try{this.spinner?this.spinner.info(D.chalk.blue(e)):console.log(D.chalk.blue("ℹ"),e)}catch{try{process.stdout?.write?.(`ℹ ${e}
35
- `)}catch{}}}warn(e){try{this.spinner?this.spinner.warn(D.chalk.yellow(e)):console.warn(D.chalk.yellow("⚠"),e)}catch{try{process.stderr?.write?.(`⚠ ${e}
36
- `)}catch{}}}handleError(e){const n=e instanceof Error?e.message:String(e);this.error(n),process.env.DEBUG&&e instanceof Error&&(console.error(D.chalk.gray("Stack trace:")),console.error(D.chalk.gray(e.stack))),process.exit(1)}}const $={STATUS:"agent-status",RESIZE:"agent-pty-resize",DIRECT_CONTROL:"agent-direct-control",MESSAGE_INPUT:"agent-message-input",MESSAGE_OUTPUT:"agent-message-output",MESSAGE_OUTPUT_STARTED:"agent-message-output-started",MESSAGE_OUTPUT_ENDED:"agent-message-output-ended",MESSAGE_OUTPUT_PERMISSION_REQUESTED:"agent-message-output-permission-requested",MESSAGE_DELETED:"agent-message-deleted",MESSAGE_STDOUT:"agent-message-stdout",MESSAGE_STDIN:"agent-message-stdin",ERROR:"agent-error"},J={CLAUDE_CODE:"claude-code",GEMINI_CLI:"gemini-cli"},H={STARTING:"starting",IDLE:"idle",PAUSED:"paused",STOPPED:"stopped",ERROR:"error"},cn={STDOUT:"stdout",STDERR:"stderr"},B={STATUS:"daemon-status",ERROR:"daemon-error",TERMINATE:"daemon-terminate",LIST:"daemon-list-agent-sessions",START_AGENT:"daemon-start-agent",STOP_AGENT:"daemon-stop-agent"},De={STARTING:"starting",IDLE:"idle",BUSY:"busy",OFFLINE:"offline"},S={REQUEST:"request",RESPONSE:"response",ACK:"ack"};function y(t,e,n){function r(a,l){var g;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(g=a._zod).traits??(g.traits=new Set),a._zod.traits.add(t),e(a,l);for(const p in o.prototype)p in a||Object.defineProperty(a,p,{value:o.prototype[p].bind(a)});a._zod.constr=o,a._zod.def=l}const i=n?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function o(a){var l;const g=n?.Parent?new s:this;r(g,a),(l=g._zod).deferred??(l.deferred=[]);for(const p of g._zod.deferred)p();return g}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(o,"name",{value:t}),o}class Pe extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const zn={};function Ee(t){return zn}function zo(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function Mo(t,e){return typeof e=="bigint"?e.toString():e}function Mn(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function xt(t){return t==null}function Pt(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Go(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(t.toFixed(i).replace(".","")),o=Number.parseInt(e.toFixed(i).replace(".",""));return s%o/10**i}function K(t,e,n){Object.defineProperty(t,e,{get(){{const r=n();return t[e]=r,r}},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function Rt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function $e(t){return JSON.stringify(t)}const Gn=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function bt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Lo=Mn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function it(t){if(bt(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(bt(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const jo=new Set(["string","number","symbol"]);function Me(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function I(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Wo(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Zo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Vo(t,e){const n={},r=t._zod.def;for(const i in e){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&(n[i]=r.shape[i])}return be(t,{...t._zod.def,shape:n,checks:[]})}function Ho(t,e){const n={...t._zod.def.shape},r=t._zod.def;for(const i in e){if(!(i in r.shape))throw new Error(`Unrecognized key: "${i}"`);e[i]&&delete n[i]}return be(t,{...t._zod.def,shape:n,checks:[]})}function Ko(t,e){if(!it(e))throw new Error("Invalid input to extend: expected a plain object");const n={...t._zod.def,get shape(){const r={...t._zod.def.shape,...e};return Rt(this,"shape",r),r},checks:[]};return be(t,n)}function qo(t,e){return be(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Rt(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function Yo(t,e,n){const r=e._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)i[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return be(e,{...e._zod.def,shape:i,checks:[]})}function Jo(t,e,n){const r=e._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new t({type:"nonoptional",innerType:r[s]});return be(e,{...e._zod.def,shape:i,checks:[]})}function Oe(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Se(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function qe(t){return typeof t=="string"?t:t?.message}function ve(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const i=qe(t.inst?._zod.def?.error?.(t))??qe(e?.error?.(t))??qe(n.customError?.(t))??qe(n.localeError?.(t))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Nt(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Re(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const Ln=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Mo,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},jn=y("$ZodError",Ln),Wn=y("$ZodError",Ln,{Parent:Error});function Qo(t,e=n=>n.message){const n={},r=[];for(const i of t.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(e(i))):r.push(e(i));return{formErrors:r,fieldErrors:n}}function Xo(t,e){const n=e||function(s){return s.message},r={_errors:[]},i=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)r._errors.push(n(o));else{let a=r,l=0;for(;l<o.path.length;){const g=o.path[l];l===o.path.length-1?(a[g]=a[g]||{_errors:[]},a[g]._errors.push(n(o))):a[g]=a[g]||{_errors:[]},a=a[g],l++}}};return i(t),r}const ea=t=>(e,n,r,i)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new Pe;if(o.issues.length){const a=new(i?.Err??t)(o.issues.map(l=>ve(l,s,Ee())));throw Gn(a,i?.callee),a}return o.value},ta=t=>async(e,n,r,i)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(i?.Err??t)(o.issues.map(l=>ve(l,s,Ee())));throw Gn(a,i?.callee),a}return o.value},Zn=t=>(e,n,r)=>{const i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Pe;return s.issues.length?{success:!1,error:new(t??jn)(s.issues.map(o=>ve(o,i,Ee())))}:{success:!0,data:s.value}},na=Zn(Wn),Vn=t=>async(e,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=e._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>ve(o,i,Ee())))}:{success:!0,data:s.value}},ra=Vn(Wn),ia=/^[cC][^\s-]{8,}$/,sa=/^[0-9a-z]+$/,oa=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,aa=/^[0-9a-vA-V]{20}$/,ua=/^[A-Za-z0-9]{27}$/,ca=/^[a-zA-Z0-9_-]{21}$/,la=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ha=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ln=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,da=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ga="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fa(){return new RegExp(ga,"u")}const pa=/^(?:(?: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])$/,ma=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Da=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ea=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,va=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hn=/^[A-Za-z0-9_-]*$/,ya=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,_a=/^\+(?:[0-9]){6,14}[0-9]$/,Kn="(?:(?:\\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])))",Sa=new RegExp(`^${Kn}$`);function qn(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Fa(t){return new RegExp(`^${qn(t)}$`)}function wa(t){const e=qn({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Kn}T(?:${r})$`)}const Ca=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ba=/^\d+$/,Aa=/^-?\d+(?:\.\d+)?/i,Ta=/true|false/i,ka=/^[^A-Z]*$/,Ia=/^[^a-z]*$/,se=y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Yn={number:"number",bigint:"bigint",object:"date"},Jn=y("$ZodCheckLessThan",(t,e)=>{se.init(t,e);const n=Yn[typeof e.value];t._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Qn=y("$ZodCheckGreaterThan",(t,e)=>{se.init(t,e);const n=Yn[typeof e.value];t._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),$a=y("$ZodCheckMultipleOf",(t,e)=>{se.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Go(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),Oa=y("$ZodCheckNumberFormat",(t,e)=>{se.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[i,s]=Zo[e.format];t._zod.onattach.push(o=>{const a=o._zod.bag;a.format=e.format,a.minimum=i,a.maximum=s,n&&(a.pattern=ba)}),t._zod.check=o=>{const a=o.value;if(n){if(!Number.isInteger(a)){o.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),xa=y("$ZodCheckMaxLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!xt(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const i=r.value;if(i.length<=e.maximum)return;const o=Nt(i);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),Pa=y("$ZodCheckMinLength",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!xt(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const o=Nt(i);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),Ra=y("$ZodCheckLengthEquals",(t,e)=>{var n;se.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!xt(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=r=>{const i=r.value,s=i.length;if(s===e.length)return;const o=Nt(i),a=s>e.length;r.issues.push({origin:o,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),at=y("$ZodCheckStringFormat",(t,e)=>{var n,r;se.init(t,e),t._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Na=y("$ZodCheckRegex",(t,e)=>{at.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ba=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=ka),at.init(t,e)}),Ua=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ia),at.init(t,e)}),za=y("$ZodCheckIncludes",(t,e)=>{se.init(t,e);const n=Me(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),Ma=y("$ZodCheckStartsWith",(t,e)=>{se.init(t,e);const n=new RegExp(`^${Me(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Ga=y("$ZodCheckEndsWith",(t,e)=>{se.init(t,e);const n=new RegExp(`.*${Me(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),La=y("$ZodCheckOverwrite",(t,e)=>{se.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class ja{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(`
37
- `).filter(o=>o),i=Math.min(...r.map(o=>o.length-o.trimStart().length)),s=r.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,n=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,i.join(`
38
- `))}}const Wa={major:4,minor:0,patch:0},Z=y("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Wa;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const i of r)for(const s of i._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const i=(s,o,a)=>{let l=Oe(s),g;for(const p of o){if(p._zod.def.when){if(!p._zod.def.when(s))continue}else if(l)continue;const E=s.issues.length,m=p._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new Pe;if(g||m instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await m,s.issues.length!==E&&(l||(l=Oe(s,E)))});else{if(s.issues.length===E)continue;l||(l=Oe(s,E))}}return g?g.then(()=>s):s};t._zod.run=(s,o)=>{const a=t._zod.parse(s,o);if(a instanceof Promise){if(o.async===!1)throw new Pe;return a.then(l=>i(l,r,o))}return i(a,r,o)}}t["~standard"]={validate:i=>{try{const s=na(t,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ra(t,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Bt=y("$ZodString",(t,e)=>{Z.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ca(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),q=y("$ZodStringFormat",(t,e)=>{at.init(t,e),Bt.init(t,e)}),Za=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ha),q.init(t,e)}),Va=y("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ln(r))}else e.pattern??(e.pattern=ln());q.init(t,e)}),Ha=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=da),q.init(t,e)}),Ka=y("$ZodURL",(t,e)=>{q.init(t,e),t._zod.check=n=>{try{const r=n.value,i=new URL(r),s=i.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ya.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),qa=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=fa()),q.init(t,e)}),Ya=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ca),q.init(t,e)}),Ja=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ia),q.init(t,e)}),Qa=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sa),q.init(t,e)}),Xa=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=oa),q.init(t,e)}),eu=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=aa),q.init(t,e)}),tu=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ua),q.init(t,e)}),nu=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=wa(e)),q.init(t,e)}),ru=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sa),q.init(t,e)}),iu=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Fa(e)),q.init(t,e)}),su=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=la),q.init(t,e)}),ou=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=pa),q.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),au=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ma),q.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),uu=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Da),q.init(t,e)}),cu=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ea),q.init(t,e),t._zod.check=n=>{const[r,i]=n.value.split("/");try{if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Xn(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const lu=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=va),q.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Xn(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function hu(t){if(!Hn.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Xn(n)}const du=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Hn),q.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{hu(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),gu=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=_a),q.init(t,e)});function fu(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const pu=y("$ZodJWT",(t,e)=>{q.init(t,e),t._zod.check=n=>{fu(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),er=y("$ZodNumber",(t,e)=>{Z.init(t,e),t._zod.pattern=t._zod.bag.pattern??Aa,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),n}}),mu=y("$ZodNumber",(t,e)=>{Oa.init(t,e),er.init(t,e)}),Du=y("$ZodBoolean",(t,e)=>{Z.init(t,e),t._zod.pattern=Ta,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),n}}),Eu=y("$ZodAny",(t,e)=>{Z.init(t,e),t._zod.parse=n=>n}),vu=y("$ZodUnknown",(t,e)=>{Z.init(t,e),t._zod.parse=n=>n}),yu=y("$ZodNever",(t,e)=>{Z.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function hn(t,e,n){t.issues.length&&e.issues.push(...Se(n,t.issues)),e.value[n]=t.value}const _u=y("$ZodArray",(t,e)=>{Z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const s=[];for(let o=0;o<i.length;o++){const a=i[o],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?s.push(l.then(g=>hn(g,n,o))):hn(l,n,o)}return s.length?Promise.all(s).then(()=>n):n}});function Ye(t,e,n){t.issues.length&&e.issues.push(...Se(n,t.issues)),e.value[n]=t.value}function dn(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Se(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const Su=y("$ZodObject",(t,e)=>{Z.init(t,e);const n=Mn(()=>{const E=Object.keys(e.shape);for(const F of E)if(!(e.shape[F]instanceof Z))throw new Error(`Invalid element at key "${F}": expected a Zod schema`);const m=Wo(e.shape);return{shape:e.shape,keys:E,keySet:new Set(E),numKeys:E.length,optionalKeys:new Set(m)}});K(t._zod,"propValues",()=>{const E=e.shape,m={};for(const F in E){const k=E[F]._zod;if(k.values){m[F]??(m[F]=new Set);for(const u of k.values)m[F].add(u)}}return m});const r=E=>{const m=new ja(["shape","payload","ctx"]),F=n.value,k=d=>{const f=$e(d);return`shape[${f}]._zod.run({ value: input[${f}], issues: [] }, ctx)`};m.write("const input = payload.value;");const u=Object.create(null);let c=0;for(const d of F.keys)u[d]=`key_${c++}`;m.write("const newResult = {}");for(const d of F.keys)if(F.optionalKeys.has(d)){const f=u[d];m.write(`const ${f} = ${k(d)};`);const _=$e(d);m.write(`
39
- if (${f}.issues.length) {
40
- if (input[${_}] === undefined) {
41
- if (${_} in input) {
42
- newResult[${_}] = undefined;
43
- }
44
- } else {
45
- payload.issues = payload.issues.concat(
46
- ${f}.issues.map((iss) => ({
47
- ...iss,
48
- path: iss.path ? [${_}, ...iss.path] : [${_}],
49
- }))
50
- );
51
- }
52
- } else if (${f}.value === undefined) {
53
- if (${_} in input) newResult[${_}] = undefined;
54
- } else {
55
- newResult[${_}] = ${f}.value;
56
- }
57
- `)}else{const f=u[d];m.write(`const ${f} = ${k(d)};`),m.write(`
58
- if (${f}.issues.length) payload.issues = payload.issues.concat(${f}.issues.map(iss => ({
59
- ...iss,
60
- path: iss.path ? [${$e(d)}, ...iss.path] : [${$e(d)}]
61
- })));`),m.write(`newResult[${$e(d)}] = ${f}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");const h=m.compile();return(d,f)=>h(E,d,f)};let i;const s=bt,o=!zn.jitless,l=o&&Lo.value,g=e.catchall;let p;t._zod.parse=(E,m)=>{p??(p=n.value);const F=E.value;if(!s(F))return E.issues.push({expected:"object",code:"invalid_type",input:F,inst:t}),E;const k=[];if(o&&l&&m?.async===!1&&m.jitless!==!0)i||(i=r(e.shape)),E=i(E,m);else{E.value={};const f=p.shape;for(const _ of p.keys){const O=f[_],A=O._zod.run({value:F[_],issues:[]},m),x=O._zod.optin==="optional"&&O._zod.optout==="optional";A instanceof Promise?k.push(A.then(P=>x?dn(P,E,_,F):Ye(P,E,_))):x?dn(A,E,_,F):Ye(A,E,_)}}if(!g)return k.length?Promise.all(k).then(()=>E):E;const u=[],c=p.keySet,h=g._zod,d=h.def.type;for(const f of Object.keys(F)){if(c.has(f))continue;if(d==="never"){u.push(f);continue}const _=h.run({value:F[f],issues:[]},m);_ instanceof Promise?k.push(_.then(O=>Ye(O,E,f))):Ye(_,E,f)}return u.length&&E.issues.push({code:"unrecognized_keys",keys:u,input:F,inst:t}),k.length?Promise.all(k).then(()=>E):E}});function gn(t,e,n,r){for(const i of t)if(i.issues.length===0)return e.value=i.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(i=>i.issues.map(s=>ve(s,r,Ee())))}),e}const Fu=y("$ZodUnion",(t,e)=>{Z.init(t,e),K(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),K(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),K(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),K(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){const n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Pt(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let i=!1;const s=[];for(const o of e.options){const a=o._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)s.push(a),i=!0;else{if(a.issues.length===0)return a;s.push(a)}}return i?Promise.all(s).then(o=>gn(o,n,t,r)):gn(s,n,t,r)}}),wu=y("$ZodIntersection",(t,e)=>{Z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value,s=e.left._zod.run({value:i,issues:[]},r),o=e.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,g])=>fn(n,l,g)):fn(n,s,o)}});function At(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(it(t)&&it(e)){const n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(const s of r){const o=At(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r],o=At(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function fn(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Oe(t))return t;const r=At(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}const Cu=y("$ZodRecord",(t,e)=>{Z.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!it(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;n.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const g=e.valueType._zod.run({value:i[l],issues:[]},r);g instanceof Promise?s.push(g.then(p=>{p.issues.length&&n.issues.push(...Se(l,p.issues)),n.value[l]=p.value})):(g.issues.length&&n.issues.push(...Se(l,g.issues)),n.value[l]=g.value)}let a;for(const l in i)o.has(l)||(a=a??[],a.push(l));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:a})}else{n.value={};for(const o of Reflect.ownKeys(i)){if(o==="__proto__")continue;const a=e.keyType._zod.run({value:o,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(g=>ve(g,r,Ee())),input:o,path:[o],inst:t}),n.value[a.value]=a.value;continue}const l=e.valueType._zod.run({value:i[o],issues:[]},r);l instanceof Promise?s.push(l.then(g=>{g.issues.length&&n.issues.push(...Se(o,g.issues)),n.value[a.value]=g.value})):(l.issues.length&&n.issues.push(...Se(o,l.issues)),n.value[a.value]=l.value)}}return s.length?Promise.all(s).then(()=>n):n}}),bu=y("$ZodEnum",(t,e)=>{Z.init(t,e);const n=zo(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>jo.has(typeof r)).map(r=>typeof r=="string"?Me(r):r.toString()).join("|")})$`),t._zod.parse=(r,i)=>{const s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),Au=y("$ZodLiteral",(t,e)=>{Z.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Me(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const i=n.value;return t._zod.values.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}}),Tu=y("$ZodTransform",(t,e)=>{Z.init(t,e),t._zod.parse=(n,r)=>{const i=e.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(n.value=o,n));if(i instanceof Promise)throw new Pe;return n.value=i,n}}),ku=y("$ZodOptional",(t,e)=>{Z.init(t,e),t._zod.optin="optional",t._zod.optout="optional",K(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),K(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Pt(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),Iu=y("$ZodNullable",(t,e)=>{Z.init(t,e),K(t._zod,"optin",()=>e.innerType._zod.optin),K(t._zod,"optout",()=>e.innerType._zod.optout),K(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${Pt(n.source)}|null)$`):void 0}),K(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),$u=y("$ZodDefault",(t,e)=>{Z.init(t,e),t._zod.optin="optional",K(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>pn(s,e)):pn(i,e)}});function pn(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Ou=y("$ZodPrefault",(t,e)=>{Z.init(t,e),t._zod.optin="optional",K(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),xu=y("$ZodNonOptional",(t,e)=>{Z.init(t,e),K(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>mn(s,t)):mn(i,t)}});function mn(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const Pu=y("$ZodCatch",(t,e)=>{Z.init(t,e),t._zod.optin="optional",K(t._zod,"optout",()=>e.innerType._zod.optout),K(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(o=>ve(o,r,Ee()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>ve(s,r,Ee()))},input:n.value}),n.issues=[]),n)}}),Ru=y("$ZodPipe",(t,e)=>{Z.init(t,e),K(t._zod,"values",()=>e.in._zod.values),K(t._zod,"optin",()=>e.in._zod.optin),K(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{const i=e.in._zod.run(n,r);return i instanceof Promise?i.then(s=>Dn(s,e,r)):Dn(i,e,r)}});function Dn(t,e,n){return Oe(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}const Nu=y("$ZodReadonly",(t,e)=>{Z.init(t,e),K(t._zod,"propValues",()=>e.innerType._zod.propValues),K(t._zod,"values",()=>e.innerType._zod.values),K(t._zod,"optin",()=>e.innerType._zod.optin),K(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(En):En(i)}});function En(t){return t.value=Object.freeze(t.value),t}const Bu=y("$ZodCustom",(t,e)=>{se.init(t,e),Z.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,i=e.fn(r);if(i instanceof Promise)return i.then(s=>vn(s,n,r,t));vn(i,n,r,t)}});function vn(t,e,n,r){if(!t){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(Re(i))}}class Uu{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){const r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function zu(){return new Uu}const Je=zu();function Mu(t,e){return new t({type:"string",...I(e)})}function Gu(t,e){return new t({type:"string",coerce:!0,...I(e)})}function Lu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function yn(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...I(e)})}function ju(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...I(e)})}function Wu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function Zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function Vu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Hu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Ku(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function qu(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function Yu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Ju(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Qu(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Xu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function ec(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function tc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function nc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function rc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function ic(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...I(e)})}function sc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...I(e)})}function oc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function ac(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function uc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function cc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function lc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function hc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function dc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function gc(t,e){return new t({type:"number",checks:[],...I(e)})}function fc(t,e){return new t({type:"number",coerce:!0,checks:[],...I(e)})}function pc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function mc(t,e){return new t({type:"boolean",...I(e)})}function Dc(t){return new t({type:"any"})}function Ec(t){return new t({type:"unknown"})}function vc(t,e){return new t({type:"never",...I(e)})}function _n(t,e){return new Jn({check:"less_than",...I(e),value:t,inclusive:!1})}function yt(t,e){return new Jn({check:"less_than",...I(e),value:t,inclusive:!0})}function Sn(t,e){return new Qn({check:"greater_than",...I(e),value:t,inclusive:!1})}function _t(t,e){return new Qn({check:"greater_than",...I(e),value:t,inclusive:!0})}function Fn(t,e){return new $a({check:"multiple_of",...I(e),value:t})}function tr(t,e){return new xa({check:"max_length",...I(e),maximum:t})}function st(t,e){return new Pa({check:"min_length",...I(e),minimum:t})}function nr(t,e){return new Ra({check:"length_equals",...I(e),length:t})}function yc(t,e){return new Na({check:"string_format",format:"regex",...I(e),pattern:t})}function _c(t){return new Ba({check:"string_format",format:"lowercase",...I(t)})}function Sc(t){return new Ua({check:"string_format",format:"uppercase",...I(t)})}function Fc(t,e){return new za({check:"string_format",format:"includes",...I(e),includes:t})}function wc(t,e){return new Ma({check:"string_format",format:"starts_with",...I(e),prefix:t})}function Cc(t,e){return new Ga({check:"string_format",format:"ends_with",...I(e),suffix:t})}function Ge(t){return new La({check:"overwrite",tx:t})}function bc(t){return Ge(e=>e.normalize(t))}function Ac(){return Ge(t=>t.trim())}function Tc(){return Ge(t=>t.toLowerCase())}function kc(){return Ge(t=>t.toUpperCase())}function Ic(t,e,n){return new t({type:"array",element:e,...I(n)})}function $c(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}const Oc=y("ZodISODateTime",(t,e)=>{nu.init(t,e),X.init(t,e)});function xc(t){return cc(Oc,t)}const Pc=y("ZodISODate",(t,e)=>{ru.init(t,e),X.init(t,e)});function Rc(t){return lc(Pc,t)}const Nc=y("ZodISOTime",(t,e)=>{iu.init(t,e),X.init(t,e)});function Bc(t){return hc(Nc,t)}const Uc=y("ZodISODuration",(t,e)=>{su.init(t,e),X.init(t,e)});function zc(t){return dc(Uc,t)}const Mc=(t,e)=>{jn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Xo(t,n)},flatten:{value:n=>Qo(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},ut=y("ZodError",Mc,{Parent:Error}),Gc=ea(ut),Lc=ta(ut),jc=Zn(ut),Wc=Vn(ut),Q=y("ZodType",(t,e)=>(Z.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>be(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>Gc(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>jc(t,n,r),t.parseAsync=async(n,r)=>Lc(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Wc(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(Nl(n,r)),t.superRefine=n=>t.check(Bl(n)),t.overwrite=n=>t.check(Ge(n)),t.optional=()=>bn(t),t.nullable=()=>An(t),t.nullish=()=>bn(An(t)),t.nonoptional=n=>Tl(t,n),t.array=()=>Ce(t),t.or=n=>ct([t,n]),t.and=n=>El(t,n),t.transform=n=>Tn(t,Sl(n)),t.default=n=>Cl(t,n),t.prefault=n=>Al(t,n),t.catch=n=>Il(t,n),t.pipe=n=>Tn(t,n),t.readonly=()=>xl(t),t.describe=n=>{const r=t.clone();return Je.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Je.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Je.get(t);const r=t.clone();return Je.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),rr=y("_ZodString",(t,e)=>{Bt.init(t,e),Q.init(t,e);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(yc(...r)),t.includes=(...r)=>t.check(Fc(...r)),t.startsWith=(...r)=>t.check(wc(...r)),t.endsWith=(...r)=>t.check(Cc(...r)),t.min=(...r)=>t.check(st(...r)),t.max=(...r)=>t.check(tr(...r)),t.length=(...r)=>t.check(nr(...r)),t.nonempty=(...r)=>t.check(st(1,...r)),t.lowercase=r=>t.check(_c(r)),t.uppercase=r=>t.check(Sc(r)),t.trim=()=>t.check(Ac()),t.normalize=(...r)=>t.check(bc(...r)),t.toLowerCase=()=>t.check(Tc()),t.toUpperCase=()=>t.check(kc())}),ir=y("ZodString",(t,e)=>{Bt.init(t,e),rr.init(t,e),t.email=n=>t.check(Lu(Zc,n)),t.url=n=>t.check(Hu(Vc,n)),t.jwt=n=>t.check(uc(al,n)),t.emoji=n=>t.check(Ku(Hc,n)),t.guid=n=>t.check(yn(wn,n)),t.uuid=n=>t.check(ju(Qe,n)),t.uuidv4=n=>t.check(Wu(Qe,n)),t.uuidv6=n=>t.check(Zu(Qe,n)),t.uuidv7=n=>t.check(Vu(Qe,n)),t.nanoid=n=>t.check(qu(Kc,n)),t.guid=n=>t.check(yn(wn,n)),t.cuid=n=>t.check(Yu(qc,n)),t.cuid2=n=>t.check(Ju(Yc,n)),t.ulid=n=>t.check(Qu(Jc,n)),t.base64=n=>t.check(sc(il,n)),t.base64url=n=>t.check(oc(sl,n)),t.xid=n=>t.check(Xu(Qc,n)),t.ksuid=n=>t.check(ec(Xc,n)),t.ipv4=n=>t.check(tc(el,n)),t.ipv6=n=>t.check(nc(tl,n)),t.cidrv4=n=>t.check(rc(nl,n)),t.cidrv6=n=>t.check(ic(rl,n)),t.e164=n=>t.check(ac(ol,n)),t.datetime=n=>t.check(xc(n)),t.date=n=>t.check(Rc(n)),t.time=n=>t.check(Bc(n)),t.duration=n=>t.check(zc(n))});function v(t){return Mu(ir,t)}const X=y("ZodStringFormat",(t,e)=>{q.init(t,e),rr.init(t,e)}),Zc=y("ZodEmail",(t,e)=>{Ha.init(t,e),X.init(t,e)}),wn=y("ZodGUID",(t,e)=>{Za.init(t,e),X.init(t,e)}),Qe=y("ZodUUID",(t,e)=>{Va.init(t,e),X.init(t,e)}),Vc=y("ZodURL",(t,e)=>{Ka.init(t,e),X.init(t,e)}),Hc=y("ZodEmoji",(t,e)=>{qa.init(t,e),X.init(t,e)}),Kc=y("ZodNanoID",(t,e)=>{Ya.init(t,e),X.init(t,e)}),qc=y("ZodCUID",(t,e)=>{Ja.init(t,e),X.init(t,e)}),Yc=y("ZodCUID2",(t,e)=>{Qa.init(t,e),X.init(t,e)}),Jc=y("ZodULID",(t,e)=>{Xa.init(t,e),X.init(t,e)}),Qc=y("ZodXID",(t,e)=>{eu.init(t,e),X.init(t,e)}),Xc=y("ZodKSUID",(t,e)=>{tu.init(t,e),X.init(t,e)}),el=y("ZodIPv4",(t,e)=>{ou.init(t,e),X.init(t,e)}),tl=y("ZodIPv6",(t,e)=>{au.init(t,e),X.init(t,e)}),nl=y("ZodCIDRv4",(t,e)=>{uu.init(t,e),X.init(t,e)}),rl=y("ZodCIDRv6",(t,e)=>{cu.init(t,e),X.init(t,e)}),il=y("ZodBase64",(t,e)=>{lu.init(t,e),X.init(t,e)}),sl=y("ZodBase64URL",(t,e)=>{du.init(t,e),X.init(t,e)}),ol=y("ZodE164",(t,e)=>{gu.init(t,e),X.init(t,e)}),al=y("ZodJWT",(t,e)=>{pu.init(t,e),X.init(t,e)}),Ut=y("ZodNumber",(t,e)=>{er.init(t,e),Q.init(t,e),t.gt=(r,i)=>t.check(Sn(r,i)),t.gte=(r,i)=>t.check(_t(r,i)),t.min=(r,i)=>t.check(_t(r,i)),t.lt=(r,i)=>t.check(_n(r,i)),t.lte=(r,i)=>t.check(yt(r,i)),t.max=(r,i)=>t.check(yt(r,i)),t.int=r=>t.check(Cn(r)),t.safe=r=>t.check(Cn(r)),t.positive=r=>t.check(Sn(0,r)),t.nonnegative=r=>t.check(_t(0,r)),t.negative=r=>t.check(_n(0,r)),t.nonpositive=r=>t.check(yt(0,r)),t.multipleOf=(r,i)=>t.check(Fn(r,i)),t.step=(r,i)=>t.check(Fn(r,i)),t.finite=()=>t;const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function re(t){return gc(Ut,t)}const ul=y("ZodNumberFormat",(t,e)=>{mu.init(t,e),Ut.init(t,e)});function Cn(t){return pc(ul,t)}const cl=y("ZodBoolean",(t,e)=>{Du.init(t,e),Q.init(t,e)});function Ae(t){return mc(cl,t)}const ll=y("ZodAny",(t,e)=>{Eu.init(t,e),Q.init(t,e)});function he(){return Dc(ll)}const hl=y("ZodUnknown",(t,e)=>{vu.init(t,e),Q.init(t,e)});function Ne(){return Ec(hl)}const dl=y("ZodNever",(t,e)=>{yu.init(t,e),Q.init(t,e)});function gl(t){return vc(dl,t)}const fl=y("ZodArray",(t,e)=>{_u.init(t,e),Q.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(st(n,r)),t.nonempty=n=>t.check(st(1,n)),t.max=(n,r)=>t.check(tr(n,r)),t.length=(n,r)=>t.check(nr(n,r)),t.unwrap=()=>t.element});function Ce(t,e){return Ic(fl,t,e)}const pl=y("ZodObject",(t,e)=>{Su.init(t,e),Q.init(t,e),K(t,"shape",()=>e.shape),t.keyof=()=>ne(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ne()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ne()}),t.strict=()=>t.clone({...t._zod.def,catchall:gl()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ko(t,n),t.merge=n=>qo(t,n),t.pick=n=>Vo(t,n),t.omit=n=>Ho(t,n),t.partial=(...n)=>Yo(sr,t,n[0]),t.required=(...n)=>Jo(or,t,n[0])});function me(t,e){const n={type:"object",get shape(){return Rt(this,"shape",{...t}),this.shape},...I(e)};return new pl(n)}const ml=y("ZodUnion",(t,e)=>{Fu.init(t,e),Q.init(t,e),t.options=e.options});function ct(t,e){return new ml({type:"union",options:t,...I(e)})}const Dl=y("ZodIntersection",(t,e)=>{wu.init(t,e),Q.init(t,e)});function El(t,e){return new Dl({type:"intersection",left:t,right:e})}const vl=y("ZodRecord",(t,e)=>{Cu.init(t,e),Q.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function lt(t,e,n){return new vl({type:"record",keyType:t,valueType:e,...I(n)})}const Tt=y("ZodEnum",(t,e)=>{bu.init(t,e),Q.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,i)=>{const s={};for(const o of r)if(n.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Tt({...e,checks:[],...I(i),entries:s})},t.exclude=(r,i)=>{const s={...e.entries};for(const o of r)if(n.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Tt({...e,checks:[],...I(i),entries:s})}});function ne(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new Tt({type:"enum",entries:n,...I(e)})}const yl=y("ZodLiteral",(t,e)=>{Au.init(t,e),Q.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function b(t,e){return new yl({type:"literal",values:Array.isArray(t)?t:[t],...I(e)})}const _l=y("ZodTransform",(t,e)=>{Tu.init(t,e),Q.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(Re(s,n.value,e));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!0),n.issues.push(Re(o))}};const i=e.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function Sl(t){return new _l({type:"transform",transform:t})}const sr=y("ZodOptional",(t,e)=>{ku.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bn(t){return new sr({type:"optional",innerType:t})}const Fl=y("ZodNullable",(t,e)=>{Iu.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType});function An(t){return new Fl({type:"nullable",innerType:t})}const wl=y("ZodDefault",(t,e)=>{$u.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Cl(t,e){return new wl({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const bl=y("ZodPrefault",(t,e)=>{Ou.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Al(t,e){return new bl({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const or=y("ZodNonOptional",(t,e)=>{xu.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Tl(t,e){return new or({type:"nonoptional",innerType:t,...I(e)})}const kl=y("ZodCatch",(t,e)=>{Pu.init(t,e),Q.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Il(t,e){return new kl({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const $l=y("ZodPipe",(t,e)=>{Ru.init(t,e),Q.init(t,e),t.in=e.in,t.out=e.out});function Tn(t,e){return new $l({type:"pipe",in:t,out:e})}const Ol=y("ZodReadonly",(t,e)=>{Nu.init(t,e),Q.init(t,e)});function xl(t){return new Ol({type:"readonly",innerType:t})}const Pl=y("ZodCustom",(t,e)=>{Bu.init(t,e),Q.init(t,e)});function Rl(t){const e=new se({check:"custom"});return e._zod.check=t,e}function Nl(t,e={}){return $c(Pl,t,e)}function Bl(t){const e=Rl(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Re(r,n.value,e._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!e._zod.def.abort),n.issues.push(Re(i))}},t(n.value,n)));return e}function kn(t){return Gu(ir,t)}function In(t){return fc(Ut,t)}const N=me({eventType:v(),command:v(),payload:me({sessionId:v(),timestamp:re().default(()=>Date.now())})}),Ul=ne([H.STARTING,H.IDLE,H.PAUSED,H.STOPPED,H.ERROR]),zl=ne([J.CLAUDE_CODE,J.GEMINI_CLI]),Ml=ne([cn.STDOUT,cn.STDERR]),ar=N.extend({eventType:b($.STATUS).default($.STATUS),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default(""),fullscreen:Ae().default(!1).optional()})}),ur=N.extend({eventType:b($.RESIZE).default($.RESIZE),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default(""),cols:In(),rows:In()})}),cr=N.extend({eventType:b($.DIRECT_CONTROL).default($.DIRECT_CONTROL),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v(),controlType:ne(["interrupt","cancel","eof","signal"]).default("interrupt"),metadata:lt(v(),he()).optional()})}),kt=N.extend({eventType:b($.STATUS).default($.STATUS),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),status:Ul.default(H.IDLE),agentType:zl.optional(),pid:re().optional(),version:v().optional(),capabilities:Ce(v()).optional(),message:v().optional()})}),lr=N.extend({eventType:b($.MESSAGE_INPUT).default($.MESSAGE_INPUT),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:kn(),messageId:v(),content:kn(),metadata:lt(v(),he()).optional()})}),Gl=N.extend({eventType:b($.MESSAGE_INPUT).default($.MESSAGE_INPUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),id:v(),sessionId:v(),memberId:v().nullable().optional(),messageType:ne(["input","output","error","system"]),content:v(),contentSize:re().nullable(),messageTimestamp:v(),metadata:he().nullable(),createdAt:v(),updatedAt:v()})}),Ll=N.extend({eventType:b($.MESSAGE_OUTPUT).default($.MESSAGE_OUTPUT),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default("")})}),hr=N.extend({eventType:b($.MESSAGE_OUTPUT).default($.MESSAGE_OUTPUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),id:v(),messageId:v(),memberId:v().nullable().optional(),messageType:ne(["input","output","error","system"]),parts:Ce(Ne()).default([]),contentSize:re().nullable(),messageTimestamp:v(),stream:Ml.optional(),isComplete:Ae().optional().default(!1),metadata:he().nullable(),createdAt:v(),updatedAt:v()})}),jl=N.extend({eventType:b($.MESSAGE_OUTPUT_PERMISSION_REQUESTED).default($.MESSAGE_OUTPUT_PERMISSION_REQUESTED),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default(""),messageId:v(),toolName:v(),description:v(),metadata:lt(v(),he()).optional()})}),dr=N.extend({eventType:b($.MESSAGE_STDIN).default($.MESSAGE_STDIN),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default("")})}),gr=N.extend({eventType:b($.MESSAGE_STDOUT).default($.MESSAGE_STDOUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default("")})}),Wl=N.extend({eventType:b($.MESSAGE_OUTPUT_STARTED).default($.MESSAGE_OUTPUT_STARTED),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),id:v(),messageId:v(),memberId:v().nullable().optional(),messageType:ne(["input","output","error","system"]),parts:Ce(Ne()).default([]),contentSize:re().nullable(),messageTimestamp:v(),metadata:he().nullable(),createdAt:v(),updatedAt:v()})}),Zl=N.extend({eventType:b($.MESSAGE_OUTPUT_ENDED).default($.MESSAGE_OUTPUT_ENDED),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),id:v(),messageId:v(),memberId:v().nullable().optional(),messageType:ne(["input","output","error","system"]),parts:Ce(Ne()),contentSize:re().nullable(),messageTimestamp:v(),totalTokens:re().optional(),completionTime:re().optional(),metadata:he().nullable(),createdAt:v(),updatedAt:v()})}),Vl=N.extend({eventType:b($.MESSAGE_DELETED).default($.MESSAGE_DELETED),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),id:v()})}),Hl=N.extend({eventType:b($.ERROR).default($.ERROR),command:b(S.REQUEST).default(S.REQUEST),payload:N.shape.payload.extend({data:v().default("")})}),fr=N.extend({eventType:b($.ERROR).default($.ERROR),command:b(S.RESPONSE).default(S.RESPONSE),payload:N.shape.payload.extend({data:v().default(""),error:me({code:v().default("UNKNOWN_ERROR"),message:v().default("An unknown error occurred"),details:he().optional(),stack:v().optional()})})}),Kl=N.extend({eventType:b($.STATUS).default($.STATUS),command:b(S.ACK).default(S.ACK),payload:N.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),ql=N.extend({eventType:b($.MESSAGE_INPUT).default($.MESSAGE_INPUT),command:b(S.ACK).default(S.ACK),payload:N.shape.payload.extend({data:v().default(""),messageId:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Yl=N.extend({eventType:b($.MESSAGE_OUTPUT).default($.MESSAGE_OUTPUT),command:b(S.ACK).default(S.ACK),payload:N.shape.payload.extend({data:v().default(""),messageId:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Jl=N.extend({eventType:b($.MESSAGE_DELETED).default($.MESSAGE_DELETED),command:b(S.ACK).default(S.ACK),payload:N.shape.payload.extend({data:v().default(""),id:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Ql=N.extend({eventType:b($.ERROR).default($.ERROR),command:b(S.ACK).default(S.ACK),payload:N.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})});ct([ar,ur,cr,kt,lr,Gl,Ll,hr,jl,dr,gr,Wl,Zl,Vl,Hl,fr,Kl,ql,Yl,Jl,Ql]);const U=me({eventType:v(),command:v(),payload:me({sessionId:v(),timestamp:re().default(()=>Date.now())})}),Xl=ne([De.IDLE,De.BUSY,De.OFFLINE,De.STARTING]),pr=U.extend({eventType:b(B.STATUS).default(B.STATUS),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default("")})}),It=U.extend({eventType:b(B.STATUS).default(B.STATUS),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),status:Xl.default(De.IDLE)})}),eh=U.extend({eventType:b(B.ERROR).default(B.ERROR),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default("")})}),mr=U.extend({eventType:b(B.ERROR).default(B.ERROR),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),error:me({code:v().default("UNKNOWN_ERROR"),message:v().default("An unknown error occurred"),details:he().optional()})})}),Dr=U.extend({eventType:b(B.TERMINATE).default(B.TERMINATE),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().optional().default("")})}),Er=U.extend({eventType:b(B.TERMINATE).default(B.TERMINATE),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().optional().default("")})}),vr=U.extend({eventType:b(B.LIST).default(B.LIST),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().optional().default("")})}),yr=U.extend({eventType:b(B.LIST).default(B.LIST),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().optional().default("")})}),zt=U.extend({eventType:b(B.START_AGENT).default(B.START_AGENT),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default(""),agentType:v(),agentSessionId:v(),agentConfig:me({conversationSessionId:v().optional(),workingDirectory:v().nullable(),environment:lt(v(),v()).optional(),args:Ce(v()).optional(),commands:Ce(v()).optional(),mcps:he().optional(),hooks:he().optional(),xterm:Ae().optional().default(!1),docker:Ae().optional().default(!1),dockerImage:v().optional(),autonomous:Ae().optional().default(!1),worktree:ct([Ae(),me({branch:v().optional(),name:v().optional()})]).optional().default(!1),sessionAlias:v().optional(),llmConfig:me({provider:v(),model:v().optional(),apiKey:v().optional(),endpoint:v().optional()}).optional()}).optional()})}),th=U.extend({eventType:b(B.START_AGENT).default(B.START_AGENT),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),agentSessionId:v(),agentType:v(),status:ne(["started","failed"]).default("started"),message:v().optional()})}),nh=U.extend({eventType:b(B.START_AGENT).default(B.START_AGENT),command:b(S.ACK).default(S.ACK),payload:U.shape.payload.extend({data:v().default(""),agentType:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),daemonsSent:re().default(0)})}),_r=U.extend({eventType:b(B.STOP_AGENT).default(B.STOP_AGENT),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default(""),agentSessionId:v()})}),Sr=U.extend({eventType:b(B.STOP_AGENT).default(B.STOP_AGENT),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),agentSessionId:v(),status:ne(["stopped","not_found","failed"]).default("stopped"),message:v().optional()})}),rh=U.extend({eventType:b(B.STOP_AGENT).default(B.STOP_AGENT),command:b(S.ACK).default(S.ACK),payload:U.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),daemonsSent:re().default(0)})}),ih=U.extend({eventType:b(B.TERMINATE).default(B.TERMINATE),command:b(S.ACK).default(S.ACK),payload:U.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),daemonsSent:re().default(0)})}),sh=U.extend({eventType:b(B.LIST).default(B.LIST),command:b(S.ACK).default(S.ACK),payload:U.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),daemonsSent:re().default(0)})});ct([pr,It,eh,mr,Dr,Er,vr,yr,zt,th,nh,_r,Sr,rh,ih,sh]);const Fr=D.z.object({VITE_INJECT_AGIFLOW_APP_ENDPOINT:D.z.string().default("").transform(t=>t.trim()||void 0).pipe(D.z.string().url().optional()).describe("Server base URL for both HTTP API and WebSocket connections (optional - leave empty for standalone mode)"),VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:D.z.string().default("").transform(t=>t.trim()||void 0).pipe(D.z.string().url().optional()).describe("Server base URL when running inside Docker containers (optional)"),VITE_AGENT_CLI_DOCKER_IMAGE:D.z.string().default("").describe("Docker image name for containerized Claude Code agents"),VITE_AGENT_CLI_DOCKER_NETWORK:D.z.string().default("").describe("Docker network mode for containerized agents"),VITE_SAVE_RAW:D.z.preprocess(t=>t==="false"||t===""||t===null||t===void 0?!1:t==="true"?!0:t,D.z.boolean()).default(!1)});Nn.config({override:!1,debug:!1});const ue=Fr.parse({VITE_INJECT_AGIFLOW_APP_ENDPOINT:"https://agiflow.io",VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:"https://agiflow.io",VITE_AGENT_CLI_DOCKER_IMAGE:"agiflowai/agent-cli:v0.0.4",VITE_AGENT_CLI_DOCKER_NETWORK:""});function wr(t=!1){return process.env.AGENT_CONTAINER_MODE==="true"||t?ue.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT}function oh(t){const e=new URL(t);return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.toString()}function Cr(t=!0,e){const r=fe.hostname().replace(/[^a-zA-Z0-9-]/g,"-");if(t){const i=e||process.cwd(),s=ni.createHash("sha256").update(i).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"").slice(0,8);return`claude-daemon-${r}-${s}`}return`claude-daemon-${r}-${Date.now()}`}function br(){return{hostname:fe.hostname(),platform:fe.platform(),arch:fe.arch(),release:fe.release(),cpus:fe.cpus().length,totalMemory:fe.totalmem(),type:fe.type()}}function ah(t){return t.replace(/^http/,"ws")}function Ar(t,e=3e3){return t.replace(/^ws/,"http").replace(/:\d+$/,`:${e}`)}function Tr(t,e=3e5,n){let r=null;const i=n||console,s=()=>{o(),t().catch(a=>{i.warn?.("Heartbeat failed:",a)||console.warn("Heartbeat failed:",a)}),r=setInterval(async()=>{try{await t()}catch(a){i.warn?.("Heartbeat failed:",a)||console.warn("Heartbeat failed:",a)}},e)},o=()=>{r&&(clearInterval(r),r=null)};return{start:s,stop:o}}class uh{ws=null;options;callbacks;isConnected=!1;reconnectTimer=null;shouldReconnect=!0;currentSessionId=null;credentialsService;logger;pingInterval=null;connectionAttempts=0;maxReconnectAttempts=10;heartbeatInterval=null;constructor(e,n={}){const r=D.SubEnvManager.isContainerMode?2e3:5e3;this.options={reconnectInterval:r,...e},this.callbacks=n,this.credentialsService=e.credentialsService??new D.CredentialsService,this.logger=e.logger??new D.Logger({verbose:e.verbose??!1}),D.SubEnvManager.isContainerMode&&this.logger.debug("🐳 Docker WebSocket service initialized with enhanced connectivity handling")}async connect(e){if(this.ws&&this.ws.readyState===_e.OPEN)return;this.currentSessionId=e;const n=await this.buildWebSocketUrl(e);return D.SubEnvManager.isContainerMode&&(this.logger.info(`🐳 Docker WebSocket connecting to: ${n}`),this.logger.debug("Docker network environment:",{hostname:D.SubEnvManager.hostname,containerMode:D.SubEnvManager.isContainerMode,serverUrl:this.options.serverUrl})),new Promise((r,i)=>{const s={};this.options.apiKey&&(s["x-api-key"]=this.options.apiKey),this.ws=new _e(n,{headers:s}),this.ws.on("open",()=>{this.isConnected=!0,this.connectionAttempts=0;const o=this.logger;o&&(D.SubEnvManager.isContainerMode?o.info(`🐳 Docker WebSocket connected successfully to ${n}`):o.info(`🔌 WebSocket connected to ${n}`)),D.SubEnvManager.isContainerMode&&this.startHealthMonitoring(),this.startAgentHeartbeat(),this.callbacks.onConnect&&this.callbacks.onConnect(),r()}),this.ws.on("message",o=>{try{const a=JSON.parse(o.toString());this.handleMessage(a)}catch(a){this.log(`Error parsing message: ${a}`)}}),this.ws.on("close",(o,a)=>{this.isConnected=!1,this.currentSessionId=null,this.callbacks.onDisconnect&&this.callbacks.onDisconnect(o,a.toString()),this.shouldReconnect&&this.scheduleReconnect(e)}),this.ws.on("error",o=>{D.SubEnvManager.isContainerMode&&this.logger.error("🐳 Docker WebSocket connection error:",new Error(`Docker WebSocket error: ${o.message}. URL: ${n}, Hostname: ${D.SubEnvManager.hostname}, Server: ${this.options.serverUrl}`)),o.message.includes("401")&&this.options.apiKey&&this.log(`API key first 8 chars: ${this.options.apiKey.substring(0,8)}...`),(o.message.includes("ECONNREFUSED")||o.message.includes("ENOTFOUND"))&&this.logger.error("🐳 Docker networking issue - check if server is accessible from container"),this.callbacks.onError&&this.callbacks.onError(o),this.isConnected||i(o)}),setTimeout(()=>{this.isConnected||i(new Error("WebSocket connection timeout"))},1e4)})}disconnect(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHealthMonitoring(),this.stopAgentHeartbeat(),this.ws&&(this.ws.close(),this.ws=null),this.isConnected=!1}isWebSocketConnected(){return this.isConnected}getCurrentSessionId(){if(!this.currentSessionId)throw new Error("No active session ID");return this.currentSessionId}setCurrentSessionId(e){this.currentSessionId=e}sendAgentStatus(e){const n={eventType:$.STATUS,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:"",status:e.status||H.IDLE,agentType:e.agentType,pid:e.pid,version:e.version,capabilities:e.capabilities,message:e.message}};this.sendMessage(kt.parse(n))}sendAgentOutput(e){const n=new Date().toISOString(),r={eventType:$.MESSAGE_OUTPUT,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:e.content,id:e.messageId,messageId:e.messageId,messageType:"output",parts:[],contentSize:e.content.length,messageTimestamp:n,stream:e.stream,isComplete:e.isComplete||!1,metadata:e.metadata,createdAt:n,updatedAt:n}};this.sendMessage(hr.parse(r))}sendAgentError(e){const n={eventType:$.ERROR,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:"",error:{code:e.code,message:e.message,details:e.details,stack:e.stack}}};this.sendMessage(fr.parse(n))}sendStdoutMessage(e){const n={eventType:$.MESSAGE_STDOUT,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:e}};this.sendMessage(gr.parse(n))}sendMessage(e){if(this.ws&&this.ws.readyState===_e.OPEN)try{this.ws.send(JSON.stringify(e))}catch(n){D.SubEnvManager.isContainerMode?(this.logger.error("🐳 Docker WebSocket send error:",n),this.logger.debug("🐳 Message that failed to send:",e)):this.logger.error("WebSocket send error:",n),this.currentSessionId&&this.scheduleReconnect(this.currentSessionId)}else{const n=this.ws?this.ws.readyState:"no socket";D.SubEnvManager.isContainerMode?this.logger.warn(`🐳 Docker WebSocket not ready to send message. State: ${n}`):this.logger.warn(`WebSocket not ready to send message. State: ${n}`)}}handleMessage(e){try{switch(e.eventType){case $.STATUS:if(e.command===S.REQUEST){const n=ar.parse(e);this.callbacks.onStatusRequest&&this.callbacks.onStatusRequest(n)}break;case $.MESSAGE_INPUT:if(e.command===S.REQUEST){const n=lr.parse(e);this.callbacks.onMessageInput&&this.callbacks.onMessageInput(n)}break;case $.MESSAGE_STDIN:if(e.command===S.REQUEST){const n=dr.parse(e);this.callbacks.onStdinInput&&this.callbacks.onStdinInput(n)}break;case $.RESIZE:if(e.command===S.REQUEST){const n=ur.parse(e),r=this.logger;r&&r.info(`📐 Received resize event: ${n.payload.cols}x${n.payload.rows}`),this.callbacks.onResizeRequest?this.callbacks.onResizeRequest(n):r&&r.warn("📐 No onResizeRequest callback registered, ignoring resize event")}break;case $.DIRECT_CONTROL:if(e.command===S.REQUEST){const n=cr.parse(e),r=this.logger;r&&r.info(`🎮 Received direct control event: ${n.payload.controlType} - data: ${JSON.stringify(n.payload.data)}`),this.callbacks.onDirectControl?this.callbacks.onDirectControl(n):r&&r.warn("🎮 No onDirectControl callback registered, ignoring direct control event")}break;default:this.callbacks.onMessage&&this.callbacks.onMessage(e)}}catch(n){this.log(`Error validating message: ${n}`)}}scheduleReconnect(e){if(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.connectionAttempts++,this.connectionAttempts>this.maxReconnectAttempts){D.SubEnvManager.isContainerMode?this.logger.error(`🐳 Docker WebSocket max reconnection attempts (${this.maxReconnectAttempts}) exceeded. Giving up.`):this.logger.error(`WebSocket max reconnection attempts (${this.maxReconnectAttempts}) exceeded. Giving up.`);return}const n=this.options.reconnectInterval||2e3,r=D.SubEnvManager.isContainerMode?Math.min(this.connectionAttempts,5):1,i=n*r;D.SubEnvManager.isContainerMode&&this.logger.info(`🐳 Docker WebSocket reconnection attempt ${this.connectionAttempts}/${this.maxReconnectAttempts} in ${i}ms`),this.reconnectTimer=setTimeout(async()=>{try{await this.connect(e)}catch(s){const o=s instanceof Error?s.message:String(s);D.SubEnvManager.isContainerMode?this.logger.error(`🐳 Docker WebSocket reconnection failed: ${o}`):this.log(`Reconnection failed: ${o}`),this.scheduleReconnect(e)}},i)}async buildWebSocketUrl(e){const n=new URL(this.options.serverUrl);n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),n.pathname=`/api/v1/organizations/${this.options.organizationId}/agent-sessions/${e}/ws`,n.searchParams.set("clientType","agent");const r=await this.credentialsService.getDeviceId();return n.searchParams.set("deviceId",r||"unknown"),n.toString()}startHealthMonitoring(){this.pingInterval&&clearInterval(this.pingInterval),this.pingInterval=setInterval(()=>{this.ws&&this.ws.readyState===_e.OPEN||(this.logger.warn("🐳 Docker WebSocket connection lost during health check"),this.stopHealthMonitoring(),this.currentSessionId&&this.scheduleReconnect(this.currentSessionId))},3e4)}stopHealthMonitoring(){this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=null)}startAgentHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.sendHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.sendHeartbeat()},3e4)}stopAgentHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}sendHeartbeat(){if(this.isConnected&&this.currentSessionId)try{const e={eventType:$.STATUS,command:S.RESPONSE,payload:{sessionId:this.currentSessionId,timestamp:Date.now(),data:"",status:H.IDLE,message:"Heartbeat"}},n=kt.parse(e);this.sendMessage(n),this.logger.debug("Agent session heartbeat sent")}catch(e){this.logger.warn("Failed to send agent session heartbeat:",e)}}log(e){this.options.verbose&&console.log(`[AGENT-WS] ${e}`)}}class ch{session;logger;constructor(e){this.logger=e??new D.Logger({verbose:!1})}spawn(e,n){const r=e.agentSessionId||xn.ulid(),i=e.workingDir||process.cwd(),s={};e.agentApiKey&&(s[D.ENV_KEYS.AGENT_API_KEY]=e.agentApiKey),e.agentOrganizationId&&(s[D.ENV_KEYS.AGENT_ORGANIZATION_ID]=e.agentOrganizationId),e.agentDeviceGuid&&(s[D.ENV_KEYS.AGENT_DEVICE_GUID]=e.agentDeviceGuid),e.agentServerUrl&&(s[D.ENV_KEYS.AGENT_SERVER_URL]=e.agentServerUrl),e.agentType&&(s[D.ENV_KEYS.AGENT_TYPE]=e.agentType),s[D.ENV_KEYS.AGENT_SESSION_ID]=r,this.logger.debug("PTY Environment Variables:",{...process.env,...s,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"});const o=ti.spawn(e.command,e.args||[],{name:"xterm-256color",cwd:i,env:{...process.env,...s,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),a={id:r,ptyProcess:o,command:e.command,workingDir:i,status:"running",createdAt:new Date,lastActivity:new Date,logStream:e.logStream};return o.onData(l=>{a.lastActivity=new Date,a.logStream&&a.logStream.write(l),process.stdout.isTTY&&process.stdout.write(l),n?.onData&&n.onData(l,l)}),o.onExit(l=>{const g=l.exitCode,p=l.signal;a.status=g===0?"stopped":"error",a.lastActivity=new Date,this.logger.info(`PTY process ${r} exited with code ${g}${p?` (signal: ${p})`:""}`),a.logStream&&a.logStream.end(),n?.onExit&&n.onExit(g,p)}),this.session=a,a}sendInput(e){return this.session?.ptyProcess?(this.session.ptyProcess.write(e),this.session.lastActivity=new Date,!0):(this.logger.warn("No active process to send input to"),!1)}resize(e,n){return this.session?.ptyProcess?(this.session.ptyProcess.resize(e,n),this.session.lastActivity=new Date,!0):!1}kill(e){if(!this.session?.ptyProcess)return this.logger.warn("No PTY session to kill"),!1;try{return this.session.ptyProcess.kill(e),this.session.status="stopped",!0}catch(n){return this.logger.error(`Failed to kill PTY session : ${n}`),!1}}getSession(){return this.session}isSessionRunning(){return this.session?.status==="running"}}class $t{logger;targetDirectory;originalDirectory;envFilePatterns=[".env",".env.development",".dev.vars",".env.test"];constructor(e){if(this.targetDirectory=C.resolve(e.targetDirectory),this.originalDirectory=e.originalDirectory?C.resolve(e.originalDirectory):void 0,this.logger=e.logger??new D.Logger({verbose:!1}),!T.existsSync(this.targetDirectory))throw new Error(`Target directory does not exist: ${this.targetDirectory}`);if(this.originalDirectory&&!T.existsSync(this.originalDirectory))throw new Error(`Original directory does not exist: ${this.originalDirectory}`)}async setup(){const e={envFilesCopied:[],errors:[]};try{this.originalDirectory&&(this.logger.info("Copying environment files..."),e.envFilesCopied=await this.copyEnvironmentFiles(),this.logger.success(`Copied ${e.envFilesCopied.filter(n=>n.copied).length} environment files`))}catch(n){const r=`Setup failed: ${n.message}`;e.errors.push(r),this.logger.error(r)}return e}async copyEnvironmentFiles(){if(!this.originalDirectory)return[];const e=[],n=await this.findEnvironmentFiles(this.originalDirectory);for(const r of n)try{const i=C.relative(this.originalDirectory,r),s=C.join(this.targetDirectory,i),o=C.dirname(s);T.existsSync(o)||await pe.mkdir(o,{recursive:!0}),await pe.copyFile(r,s),e.push({originalPath:r,targetPath:s,relativePath:i,copied:!0}),this.logger.debug(`Copied: ${i}`)}catch(i){e.push({originalPath:r,targetPath:"",relativePath:C.relative(this.originalDirectory,r),copied:!1}),this.logger.warn(`Failed to copy ${r}: ${i.message}`)}return e}async findEnvironmentFiles(e,n=0){const r=[];if(n>=5)return r;try{const s=await pe.readdir(e,{withFileTypes:!0});for(const o of s){const a=C.join(e,o.name);if(o.isDirectory()){if(this.shouldSkipDirectory(o.name))continue;const l=await this.findEnvironmentFiles(a,n+1);r.push(...l)}else o.isFile()&&this.isEnvironmentFile(o.name)&&r.push(a)}}catch(s){this.logger.debug(`Cannot read directory ${e}: ${s.message}`)}return r}isEnvironmentFile(e){return this.envFilePatterns.some(n=>n.includes("*")?!1:e===n||e.startsWith(n+"."))}shouldSkipDirectory(e){return["node_modules",".git",".next",".nuxt","dist","build","coverage",".nyc_output",".cache","tmp","temp",".vscode",".idea","__pycache__",".pytest_cache",".mypy_cache"].includes(e)||e.startsWith(".")}async installDependencies(e="pnpm"){try{const n=C.join(this.targetDirectory,"package.json");if(!T.existsSync(n))return this.logger.debug("No package.json found, skipping dependency installation"),!1;if(!this.isPackageManagerAvailable(e))if(this.logger.warn(`${e} is not available, trying npm...`),this.isPackageManagerAvailable("npm"))e="npm";else throw new Error("No package manager available (tried pnpm, npm)");const r=this.getInstallCommand(e);this.logger.info(`Running: ${r}`);try{return ie.execSync(r,{cwd:this.targetDirectory,stdio:"pipe",encoding:"utf8"}),!0}catch(i){if(i.message?.includes("EUNSUPPORTEDPROTOCOL")||i.message?.includes("workspace:"))return this.logger.warn("Workspace protocol detected in dependencies, skipping installation"),this.logger.debug("This is expected in Docker containers where dependencies are pre-installed"),!1;throw i}}catch(n){return this.logger.error(`Failed to install dependencies: ${n.message}`),!1}}isPackageManagerAvailable(e){try{return ie.execSync(`${e} --version`,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}getInstallCommand(e){switch(e){case"pnpm":return"pnpm install";case"yarn":return"yarn install";case"npm":default:return"npm install"}}async getEnvironmentFiles(){return this.originalDirectory?await this.findEnvironmentFiles(this.originalDirectory):[]}getTargetDirectory(){return this.targetDirectory}getOriginalDirectory(){return this.originalDirectory}hasPackageJson(){return T.existsSync(C.join(this.targetDirectory,"package.json"))}isNodeProject(){return["package.json","node_modules","yarn.lock","package-lock.json","pnpm-lock.yaml"].some(n=>T.existsSync(C.join(this.targetDirectory,n)))}isPythonProject(){return["requirements.txt","pyproject.toml","setup.py","Pipfile","poetry.lock","uv.lock"].some(n=>T.existsSync(C.join(this.targetDirectory,n)))}isNxMonorepo(){return["nx.json","workspace.json","angular.json"].some(n=>T.existsSync(C.join(this.targetDirectory,n)))}getDefaultPreAgentHooks(e){if(e&&e.length>0)return this.logger.debug("User provided pre-agent hooks, skipping defaults"),e;const n=[];return this.isNodeProject()&&!T.existsSync(C.join(this.targetDirectory,"node_modules"))&&this.hasPackageJson()&&(this.logger.info("No node_modules found, adding default pnpm install hook"),n.push("pnpm install"),this.isNxMonorepo()&&(this.logger.info("Nx monorepo detected, adding default build hook"),n.push("nx run-many -t build"))),this.isPythonProject()&&(T.existsSync(C.join(this.targetDirectory,".venv"))||T.existsSync(C.join(this.targetDirectory,"venv"))||(this.logger.info("No virtual environment found, adding default Python setup hooks"),T.existsSync(C.join(this.targetDirectory,"uv.lock"))?n.push("uv sync"):T.existsSync(C.join(this.targetDirectory,"requirements.txt"))&&(n.push("python -m venv .venv"),n.push(".venv/bin/pip install -r requirements.txt")))),n}async preAgentSetup(e){const n={hooks:[]};if(this.originalDirectory){const r=await this.setup();n.envFilesCopied=r.envFilesCopied,n.errors=r.errors}return n.hooks=this.getDefaultPreAgentHooks(e),n}async buildNxMonorepo(){try{if(!this.isNxAvailable())return this.logger.warn("Nx is not available, skipping build"),!1;this.logger.info("Running: nx run-many -t build");try{return ie.execSync("nx run-many -t build",{cwd:this.targetDirectory,stdio:"pipe",encoding:"utf8",timeout:3e5}),!0}catch(e){if(e.message?.includes("workspace:")||e.message?.includes("Cannot find module")||e.message?.includes("ENOENT"))return this.logger.warn("Build failed due to workspace or dependency issues, skipping build"),this.logger.debug("This is expected in Docker containers with pre-built applications"),!1;throw e}}catch(e){return this.logger.error(`Failed to build Nx monorepo: ${e.message}`),!1}}isNxAvailable(){try{return ie.execSync("nx --version",{stdio:"pipe",timeout:5e3}),!0}catch{try{return ie.execSync("npx nx --version",{stdio:"pipe",timeout:1e4}),!0}catch{return!1}}}}class kr{logger;onData;onExit;ctrlCCount=0;ctrlCTimeout=null;CTRL_C_RESET_MS=3e3;constructor({logger:e,onData:n,onExit:r}){this.logger=e??new D.Logger({verbose:!1}),this.onData=n,this.onExit=r,this.start()}handleCtrlC(){return this.ctrlCCount++,this.ctrlCTimeout&&clearTimeout(this.ctrlCTimeout),this.ctrlCCount===1?(this.logger.debug("First Ctrl+C detected - Claude will clear input. Press Ctrl+C again to exit."),this.ctrlCTimeout=setTimeout(()=>{this.ctrlCCount=0,this.ctrlCTimeout=null},this.CTRL_C_RESET_MS),!1):this.ctrlCCount>=2?(this.logger.debug("Second Ctrl+C detected - initiating graceful exit."),this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.ctrlCCount=0,!0):!1}start(){if(this.logger.info("StdinForwarding starting..."),!process.stdin.isTTY){this.logger.warn("No TTY available for stdin forwarding");return}this.logger.debug("Setting up process event handlers..."),process.on("SIGINT",()=>{this.logger.info("Process received SIGINT"),this.onExit("SIGINT")}),process.on("SIGTERM",()=>{this.logger.info("Process received SIGTERM"),this.onExit("SIGTERM")}),process.on("uncaughtException",async e=>{this.logger.error("Uncaught exception:",e);try{this.onExit("uncaughtException")}catch{}process.exit(1)}),process.on("unhandledRejection",async e=>{this.logger.error("Unhandled rejection:",e);try{this.onExit(e.toString())}catch{}process.exit(1)}),this.logger.debug("Setting stdin to raw mode...");try{process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.setEncoding("utf8"),this.logger.debug("Stdin raw mode enabled successfully")}catch(e){this.logger.error("Failed to set stdin raw mode:",e);return}this.logger.debug("Setting up stdin data handler..."),process.stdin.on("data",e=>{try{if(this.logger.debug("=== STDIN DATA RECEIVED ==="),e==="")if(this.handleCtrlC()){this.logger.debug("Double Ctrl+C detected, exiting agent"),this.onExit(e);return}else{this.logger.debug("First Ctrl+C detected, forwarding to Claude to clear input"),this.onData(e);return}if(e===""){this.logger.debug("Received Ctrl+D (EOF), exiting agent"),this.onExit(e);return}this.logger.debug(`Forwarding stdin data: ${JSON.stringify(e)} (length: ${e.length}, chars: ${e.split("").map(o=>o.charCodeAt(0)).join(",")})`),e.length===1&&e.charCodeAt(0)>=32&&e.charCodeAt(0)<=126?this.logger.debug("Normal typing character detected"):e==="\r"||e===`
62
- `||e===`\r
63
- `?this.logger.debug("Enter key detected"):e===" "?this.logger.debug("Tab key detected"):e==="\b"||e===""?this.logger.debug("Backspace detected"):this.logger.debug(`Special character detected (code: ${e.charCodeAt(0)})`),this.logger.debug("About to call onData..."),this.onData(e),this.logger.debug("onData call completed")}catch(n){this.logger.error("Error handling stdin data:",n)}}),process.stdin.on("error",e=>{this.logger.error("Stdin error:",e)}),process.stdin.on("end",()=>{this.logger.info("Stdin ended")}),this.logger.info("Stdin forwarding enabled for fullscreen agent")}restore(){this.logger.info("Restoring stdio handler to terminal...");try{this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.ctrlCCount=0,process.stdin.isTTY&&(process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("error"),process.stdin.removeAllListeners("end"),process.stdin.setRawMode(!1),process.stdin.pause()),this.logger.info("Stdio handler restored to terminal successfully")}catch(e){throw this.logger.error("Error restoring stdio handler:",e),e}}}class Le extends qr.EventEmitter{logger;isShuttingDown=!1;activeTerminations=new Map;callbacks={};constructor(e){super(),this.logger=e??new D.Logger({verbose:!1})}registerCallbacks(e){this.callbacks={...this.callbacks,...e}}async handleAgentSigint(e){this.logger.info(`Agent ${e} received SIGINT (Ctrl+C), stopping agent only`);const n={agentSessionId:e,reason:"agent_sigint",signal:"SIGINT"},r=this.activeTerminations.get(e);if(r)return this.logger.debug(`Termination already in progress for agent ${e}`),r;const i=this.performAgentSigintTermination(n);this.activeTerminations.set(e,i);try{await i}finally{this.activeTerminations.delete(e)}}async performAgentSigintTermination(e){try{this.emit("agent:sigint",e),this.callbacks.onAgentSigint&&await this.callbacks.onAgentSigint(e),this.emit("agent:cleanup",e),this.callbacks.onAgentTerminated&&await this.callbacks.onAgentTerminated(e)}catch(n){throw this.logger.error(`Error handling agent SIGINT: ${n}`),n}}async handlePtyTermination(e){const{agentSessionId:n,exitCode:r,signal:i}=e;this.logger.info(`PTY terminated naturally for session agent ${n}. Exit code: ${r}, Signal: ${i}`);const s=this.activeTerminations.get(n);if(s)return this.logger.debug(`Termination already in progress for agent ${n}`),s;const o=this.performPtyTermination(e);this.activeTerminations.set(n,o);try{await o}finally{this.activeTerminations.delete(n)}}async performPtyTermination(e){try{this.emit("pty:terminated",e),this.callbacks.onPtyTerminated&&await this.callbacks.onPtyTerminated(e),e.reason==="natural"&&(this.emit("agent:cleanup",e),this.callbacks.onAgentTerminated&&await this.callbacks.onAgentTerminated(e))}catch(n){throw this.logger.error(`Error handling PTY termination: ${n}`),n}}async terminateAgent(e,n={}){const{force:r=!1,timeout:i=5e3}=n;this.logger.info(`Terminating agent ${e} for session force: ${r}`);const s={agentSessionId:e,reason:"user_requested"},o=this.activeTerminations.get(e);if(o)return this.logger.debug(`Termination already in progress for agent ${e}`),o;const a=this.performAgentTermination(s,{force:r,timeout:i});this.activeTerminations.set(e,a);try{await a}finally{this.activeTerminations.delete(e)}}async performAgentTermination(e,n){const{force:r,timeout:i}=n;try{this.emit("agent:terminating",e);const s=new Promise((a,l)=>{setTimeout(()=>l(new Error(`Termination timeout for agent ${e.agentSessionId}`)),i)}),o=new Promise(a=>{const l=g=>{g.agentSessionId===e.agentSessionId&&(this.off("agent:terminated",l),a())};this.on("agent:terminated",l)});try{await Promise.race([o,s]),this.logger.info(`Agent ${e.agentSessionId} terminated gracefully`)}catch(a){if(r)this.logger.warn(`Forcefully terminating agent ${e.agentSessionId} after timeout`),this.emit("agent:force-terminate",e);else throw a}this.callbacks.onAgentTerminated&&await this.callbacks.onAgentTerminated(e)}catch(s){throw this.logger.error(`Error terminating agent: ${s}`),s}}async shutdownDaemon(e){if(this.isShuttingDown){this.logger.debug("Daemon shutdown already in progress");return}this.isShuttingDown=!0,this.logger.info("Initiating daemon shutdown, terminating all agents...");try{this.callbacks.onDaemonTerminating&&await this.callbacks.onDaemonTerminating(),this.emit("daemon:shutting-down");const n=e.map(r=>this.terminateAgent(r,{force:!0,timeout:3e3}).catch(i=>{this.logger.error(`Failed to terminate agent ${r}: ${i}`)}));await Promise.allSettled(n),this.logger.info("All agents terminated, daemon can now exit"),this.emit("daemon:shutdown-complete")}catch(n){throw this.logger.error(`Error during daemon shutdown: ${n}`),n}finally{this.isShuttingDown=!1}}isShuttingDownNow(){return this.isShuttingDown}async waitForActiveTerminations(){this.activeTerminations.size!==0&&(this.logger.info(`Waiting for ${this.activeTerminations.size} active terminations to complete...`),await Promise.allSettled(this.activeTerminations.values()),this.logger.info("All active terminations completed"))}cleanup(){this.removeAllListeners(),this.activeTerminations.clear(),this.callbacks={}}}class Ir{agentType;serverUrl;apiUrl;apiKey;verbose;organizationId;standalone;logger;credentialsService;terminationService;onFullscreenChange;wsService;httpService;ptyRunner;agentInfo=null;ptySessionId=null;xtermEnabled=!1;stdinForwarding=null;isFullscreen=!1;stdoutBuffer="";stdoutThrottleTimer=null;lastStdoutSent=0;STDOUT_THROTTLE_MS=500;STDOUT_BUFFER_LIMIT=64*1024;backgroundOutputBuffer=[];BACKGROUND_BUFFER_SIZE=10;BACKGROUND_CHUNK_MAX_SIZE=2048;constructor(e){if(this.agentType=e.agentType,this.serverUrl=e.serverUrl,this.apiUrl=e.apiUrl,this.apiKey=e.apiKey,this.verbose=e.verbose??!1,this.organizationId=e.organizationId,this.standalone=e.standalone??!1,this.logger=e.logger??new D.Logger({verbose:this.verbose}),this.credentialsService=e.credentialsService??new D.CredentialsService,this.terminationService=e.terminationService??new Le(this.logger),this.onFullscreenChange=e.onFullscreenChange,this.ptyRunner=new ch(this.logger),e.serverUrl){const i={serverUrl:e.serverUrl,apiKey:e.apiKey,verbose:e.verbose,organizationId:e.organizationId,credentialsService:this.credentialsService,logger:this.logger},s={onStatusRequest:o=>this.handleStatusRequest(o),onMessageInput:o=>this.handleMessageInput(o),onStdinInput:o=>this.handleStdinInput(o),onResizeRequest:o=>this.handleResizeRequest(o),onDirectControl:o=>this.handleDirectControl(o),onConnect:()=>this.onWebSocketConnect(),onDisconnect:(o,a)=>this.onWebSocketDisconnect(o,a),onError:o=>this.onWebSocketError(o)};this.wsService=new uh(i,s),this.logger.debug("WebSocket service initialized")}else this.logger.info("Running in standalone mode without WebSocket connection");const n=wr(),r=this.apiUrl||n||e.serverUrl;r?(this.httpService=new D.AgentHttpService({apiUrl:r,organizationId:this.organizationId,apiKey:this.apiKey,logger:this.logger}),this.logger.debug("HTTP service initialized")):this.logger.info("HTTP service not initialized - no API URL provided"),this.standalone&&this.initializeStdinForwarding()}initializeStdinForwarding(){this.stdinForwarding=new kr({logger:this.logger,onData:e=>{this.logger.debug(`StdinForwarding received data: ${JSON.stringify(e)}`),this.sendInputToPty(e)},onExit:e=>{this.logger.info(`StdinForwarding received exit signal: ${e}`),this.disconnect(),process.exit(0)}})}async connectToSession(e){if(this.logger.info(`connectToSession called with sessionId: ${e}`),this.logger.info(`wsService exists: ${!!this.wsService}`),this.logger.info(`serverUrl: ${this.serverUrl||"undefined"}`),!this.wsService){this.logger.info("WebSocket service not available - skipping connection");return}this.logger.info("Attempting to connect to WebSocket..."),await this.wsService.connect(e),this.wsService.sendAgentStatus({agentType:this.agentType,status:H.IDLE,message:`${this.agentType} agent connected`})}disconnect(){if(this.standalone&&this.stdinForwarding)try{this.stdinForwarding.restore(),this.stdinForwarding=null}catch(e){this.logger.error("Error restoring stdin forwarding:",e)}this.flushStdoutBuffer(),this.stdoutThrottleTimer&&(clearTimeout(this.stdoutThrottleTimer),this.stdoutThrottleTimer=null),this.ptySessionId&&(this.logger.info(`Terminating PTY session: ${this.ptySessionId}`),this.ptyRunner.kill(),this.ptySessionId=null),this.wsService&&this.wsService.disconnect(),this.agentInfo=null}onWebSocketConnect(){this.logger.debug(`WebSocket connected for ${this.agentType} agent`)}onWebSocketDisconnect(e,n){this.logger.debug(`WebSocket disconnected for ${this.agentType} agent (${e}): ${n}`)}onWebSocketError(e){this.logger.error(`WebSocket error for ${this.agentType} agent: ${e?.message||"Unknown error"}`),this.logger.error(`Error stack: ${e?.stack||"No stack trace"}`)}async handleStatusRequest(e){if(this.logger.debug(`Handling status request for session: ${e.payload.sessionId}`),!this.wsService){this.logger.debug("WebSocket service not available - cannot handle status request");return}try{try{this.wsService.getCurrentSessionId()!==e.payload.sessionId&&(this.wsService.setCurrentSessionId(e.payload.sessionId),this.logger.debug(`Set current session ID to: ${e.payload.sessionId}`))}catch{this.wsService.setCurrentSessionId(e.payload.sessionId),this.logger.debug(`Set current session ID to: ${e.payload.sessionId}`)}let n=H.IDLE,r=`${this.agentType} agent is idle`;this.agentInfo&&this.agentInfo.agentSessionId===e.payload.sessionId?(n=this.agentInfo.status,n===H.IDLE?r=`${this.agentType} agent is running`:n===H.STARTING?r=`${this.agentType} agent is starting`:n===H.ERROR?r=`${this.agentType} agent encountered an error`:n===H.STOPPED&&(r=`${this.agentType} agent is stopped`)):(this.logger.debug(`No active agent process for session ${e.payload.sessionId}, but daemon is ready`),r=`${this.agentType} daemon ready, agent not launched`),e.payload.fullscreen===!0&&(this.logger.debug("Status request includes fullscreen=true, enabling fullscreen mode"),this.setFullscreen(!0)),this.wsService.sendAgentStatus({agentType:this.agentType,status:n,message:r,pid:this.agentInfo?.process?.pid||process.pid,version:await this.getVersion()||void 0,capabilities:["chat","code-editing","file-operations"]})}catch(n){this.wsService.sendAgentError({code:"STATUS_FAILED",message:`Status request failed: ${n.message}`,details:{error:n.toString()}})}}async handleMessageInput(e){this.logger.debug(`Handling message input: ${e.payload.content}`);const n=e.payload.content;if(this.sendInputToPty("\x1B[I"),this.agentType.toLowerCase().includes(J.GEMINI_CLI)){this.logger.debug("Gemini agent detected - pasting content with newline");for(const i of[" "," "])await new Promise(s=>{setTimeout(()=>{this.sendInputToPty(i),s(null)},150)});await new Promise(i=>{setTimeout(()=>{this.sendInputToPty(`${n}
64
- `),i(null)},150)}),await new Promise(i=>{setTimeout(()=>{this.sendInputToPty("\r"),i(null)},150)})}else this.sendInputToPty(n),setTimeout(()=>{this.sendInputToPty("\r")},50)}async handleStdinInput(e){if(!this.xtermEnabled){this.logger.debug("Stdin input received but xterm is not enabled, ignoring");return}this.logger.debug(`Handling stdin input: ${e.payload.data}`),this.sendInputToPty(e.payload.data)}async handleResizeRequest(e){if(this.logger.info(`🖥️ Resize request received: ${e.payload.cols}x${e.payload.rows}, xterm enabled: ${this.xtermEnabled}`),!this.xtermEnabled){this.logger.warn("Resize request received but xterm is not enabled, ignoring");return}this.setFullscreen(!0),this.resizePty(e.payload.cols,e.payload.rows),setTimeout(()=>{this.sendBackgroundBuffer()},1e3),this.logger.info(`✅ PTY resized to ${e.payload.cols}x${e.payload.rows}`)}async handleDirectControl(e){this.logger.debug(`Handling direct control request: ${e.payload.controlType} - data: ${JSON.stringify(e.payload.data)}`);try{this.sendInputToPty(e.payload.data),this.logger.debug(`Direct control signal sent to PTY: ${e.payload.controlType}`)}catch(n){this.logger.error(`Failed to send direct control signal to PTY: ${n}`)}}sendStdoutEvent(e){if(!this.xtermEnabled||!this.agentInfo||(this.addToBackgroundBuffer(e),!this.isFullscreen))return;if(this.stdoutBuffer+=e,this.stdoutBuffer.length>this.STDOUT_BUFFER_LIMIT){this.logger.debug(`📦 Stdout buffer limit exceeded (${this.stdoutBuffer.length} chars), flushing immediately`),this.flushStdoutBuffer();return}const r=Date.now()-this.lastStdoutSent;if(r>=this.STDOUT_THROTTLE_MS)this.flushStdoutBuffer();else if(!this.stdoutThrottleTimer){const i=this.STDOUT_THROTTLE_MS-r;this.stdoutThrottleTimer=setTimeout(()=>{this.flushStdoutBuffer()},i)}}flushStdoutBuffer(){if(!(!this.stdoutBuffer||!this.wsService))try{this.wsService.sendStdoutMessage(this.stdoutBuffer),this.lastStdoutSent=Date.now(),this.logger.debug(`📤 Stdout buffer flushed: ${this.stdoutBuffer.length} chars`),this.stdoutBuffer="",this.stdoutThrottleTimer&&(clearTimeout(this.stdoutThrottleTimer),this.stdoutThrottleTimer=null)}catch(e){this.logger.error("Failed to send stdout event:",e)}}addToBackgroundBuffer(e){const n=e.length>this.BACKGROUND_CHUNK_MAX_SIZE?e.substring(e.length-this.BACKGROUND_CHUNK_MAX_SIZE):e;this.backgroundOutputBuffer.push(n),this.backgroundOutputBuffer.length>this.BACKGROUND_BUFFER_SIZE&&this.backgroundOutputBuffer.shift(),this.logger.debug(`📦 Added ${n.length} chars to background buffer (${this.backgroundOutputBuffer.length}/${this.BACKGROUND_BUFFER_SIZE} chunks)`)}sendBackgroundBuffer(){if(this.backgroundOutputBuffer.length===0||!this.wsService)return;this.logger.debug(`📤 Sending background buffer: ${this.backgroundOutputBuffer.length} chunks`);const e=this.backgroundOutputBuffer.join("");if(e)try{this.wsService.sendStdoutMessage(e),this.logger.debug(`📤 Background buffer sent: ${e.length} chars`)}catch(n){this.logger.error("Failed to send background buffer:",n)}}setXtermEnabled(e){this.xtermEnabled=e,this.logger.debug(`Xterm functionality ${e?"enabled":"disabled"}`)}setFullscreen(e,n=!1){const r=this.isFullscreen;this.isFullscreen=e,this.logger.debug(`Agent fullscreen mode ${e?"enabled":"disabled"}`),e&&!r&&this.xtermEnabled&&this.agentInfo&&this.sendBackgroundBuffer(),!n&&r!==e&&this.agentInfo&&this.onFullscreenChange&&this.onFullscreenChange(this.agentInfo.agentSessionId,e)}getFullscreen(){return this.isFullscreen}sendAgentStatus(e){this.wsService&&this.wsService.sendAgentStatus(e)}sendAgentOutput(e){this.wsService&&this.wsService.sendAgentOutput(e)}sendAgentError(e){this.wsService&&this.wsService.sendAgentError(e)}getAgentInfo(){return this.agentInfo}sendInputToPty(e){this.ptyRunner.sendInput(e)}setAgentInfo(e){if(this.agentInfo=e,e.agentSessionId&&this.wsService)try{this.wsService.setCurrentSessionId(e.agentSessionId)}catch{}}getAgentEnvironmentVariables(){const e={};for(const[n,r]of Object.entries(process.env))r!==void 0&&(e[n]=r);return this.apiKey&&(e[D.ENV_KEYS.AGENT_API_KEY]=this.apiKey),this.organizationId&&(e[D.ENV_KEYS.AGENT_ORGANIZATION_ID]=this.organizationId),this.serverUrl&&(e[D.ENV_KEYS.AGENT_SERVER_URL]=this.serverUrl),e[D.ENV_KEYS.AGENT_TYPE]=this.agentType,e[D.ENV_KEYS.VERBOSE]=this.verbose?"true":"false",e}configureNodeOptions(e){let n=null;const r=C.join(__dirname,"networkLog.js"),i=C.join(__dirname,"networkLog.ts"),s=C.join(__dirname,"..","networkLog.js"),o=C.join(__dirname,"..","networkLog.ts");T.existsSync(r)?n=r:T.existsSync(i)?n=i:T.existsSync(s)?n=s:T.existsSync(o)&&(n=o);let l=e["NODE_OPTIONS"]||"";return this.logger.debug("Network logging hook configuration:",{sameDirJs:r,sameDirTs:i,parentDirJs:s,parentDirTs:o,foundPath:n,existingNodeOptions:l,alreadyIncludes:l.includes("networkLog")}),n&&!l.includes("networkLog")?(l=`${l} --require ${n}`.trim(),this.logger.debug(`Network logging hook added to NODE_OPTIONS: ${n}`)):n?this.logger.debug("Network logging hook already included in NODE_OPTIONS"):this.logger.warn("Network logging hook not found at any expected location"),this.logger.debug(`Final NODE_OPTIONS: ${l}`),l}async sendInputToAgent(e){this.ptyRunner.sendInput(e)||this.logger.warn("Failed to send input to PTY session")}resizePty(e,n){this.ptyRunner.resize(e,n)}async executePreAgentStartHooks(e,n,r){const s=new $t({targetDirectory:n,logger:this.logger}).getDefaultPreAgentHooks(e);if(!s||s.length===0){this.logger.debug("No pre-agent start hooks to execute");return}this.logger.info(`Executing ${s.length} pre-agent start hook(s) in ${n}`);const o=[];for(let a=0;a<s.length;a++){const l=s[a];this.logger.info(`[${a+1}/${s.length}] Executing hook: ${l}`);let g;if(r&&this.httpService)try{g=(await this.httpService.startMessage(r,{messageType:"output",metadata:{hookIndex:a+1,totalHooks:s.length,command:l,status:"running"}})).id}catch(p){this.logger.debug("Failed to start hook message:",p)}try{const{spawn:p}=await import("child_process"),E=await new Promise(m=>{const F=p(l,{cwd:n,shell:!0,stdio:["pipe","pipe","pipe"]});let k="",u="";F.stdout?.on("data",c=>{const h=c.toString();k+=h,this.logger.debug(`[Hook stdout] ${h.trim()}`)}),F.stderr?.on("data",c=>{const h=c.toString();u+=h,this.logger.warn(`[Hook stderr] ${h.trim()}`)}),F.on("close",c=>{if(c===0)this.logger.success(`Hook completed successfully: ${l}`),k.trim()&&this.logger.debug(`Hook stdout: ${k.trim()}`),m({success:!0,stdout:k.trim()});else{this.logger.error(`Hook failed with exit code ${c}: ${l}`),k.trim()&&this.logger.error(`Hook stdout (full output): ${k.trim()}`),u.trim()&&this.logger.error(`Hook stderr (full error): ${u.trim()}`);const h=[];u.trim()&&h.push(`stderr: ${u.trim()}`),k.trim()&&h.push(`stdout: ${k.trim()}`);const d=h.length>0?`Hook failed with exit code ${c}. ${h.join(" | ")}`:`Hook failed with exit code ${c}`;m({success:!1,error:d,stderr:u.trim()||k.trim()||void 0})}}),F.on("error",c=>{this.logger.error(`Hook execution error: ${l}`,c),m({success:!1,error:c.message})})});if(r&&g&&this.httpService)try{const m=E.success?"completed":"failed",F=E.success?`✅ Hook completed: ${l}`:`❌ Hook failed: ${l}
65
- ${E.error}`;await this.httpService.updateMessage(r,g,{parts:[{type:"text",text:F}],metadata:{hookIndex:a+1,totalHooks:s.length,command:l,status:m,exitCode:E.success?0:1,stdout:E.stdout,stderr:E.stderr,error:E.error}})}catch(m){this.logger.debug("Failed to update hook message:",m)}E.success||o.push({hook:l,error:E.error||"Unknown error",stderr:E.stderr})}catch(p){const E=p instanceof Error?p.message:String(p);if(this.logger.error(`Failed to execute hook: ${l}`,p instanceof Error?p:new Error(E)),r&&g&&this.httpService)try{await this.httpService.updateMessage(r,g,{parts:[{type:"text",text:`❌ Hook execution failed: ${l}
66
- Error: ${E}`}],metadata:{hookIndex:a+1,totalHooks:s.length,command:l,status:"failed",error:E}})}catch(m){this.logger.debug("Failed to update hook message with error:",m)}o.push({hook:l,error:E})}}if(o.length>0){r&&await this.reportHookFailuresToTask(r,o);const a=o[0];throw new Error(`Pre-agent hook(s) failed. First failure: ${a.hook} - ${a.error}`)}this.logger.success("All pre-agent start hooks completed successfully")}async reportHookFailuresToTask(e,n){if(!this.httpService){this.logger.debug("HTTP service not available - cannot report hook failures to task");return}try{const i=`⚠️ **Pre-agent start hook(s) failed**
67
-
68
- ${n.map(s=>{let o=`• **Command**: \`${s.hook}\`
69
- **Error**: ${s.error}`;return s.stderr&&(o+=`
70
- **Output**: \`\`\`
71
- ${s.stderr}
72
- \`\`\``),o}).join(`
73
-
74
- `)}
75
-
76
- **Suggestion**: Please check the hook commands and ensure all dependencies are installed correctly.`;await this.httpService.createTaskComment(e,i,void 0,{type:"hook_failure",failedHooks:n}),this.logger.info("Hook failure reported to task")}catch(r){this.logger.warn("Failed to report hook errors to task:",r)}}async setupDockerRepository(e){const n=e.payload?.agentConfig;if(!(n?.docker===!0)){this.logger.debug("Not using Docker, skipping repository setup");return}const i=n?.workingDirectory||this.agentInfo?.workingDir;if(!i){this.logger.warn("No working directory specified for Docker repository setup");return}try{this.logger.info("Setting up Docker repository with environment files...");const s=process.cwd(),a=await new $t({targetDirectory:i,originalDirectory:s,logger:this.logger}).setup();if(a.envFilesCopied.length>0){const p=a.envFilesCopied.filter(E=>E.copied).length;this.logger.success(`Copied ${p} environment files to Docker container`)}a.errors.length>0&&(this.logger.warn(`Docker repository setup completed with ${a.errors.length} errors`),a.errors.forEach(p=>this.logger.debug(`Setup error: ${p}`)));const l=n?.agentSessionId||this.agentInfo?.agentSessionId,g=n?.hooks?.preAgentStartHooks||n?.hooks?.preAgentStart;await this.executePreAgentStartHooks(g,i,l)}catch(s){this.logger.error(`Failed to setup Docker repository: ${s}`)}}setupInitialPtySize(){try{const e=process.stdout.columns||80,n=process.stdout.rows||24;this.resizePty(e,n),this.logger.info(`🖥️ PTY resized to fit terminal: ${e}x${n}`)}catch(e){this.logger.warn("Failed to detect terminal size, using defaults:",e),this.resizePty(80,24)}}}class $r extends Ir{claudePath;claudeArgs=[];optionBuffer="";optionTimeout=null;isCollectingOptions=!1;OPTION_WAIT_MS=1e3;agentInputReady=!1;startupCommands=[];startupCommandsExecuted=!1;tempMcpConfigPath=null;tempSettingsPath=null;claudeVersion=null;supportsSettingsFlag=!1;ctrlCCount=0;ctrlCTimeout=null;CTRL_C_RESET_MS=2e3;constructor(e){super({...e,agentType:J.CLAUDE_CODE}),this.claudePath=e.claudePath||"claude"}detectClaudeType(){const{execSync:e}=require("child_process");try{const n=e(`which ${this.claudePath}`,{encoding:"utf-8"}).trim();try{const r=e(`file "${n}"`,{encoding:"utf-8"});if(r.includes("Mach-O")||r.includes("executable"))return this.logger.info(`Detected standalone binary at ${n}`),this.logger.info("Using npx @anthropic-ai/claude-code instead to enable hooks"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}catch{}try{const r=T.readFileSync(n,"utf-8");if(r.startsWith("#!/usr/bin/env node")||r.includes("npx"))return this.logger.info(`Detected npm package script at ${n}`),{command:this.claudePath,args:[]}}catch{}return this.logger.info("Using npx @anthropic-ai/claude-code to enable hooks"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}catch{return this.logger.info("Claude binary not found, using npx @anthropic-ai/claude-code"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}}extractOptions(e){const n=[],r=e.split(`
77
- `);for(const i of r){const s=i.trim(),o=s.match(/❯\s*(\d+)\.\s+(.+)$/);if(o){n.push({number:parseInt(o[1],10),text:o[2].trim(),selected:!0});continue}const a=s.match(/^│.*?(\d+)\.\s+(.+)$/);a&&n.push({number:parseInt(a[1],10),text:a[2].trim(),selected:!1})}return n}processDataForOptions(e){this.optionBuffer+=e;const n=we(e);(/❯\s*\d+\./m.test(n)||/Do you want to proceed\?/m.test(n)||/│.*\d+\.\s+/.test(n))&&!this.isCollectingOptions&&this.startOptionCollection()}startOptionCollection(){this.isCollectingOptions=!0,this.optionTimeout=setTimeout(async()=>{await this.processCollectedOptions()},this.OPTION_WAIT_MS)}async processCollectedOptions(){const e=we(this.optionBuffer),n=this.extractOptions(e);n.length>0&&await this.handleDetectedOptions(n),this.resetOptionState()}resetOptionState(){this.optionBuffer="",this.optionTimeout=null,this.isCollectingOptions=!1}async handleDetectedOptions(e){if(e.length===0)return;const n=new Date().toISOString();if(this.agentInfo&&this.httpService){D.SubEnvManager.isContainerMode&&await new Promise(i=>setTimeout(i,3e3));try{let i=e.map(l=>({label:l.text,value:l.number,selected:l.selected||!1}));i=this.deduplicateOptions(i);const s=D.createSelectComponent(i),o=D.createToolInvocationInput(!1,s),a=[D.createTextPart("Claude has detected available options. Please select one:"),D.createToolInvocationPart({toolName:"selectOption",toolCallId:`option-selection-${Date.now()}`,args:{timestamp:n},state:"call"},o)];await this.httpService.sendMessage({sessionId:this.agentInfo.agentSessionId,messageType:"output",parts:a,metadata:{optionDetection:!0,optionsCount:i.length,timestamp:n}})}catch(i){this.logger.error("Failed to send structured options message:",i)}}}deduplicateOptions(e){if(e.length===0)return e;const n=new Set;let r=-1;for(let a=0;a<e.length;a++){if(n.has(e[a].value)){r=a;break}n.add(e[a].value)}if(r===-1)return e;const i=e[r].value;let s=-1;for(let a=e.length-1;a>=0;a--)if(e[a].value===i){s=a;break}return e.slice(s)}verifyAgentReady(e){if(this.agentInputReady)return;const n=we(e);[/Type (your )?(message|prompt)/i,/Enter (your )?(message|prompt)/i,/Press Enter to send/i,/╭[\s\S]*?╰/m,/┌[\s\S]*?└/m].some(s=>s.test(n))&&(this.agentInputReady=!0,this.sendAgentStatus({agentType:J.CLAUDE_CODE,status:H.IDLE,message:"Agent input box detected. Ready for commands."}),this.executeStartupCommands())}async executeStartupCommands(){if(!this.startupCommandsExecuted&&this.startupCommands.length){this.startupCommandsExecuted=!0;for(const e of this.startupCommands)try{await this.sendInputToAgent(`${e}\r`),await new Promise(n=>setTimeout(n,250))}catch(n){this.logger.warn(`Failed executing startup command: ${e}`,n)}}}handleCtrlC(){return this.ctrlCCount++,this.ctrlCTimeout&&clearTimeout(this.ctrlCTimeout),this.ctrlCCount===1?(this.ctrlCTimeout=setTimeout(()=>{this.ctrlCCount=0,this.ctrlCTimeout=null},this.CTRL_C_RESET_MS),!1):this.ctrlCCount>=2?(this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.ctrlCCount=0,!0):!1}writeMcpConfigFile(e,n){if(!e)return null;try{const r={};if(Array.isArray(e))for(const a of e){if(!a||typeof a!="object")continue;const l=a.name||a.id||a.key;l&&(r[l]={type:a.type||"stdio",command:a.command,args:a.args||a.arguments||[],url:a.url,env:a.env||{},disabled:a.disabled??!1,headers:a.headers||{}})}else if(typeof e=="object")for(const[a,l]of Object.entries(e))l&&typeof l=="object"&&(r[a]={...l,headers:l.headers||{}});if(Object.keys(r).length===0)return null;const i={mcpServers:r},s=`claude-mcps-${n}.json`,o=C.join(ae.tmpdir(),s);return T.writeFileSync(o,JSON.stringify(i,null,2),"utf8"),this.tempMcpConfigPath=o,o}catch(r){return this.logger.warn("Failed to write MCP config file",r),null}}async discoverSubagents(e){const n=[];try{const r=C.join(e,".claude","agents");if(T.existsSync(r)){const o=T.readdirSync(r).filter(a=>a.endsWith(".md"));for(const a of o){const l=C.basename(a,".md");n.push(`${l} (project)`)}}const i=C.join(ae.homedir(),".claude","agents");if(T.existsSync(i)){const o=T.readdirSync(i).filter(a=>a.endsWith(".md"));for(const a of o){const l=C.basename(a,".md");n.some(p=>p.startsWith(`${l} (`))||n.push(`${l} (user)`)}}}catch(r){this.logger.warn("Failed to discover subagents:",r)}return n}async detectClaudeVersion(){try{const{execSync:e}=await import("child_process"),r=e(`${this.claudePath} --version`,{encoding:"utf-8"}).match(/(\d+\.\d+\.\d+)/);if(r){this.claudeVersion=r[1];const[i]=this.claudeVersion.split(".").map(Number);this.supportsSettingsFlag=i>=2,this.logger.info(`Detected Claude Code version ${this.claudeVersion} (--settings flag: ${this.supportsSettingsFlag})`)}}catch(e){this.logger.warn("Failed to detect Claude Code version, assuming legacy version",e),this.supportsSettingsFlag=!1}}async createTempSettingsFile(e){try{const n=[C.join(__dirname,"..","..","dist","claudePostToolUse.js"),C.join(__dirname,"..","dist","claudePostToolUse.js"),C.join(__dirname,"dist","claudePostToolUse.js"),C.join(process.cwd(),"dist","claudePostToolUse.js")];let r=null;for(const a of n)if(T.existsSync(a)){r=a;break}if(!r)return this.logger.warn("PostToolUse hook file not found at any expected location"),null;const i={hooks:{PostToolUse:[{matcher:"*",hooks:[{type:"command",command:`node ${r}`}]}]}},s=`claude-settings-${e}.json`,o=C.join(ae.tmpdir(),s);return await pe.writeFile(o,JSON.stringify(i,null,2),"utf8"),this.tempSettingsPath=o,this.logger.info(`Created temporary settings file at ${o}`),o}catch(n){return this.logger.error(`Failed to create temporary settings file: ${n}`),null}}async addPostToolUseHook(e){const n=C.join(e,".claude","settings.local.json"),r=C.dirname(n);try{await pe.mkdir(r,{recursive:!0});let i={};try{const g=await pe.readFile(n,"utf-8");i=JSON.parse(g)}catch{this.logger.debug("No existing settings.local.json found, creating new one")}i.hooks||(i.hooks={}),i.hooks.PostToolUse||(i.hooks.PostToolUse=[]);let s=null;const o=[C.join(__dirname,"..","..","dist","claudePostToolUse.js"),C.join(__dirname,"..","dist","claudePostToolUse.js"),C.join(__dirname,"dist","claudePostToolUse.js"),C.join(process.cwd(),"dist","claudePostToolUse.js")];for(const g of o)if(T.existsSync(g)){s=g;break}if(!s){this.logger.warn("PostToolUse hook file not found at any expected location");return}const a={matcher:"*",hooks:[{type:"command",command:`node ${s}`}]};i.hooks.PostToolUse.some(g=>g.hooks&&Array.isArray(g.hooks)?g.hooks.some(p=>p.type==="command"&&p.command===`node ${s}`):!1)||(i.hooks.PostToolUse.push(a),await pe.writeFile(n,JSON.stringify(i,null,2)),this.logger.info(`Added PostToolUse hook to ${n}`))}catch(i){this.logger.error(`Failed to add PostToolUse hook: ${i}`)}}async removePostToolUseHook(e){const n=C.join(e,".claude","settings.local.json");try{const r=await pe.readFile(n,"utf-8"),i=JSON.parse(r);if(i.hooks?.PostToolUse){let s=null;const o=[C.join(__dirname,"..","..","dist","claudePostToolUse.js"),C.join(__dirname,"..","dist","claudePostToolUse.js"),C.join(__dirname,"dist","claudePostToolUse.js"),C.join(process.cwd(),"dist","claudePostToolUse.js")];for(const l of o)if(T.existsSync(l)){s=l;break}if(!s)return;const a=`node ${s}`;i.hooks.PostToolUse=i.hooks.PostToolUse.filter(l=>l.hooks&&Array.isArray(l.hooks)?(l.hooks=l.hooks.filter(g=>!(g.type==="command"&&g.command===a)),l.hooks.length>0):!0),i.hooks.PostToolUse.length===0&&delete i.hooks.PostToolUse,Object.keys(i.hooks).length===0&&delete i.hooks,await pe.writeFile(n,JSON.stringify(i,null,2)),this.logger.info(`Removed PostToolUse hook from ${n}`)}}catch(r){this.logger.debug(`Could not remove PostToolUse hook: ${r}`)}}writeSessionSettings(e,n,r,i,s){try{const o=C.join(ae.homedir(),".agiflow"),a=C.join(o,"sessions.json");T.existsSync(o)||T.mkdirSync(o,{recursive:!0});let l={};if(T.existsSync(a))try{l=JSON.parse(T.readFileSync(a,"utf-8"))}catch{this.logger.warn("Invalid sessions.json, creating new one")}l[e]={...n&&{provider:n},...r&&{model:r},...i&&{alias:i},...s&&{reasoningEffort:s}},T.writeFileSync(a,JSON.stringify(l,null,2),"utf-8"),this.logger.info(`Session settings written to ${a}`),n&&r?this.logger.info(`Session: ${i||e} (${n}/${r})`):this.logger.info(`Session: ${i||e} (default Claude)`)}catch(o){this.logger.error("Failed to write session settings",o)}}async launchAgent(e){const{payload:n}=e,r=n.agentSessionId,i=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd();this.startupCommands=n.agentConfig?.commands??[],this.startupCommandsExecuted=!1;const s=n.agentConfig?.xterm??!1;this.setXtermEnabled(s);const o=n.agentConfig?.llmConfig,a=n.agentConfig?.sessionAlias;o?.provider?this.writeSessionSettings(r,o.provider,o.model||"default",a,void 0):this.writeSessionSettings(r,void 0,void 0,a,void 0);const{command:l,args:g}=this.detectClaudeType();this.claudePath=l,this.claudeArgs=g,await this.detectClaudeVersion();const p=n.agentConfig?.hooks?.preAgentStartHooks||n.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(p,i,r),D.SubEnvManager.isContainerMode&&s&&this.setFullscreen(!0),this.serverUrl?this.supportsSettingsFlag?await this.createTempSettingsFile(r):await this.addPostToolUseHook(i):this.logger.info("Running in standalone mode - PostToolUse hook will not be configured");const m=await this.discoverSubagents(i);m.length>0&&this.logger.info(`Discovered ${m.length} Claude subagent(s): ${m.join(", ")}`);const F=this.writeMcpConfigFile(n.agentConfig?.mcps,r),k=C.join(i,".mcp.json");await this.connectToSession(r),await this.setupDockerRepository(e);const u=this.buildClaudeArgs(e),c=[];T.existsSync(k)&&c.push(k),F&&c.push(F),c.length&&u.push("--mcp-config",...c);try{const h=this.getAgentEnvironmentVariables(),d=this.configureNodeOptions(h),f=process.listeners("SIGINT"),_=()=>{this.handleCtrlC()?(this.logger.info("Double Ctrl+C detected, terminating Claude agent..."),process.removeListener("SIGINT",_),f.forEach(P=>{typeof P=="function"&&process.on("SIGINT",P)}),this.ptyRunner.kill("SIGINT")):this.ptyRunner.sendInput("")};process.removeAllListeners("SIGINT"),process.on("SIGINT",_);const O=this.ptyRunner.spawn({command:this.claudePath,args:u,workingDir:i,agentSessionId:r,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{...h,NODE_OPTIONS:d,[D.ENV_KEYS.AGENT_SESSION_ID]:r,[D.ENV_KEYS.AGENT_TYPE]:this.agentType,...F?{CLAUDE_MCP_CONFIG_FILE:F}:{},...n.data?{[D.ENV_KEYS.CONTEXT_DATA]:n.data}:{}}},{onExit:async(x,P)=>{if(process.removeListener("SIGINT",_),f.forEach(M=>{typeof M=="function"&&process.on("SIGINT",M)}),this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.optionTimeout&&(clearTimeout(this.optionTimeout),this.resetOptionState()),this.serverUrl)if(this.supportsSettingsFlag){if(this.tempSettingsPath){try{T.unlinkSync(this.tempSettingsPath),this.logger.info(`Removed temporary settings file: ${this.tempSettingsPath}`)}catch(M){this.logger.warn("Failed to delete temp settings file",M)}this.tempSettingsPath=null}}else await this.removePostToolUseHook(i);if(this.tempMcpConfigPath){try{T.unlinkSync(this.tempMcpConfigPath)}catch(M){this.logger.warn("Failed to delete temp MCP config file",M)}this.tempMcpConfigPath=null}this.logger.info(`Claude Code PTY exited with code ${x}, signal: ${P}`),this.sendAgentStatus({agentType:J.CLAUDE_CODE,status:x===0?H.STOPPED:H.ERROR,message:`Claude Code session ended (exit code: ${x})`}),this.wsService&&this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:P===2?"agent_sigint":"natural",exitCode:x,signal:P})},onData:async x=>{this.processDataForOptions(x),this.verifyAgentReady(x),this.xtermEnabled&&this.sendStdoutEvent(x)}});this.logger.success(`Claude Code launched successfully for session agentSessionId: ${r}`),this.ptySessionId=O.id,s?this.resizePty(80,24):this.setupInitialPtySize();const A={agentSessionId:r,agentType:J.CLAUDE_CODE,status:H.IDLE,workingDir:i,process:O.ptyProcess,metadata:{agentSessionId:r,agentType:n.agentType,config:n.agentConfig,ptySessionId:O.id}};return this.setAgentInfo(A),A}catch(h){throw new Error(`Failed to launch Claude Code: ${h instanceof Error?h.message:String(h)}`)}}async isAvailable(){return!0}async getVersion(){return"claude-pty-agent"}buildClaudeArgs(e){const n=[...this.claudeArgs,...e.payload?.agentConfig?.args||[]],r=e.payload?.agentConfig?.conversationSessionId;return r&&n.push("--session-id",r),this.supportsSettingsFlag&&this.tempSettingsPath&&n.push("--settings",this.tempSettingsPath),n}}class lh{session;logger;constructor(e){this.logger=e??new D.Logger({verbose:!1})}async isDockerAvailable(){return new Promise(e=>{const n=ie.spawn("docker",["--version"],{stdio:"pipe"});n.on("close",r=>{e(r===0)}),n.on("error",()=>{e(!1)})})}spawn(e,n){const r=e.agentSessionId||xn.ulid(),i=e.workingDir??process.cwd(),s=e.dockerImage||"agiflow/claude-agent:latest",o=this.buildDockerArgs(r,e,s),a=`docker ${o.join(" ")}`;this.logger.info(`🐳 Docker Command: ${a}`),this.logger.debug("Spawning Docker container with args:",o);const l=ie.spawn("docker",o,{stdio:["pipe","pipe","pipe"]}),g=`claude-agent-${r}`,p={id:r,dockerProcess:l,containerId:g,command:`docker ${o.join(" ")}`,workingDir:i,status:"running",createdAt:new Date,lastActivity:new Date,logStream:e.logStream};return l.stdout?.on("data",E=>{p.lastActivity=new Date;const m=E.toString();p.logStream&&p.logStream.write(m),process.stdout.write(m),n?.onData&&n.onData(m)}),l.stderr?.on("data",E=>{const m=E.toString();this.logger.error(`🐳 Container ${g} stderr: ${m.trim()}`),process.stderr.write(m)}),l.on("close",E=>{p.status=E===0?"stopped":"error",p.lastActivity=new Date,this.logger.info(`Container ${g} exited with code ${E}`),p.logStream&&p.logStream.end(),n?.onExit&&n.onExit(E||0,void 0)}),l.on("error",E=>{p.status="error",this.logger.error(`Container ${g} error:`,E),n?.onError&&n.onError(E)}),this.session=p,p}buildDockerArgs(e,n,r){const s=["run","--rm","--name",`claude-agent-${e}`,"-i"];if(n.privileged&&s.push("--privileged"),n.user&&s.push("--user",n.user),n.networkMode&&s.push("--network",n.networkMode),n.ports&&n.ports.length>0)for(const m of n.ports)s.push("-p",`${m.host}:${m.container}`);const o=n.agentServerUrl||D.SubEnvManager.serverUrl;s.push("-e",`${D.ENV_KEYS.AGENT_SERVER_URL}=${o}`);const a=n.agentApiKey||D.SubEnvManager.apiKey;a&&s.push("-e",`${D.ENV_KEYS.AGENT_API_KEY}=${a}`);const l=n.agentOrganizationId||D.SubEnvManager.organizationId;l&&s.push("-e",`${D.ENV_KEYS.AGENT_ORGANIZATION_ID}=${l}`);const g=n.agentType||D.SubEnvManager.agentType;g&&s.push("-e",`${D.ENV_KEYS.AGENT_TYPE}=${g}`);const p=e||D.SubEnvManager.sessionId;if(p&&s.push("-e",`${D.ENV_KEYS.AGENT_SESSION_ID}=${p}`),n.additionalEnvVars)for(const[m,F]of Object.entries(n.additionalEnvVars))s.push("-e",`${m}=${F}`);n.workingDir&&(s.push("-v",`${n.workingDir}:/workspace`),s.push("-w","/workspace"));const E=C.join(ae.homedir(),".agiflow");if(ei.existsSync(E)?(s.push("-v",`${E}:/home/node/.agiflow:ro`),this.logger.debug(`Mounting credentials directory: ${E} -> /home/node/.agiflow`)):this.logger.warn(`Credentials directory not found at: ${E}`),n.additionalVolumes&&n.additionalVolumes.length>0)for(const m of n.additionalVolumes){let F;m.type==="volume"?(F=m.readonly?`${m.host}:${m.container}:ro`:`${m.host}:${m.container}`,this.logger.debug(`Mounting named volume: ${m.host} -> ${m.container}`)):(F=m.readonly?`${m.host}:${m.container}:ro`:`${m.host}:${m.container}`,this.logger.debug(`Mounting bind volume: ${m.host} -> ${m.container}`)),s.push("-v",F)}if(D.SubEnvManager.isDebugMode&&s.push("-v","/var/run/docker.sock:/var/run/docker.sock"),s.push(r),s.push("claude"),s.push("--server-url",o),n.agentApiUrl&&s.push("--api-url",n.agentApiUrl),a&&s.push("--api-key",a),l&&s.push("--organization-id",l),p&&s.push("--agent-session-id",p),n.workingDir&&s.push("--working-directory","/workspace"),n.agentConfig){const m=encodeURIComponent(n.agentConfig);s.push("--agent-config",m)}return n.verbose&&s.push("--verbose"),n.args&&n.args.length>0&&s.push("--args",...n.args),s}sendInput(e){if(!this.session?.dockerProcess?.stdin)return this.logger.warn("No active Docker container to send input to"),!1;try{return this.session.dockerProcess.stdin.write(e),this.session.lastActivity=new Date,!0}catch(n){return this.logger.error("Failed to send input to Docker container:",n),!1}}kill(e){if(!this.session?.dockerProcess)return this.logger.warn("No active Docker container to kill"),!1;try{return this.logger.info(`Stopping Docker container: ${this.session.containerId}`),this.session.dockerProcess.kill(e||"SIGTERM"),setTimeout(()=>{this.session.dockerProcess&&!this.session.dockerProcess.killed&&(this.logger.warn(`Force killing container ${this.session.containerId}`),this.session.dockerProcess.kill("SIGKILL"))},5e3),this.session.status="stopped",!0}catch(n){return this.logger.error(`Failed to kill Docker container: ${n}`),!1}}getSession(){return this.session}isSessionRunning(){return this.session?.status==="running"}}class hh{agentType;serverUrl;apiKey;verbose;organizationId;logger;terminationService;dockerImage;onFullscreenChange;dockerRunner;agentInfo=null;isFullscreen=!1;backgroundOutputBuffer=[];BACKGROUND_BUFFER_SIZE=5;BACKGROUND_CHUNK_MAX_SIZE=2048;constructor(e){this.agentType=e.agentType,this.serverUrl=e.serverUrl,this.apiKey=e.apiKey,this.verbose=e.verbose??!1,this.organizationId=e.organizationId,this.logger=e.logger??new D.Logger({verbose:this.verbose}),this.terminationService=e.terminationService??new Le(this.logger),this.dockerImage=e.dockerImage||"agiflow/agent:latest",this.onFullscreenChange=e.onFullscreenChange,this.dockerRunner=new lh(this.logger)}async isAvailable(){return await this.dockerRunner.isDockerAvailable()}getAgentInfo(){return this.agentInfo}setAgentInfo(e){this.agentInfo=e}getAgentEnvironmentVariables(){const e={};for(const[n,r]of Object.entries(process.env))r!==void 0&&(e[n]=r);return this.apiKey&&(e[D.ENV_KEYS.AGENT_API_KEY]=this.apiKey),this.organizationId&&(e[D.ENV_KEYS.AGENT_ORGANIZATION_ID]=this.organizationId),this.serverUrl&&(e[D.ENV_KEYS.AGENT_SERVER_URL]=this.serverUrl),e[D.ENV_KEYS.AGENT_TYPE]=this.agentType,e[D.ENV_KEYS.VERBOSE]=this.verbose?"true":"false",e}addToBackgroundBuffer(e){const n=e.length>this.BACKGROUND_CHUNK_MAX_SIZE?e.substring(e.length-this.BACKGROUND_CHUNK_MAX_SIZE):e;this.backgroundOutputBuffer.push(n),this.backgroundOutputBuffer.length>this.BACKGROUND_BUFFER_SIZE&&this.backgroundOutputBuffer.shift(),this.logger.debug(`🐳 Added ${n.length} chars to Docker background buffer (${this.backgroundOutputBuffer.length}/${this.BACKGROUND_BUFFER_SIZE} chunks)`)}flushBackgroundBuffer(){if(this.backgroundOutputBuffer.length===0)return;this.logger.debug(`🐳 Flushing Docker background buffer: ${this.backgroundOutputBuffer.length} chunks`);const e=this.backgroundOutputBuffer.join("");e&&(console.log(e),this.logger.debug(`🐳 Docker background buffer flushed: ${e.length} chars`)),this.backgroundOutputBuffer=[]}setFullscreen(e,n=!1){const r=this.isFullscreen;this.isFullscreen=e,this.logger.debug(`Docker agent fullscreen mode ${e?"enabled":"disabled"}`),e&&!r&&this.agentInfo&&this.flushBackgroundBuffer(),!n&&r!==e&&this.agentInfo&&this.onFullscreenChange&&this.onFullscreenChange(this.agentInfo.agentSessionId,e)}getFullscreen(){return this.isFullscreen}disconnect(){this.logger.info(`Disconnecting ${this.agentType} Docker agent`),this.dockerRunner.kill("SIGTERM"),this.agentInfo=null}}class Or extends hh{onBeforeTerminate;constructor(e){super({...e,agentType:J.CLAUDE_CODE,dockerImage:e.dockerImage||ue.VITE_AGENT_CLI_DOCKER_IMAGE}),this.onBeforeTerminate=e.onBeforeTerminate}async getVersion(){return"claude-docker-agent"}async launchAgent(e){const{payload:n}=e,r=n.agentSessionId,i=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd();if(!await this.isAvailable())throw new Error("Docker is not available. Please install Docker to use containerized agents.");this.logger.info(`Launching Claude agent in Docker container for session: ${r}`);const s=this.getDockerOptions(e);try{const o=this.dockerRunner.spawn(s,{onExit:async(l,g)=>{if(this.logger.info(`Docker Claude agent exited with code ${l}, signal: ${g}`),this.onBeforeTerminate)try{this.logger.info("Executing cleanup callback before termination..."),await this.onBeforeTerminate(),this.logger.info("Cleanup callback completed successfully")}catch(p){this.logger.error("Error during cleanup callback:",p)}this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:g===2?"agent_sigint":"natural",exitCode:l,signal:g})},onData:async l=>{this.logger.debug("Docker container output:",l)},onError:l=>{this.logger.error("Docker container error:",l)}});this.logger.success(`Docker Claude agent launched successfully for session: ${r}`);const a={agentSessionId:r,agentType:J.CLAUDE_CODE,status:H.IDLE,workingDir:i,containerId:o.containerId,dockerSessionId:o.id,process:o.dockerProcess,metadata:{agentSessionId:r,agentType:n.agentType,config:n.agentConfig,docker:!0,containerId:o.containerId,dockerSessionId:o.id}};return this.setAgentInfo(a),a}catch(o){throw new Error(`Failed to launch Claude Docker agent: ${o instanceof Error?o.message:String(o)}`)}}disconnect(){this.logger.info("Disconnecting Claude Docker agent");try{this.dockerRunner.isSessionRunning()&&(this.dockerRunner.kill("SIGTERM"),setTimeout(()=>{this.dockerRunner.isSessionRunning()&&(this.logger.warn("Force killing Docker container..."),this.dockerRunner.kill("SIGKILL"))},3e3)),this.agentInfo=null,this.logger.info("Claude Docker agent disconnected successfully")}catch(e){this.logger.error("Error during Docker agent disconnect:",e)}}getDockerOptions(e){const{payload:n}=e,r=n.agentSessionId,i=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd(),s=ue.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT||this.serverUrl,o=s?s.replace(/^http/,"ws"):void 0;let a=null;n.agentConfig?.mcps&&(a=this.processAgentConfig(n.agentConfig.mcps));const l={...n.agentConfig,workingDirectory:"/workspace"};return a&&(l.mcps=a),{agentSessionId:r,dockerImage:n.agentConfig?.dockerImage||this.dockerImage,workingDir:i,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:o,agentApiUrl:s,agentType:J.CLAUDE_CODE,agentConfig:JSON.stringify(l),verbose:this.verbose,additionalEnvVars:{[D.ENV_KEYS.NODE_ENV]:D.SubEnvManager.nodeEnv,[D.ENV_KEYS.AGENT_SESSION_ID]:r,[D.ENV_KEYS.AGENT_CONTAINER_MODE]:D.SubEnvManager.isContainerMode?"true":"false",IS_SANDBOX:"1"},additionalVolumes:this.getAdditionalVolumes(n),networkMode:ue.VITE_AGENT_CLI_DOCKER_NETWORK,user:void 0}}getAdditionalVolumes(e){const n=[],r=D.SubEnvManager.homeDir;if(r)if(n.push({host:`${r}/.ssh`,container:"/root/.ssh",readonly:!0,type:"bind"}),n.push({host:"agiflow-pnpm-cache",container:"/root/.pnpm-store",readonly:!1,type:"volume"}),n.push({host:"agiflow-npm-cache",container:"/root/.npm",readonly:!1,type:"volume"}),n.push({host:"agiflow-node-gyp-cache",container:"/root/.cache/node-gyp",readonly:!1,type:"volume"}),D.SubEnvManager.isMacOS){const s=`${r}/.claude_tmp.json`;T.existsSync(s)||T.writeFileSync(s,"{}","utf8"),n.push({host:s,container:"/root/.claude.json",readonly:!1,type:"bind"});const o=`${r}/.claude_tmp`;T.existsSync(o)||T.mkdirSync(o,{recursive:!0}),n.push({host:o,container:"/root/.claude",readonly:!1,type:"bind"})}else{const s=`${r}/.claude.json`;T.existsSync(s)||T.writeFileSync(s,"{}","utf8"),n.push({host:s,container:"/root/.claude.json",readonly:!1,type:"bind"});const o=`${r}/.claude`;T.existsSync(o)||T.mkdirSync(o,{recursive:!0}),n.push({host:o,container:"/root/.claude",readonly:!1,type:"bind"})}return n}async sendInputToAgent(e){this.logger.debug("sendInputToAgent called on Docker agent - no action needed")}getContainerStatus(){const e=this.dockerRunner.getSession();return{isRunning:this.dockerRunner.isSessionRunning(),containerId:e?.containerId,status:e?.status,lastActivity:e?.lastActivity}}async isHealthy(){try{return!!this.dockerRunner.isSessionRunning()}catch(e){return this.logger.error("Health check failed:",e),!1}}getDockerSession(){return this.dockerRunner.getSession()}processAgentConfig(e){const n={};if(Array.isArray(e))for(const r of e){if(!r||typeof r!="object")continue;const i=r.name||r.id||r.key;i&&(n[i]={type:r.type||"stdio",command:r.command,args:r.args||r.arguments||[],url:r.url,env:r.env||{},disabled:r.disabled??!1,headers:r.headers||{}})}else if(typeof e=="object")for(const[r,i]of Object.entries(e))i&&typeof i=="object"&&(n[r]={...i,headers:i.headers||{}});return n}}class xr extends ze{register(e){e.command("claude").description("Launch Claude Code agent with full functionality").option("-s, --server-url <url>","WebSocket server URL").option("-a, --api-url <url>","HTTP API URL").option("-k, --api-key <key>","API key for authentication").option("-o, --organization-id <id>","Organization ID").option("-v, --verbose","Enable verbose logging",!1).option("-p, --claude-path <path>","Path to Claude executable","claude").option("-w, --working-directory <dir>","Working directory",process.cwd()).option("-i, --agent-session-id <id>","Agent session ID").option("-c, --agent-config <json>","Agent configuration as JSON string").option("--args <args...>","Additional arguments to pass to Claude").option("--docker","Run Claude agent in Docker container",!1).option("--docker-image <image>","Docker image to use for containerized agent").option("--llm-provider <provider>","LLM provider to route requests to (e.g., openai)").option("--llm-model <model>","LLM model to use (e.g., gpt-4-turbo, gpt-5)").option("--alias <alias>","Custom session alias for easy identification").action(async n=>{try{await this.execute(n)}catch(r){this.handleError(r)}})}async execute(e){let n;if(e.llmProvider){const c=["codex","gpt","openai","chatgpt"],h=e.llmProvider.toLowerCase();c.includes(h)||(this.error(`Invalid LLM provider: ${e.llmProvider}`),this.error(`Allowed providers: ${c.join(", ")}`),process.exit(1)),n={provider:h,model:e.llmModel}}const r=e.serverUrl||ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT,i=e.apiUrl||ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT,s=e.apiKey||D.SubEnvManager.apiKey,o=e.organizationId||D.SubEnvManager.organizationId;let a=e.agentSessionId||D.SubEnvManager.sessionId;if(a||(a=On.randomUUID(),e.verbose&&this.info(`Generated session ID: ${a}`)),!r)e.verbose&&(this.info("Running in standalone mode (no WebSocket connection)"),this.info("Agent will launch without remote connectivity"));else try{new URL(r)}catch{this.error("Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://)."),process.exit(1)}if(i)try{new URL(i)}catch{this.error("Invalid API URL. Must be a valid HTTP URL."),process.exit(1)}else!r&&e.verbose&&this.info("No API URL provided - HTTP features will be unavailable");const l=()=>{const h=new Date().toISOString().replace(/[-:]/g,"").replace("T","-").split(".")[0],d=e.llmProvider||"claude",f=e.llmModel?.replace(/[^a-z0-9]/gi,"")||"default";return`${d}-${f}-${h}`},g=e.alias||l(),p=new D.Logger({verbose:e.verbose});e.verbose&&(this.info(`Starting Claude agent${e.docker?" in Docker container":""}...`),this.info(`Session: ${g} (ID: ${a})`),p.debug("Options:",e),e.llmProvider&&this.info(`LLM Routing enabled: ${e.llmProvider} → ${e.llmModel||"default model"}`));const E=new D.CredentialsService,m=new Le(p),F=e.docker?new Or({agentType:J.CLAUDE_CODE,serverUrl:r,apiKey:s,organizationId:o,verbose:e.verbose,dockerImage:e.dockerImage,logger:p,terminationService:m}):new $r({agentType:J.CLAUDE_CODE,serverUrl:r,apiUrl:i,apiKey:s,organizationId:o,verbose:e.verbose,claudePath:e.claudePath,standalone:!0,logger:p,credentialsService:E,terminationService:m});let k={workingDirectory:e.workingDirectory?D.FileSystemUtils.getAbsolutePath(e.workingDirectory):process.cwd(),args:e.args||[],sessionAlias:g,...n&&{llmConfig:n}};if(e.agentConfig)try{const c=decodeURIComponent(e.agentConfig),h=JSON.parse(c);k={...k,...h}}catch(c){try{const h=JSON.parse(e.agentConfig);k={...k,...h}}catch{this.error(`Failed to parse agent config JSON: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}}const u=zt.parse({payload:{sessionId:a,agentType:J.CLAUDE_CODE,agentSessionId:a,agentConfig:k}});try{await F.launchAgent(u),this.success(`Claude agent${e.docker?" (Docker)":""} launched successfully for session: ${g}`);const c=async h=>{e.verbose&&this.info(`Received ${h}, shutting down Claude agent${e.docker?" container":""}...`);try{F.disconnect(),this.info(`Claude agent${e.docker?" container":""} shutdown complete`),process.exit(0)}catch(d){this.error(`Error during shutdown: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}};process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),this.info(`Claude agent${e.docker?" container":""} is running. Press Ctrl+C to stop.`),await new Promise(()=>{})}catch(c){this.error(`Failed to start Claude agent: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}}}const dh=Qr.promisify(ie.exec);class gh{claudeAgentsPath;constructor(e={}){this.claudeAgentsPath=e.claudeAgentsPath||C.join(ae.homedir(),".claude","agents")}async findAgentsDirectory(){const e=C.join(process.cwd(),".claude","agents");try{if((await T.promises.stat(e)).isDirectory())return e}catch{}try{if((await T.promises.stat(this.claudeAgentsPath)).isDirectory())return this.claudeAgentsPath}catch{}try{const n=ae.homedir(),r=[`"${n}/.config"`,`"${n}/.local"`,`"${n}/workspace"`,`"${n}/projects"`,`"${n}/dev"`,`"${n}/code"`,`"${n}/.claude"`,`"${n}"`];for(const i of r)try{const o=i===`"${n}"`?1:5,a=`find ${i} -maxdepth ${o} -type d -name "agents" -path "*/.claude/agents" 2>/dev/null | head -1`,{stdout:l}=await dh(a),g=l.trim();if(g&&g.length>0&&(await T.promises.stat(g)).isDirectory())return g}catch{}}catch(n){console.error("Error searching for .claude/agents directory:",n)}return null}async listAgentFiles(){const e=await this.findAgentsDirectory();if(!e)return[];try{return(await T.promises.readdir(e)).filter(r=>r.endsWith(".md")).map(r=>C.join(e,r))}catch(n){return console.error("Error reading agents directory:",n),[]}}async parseAgentFile(e){try{const n=await T.promises.readFile(e,"utf-8");return this.parseAgentContent(n,e)}catch(n){return console.error(`Error reading agent file ${e}:`,n),null}}parseAgentContent(e,n){const r=e.split(`
78
- `),i=r.findIndex(p=>p.trim()==="---"),s=r.findIndex((p,E)=>E>i&&p.trim()==="---");if(i===-1||s===-1)return console.error(`Invalid frontmatter in ${n}`),null;const o=r.slice(i+1,s),a={};for(const p of o){const E=p.indexOf(":");if(E>0){const m=p.substring(0,E).trim(),F=p.substring(E+1).trim();a[m]=F}}const g=r.slice(s+1).join(`
79
- `).trim();return!a.name||!a.description?(console.error(`Missing required fields in ${n}`),null):{name:a.name,description:a.description,color:a.color||"default",prompt:g,filePath:n}}async getAllAgentProfiles(){const e=await this.listAgentFiles(),n=[];for(const r of e){const i=await this.parseAgentFile(r);i&&n.push(i)}return n}async getAgentProfile(e){return(await this.getAllAgentProfiles()).find(r=>r.name===e)||null}async searchAgentProfiles(e){const n=await this.getAllAgentProfiles(),r=e.toLowerCase();return n.filter(i=>i.name.toLowerCase().includes(r)||i.description.toLowerCase().includes(r))}}class Mt{options;apiKeyPath;logger;constructor(e){this.options=e,this.logger=e.logger||new D.Logger({verbose:e.verbose||!1}),this.apiKeyPath=C.join(D.FileSystemUtils.AGIFLOW_DIR,"api-key.json")}async getValidApiKey(){try{const e=await this.loadApiKey();if(e&&this.isTokenValid(e.expires_at))return this.logger.info("Using existing API key"),e;this.logger.info("Starting device code authentication flow...");const n=await this.performDeviceCodeFlow();return await this.storeApiKey(n),n}catch(e){throw new Error(`Authentication failed: ${e instanceof Error?e.message:e}`)}}async performDeviceCodeFlow(){const e=await fetch(`${this.options.baseUrl}/api/v1/oauth/device/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.options.clientId,scope:"openid profile email"})});if(!e.ok){const l=await e.text();throw new Error(`Device authorization failed: ${e.status} ${l}`)}const n=await e.json(),r=`${n.verification_uri}?code=${encodeURIComponent(n.user_code)}`;this.logger.info("To authenticate your CLI:"),this.logger.info(`1. Open (or we opened): ${r}`),this.logger.info("2. Sign in (if needed) and confirm device authorization"),this.logger.info("3. Copy the verification token (JWT) shown after confirmation"),this.logger.info("4. Paste it below to complete authentication"),this.logger.info(""),this.logger.info(`User Code: ${n.user_code}`);const i=await et.input({message:"Paste verification token (JWT):",validate:l=>!l||l.trim().split(".").length!==3?"Invalid verification token format. Please enter a valid JWT token.":!0}),s=await fetch(`${this.options.baseUrl}/api/v1/oauth/device/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:n.device_code,verification_token:i.trim(),client_id:this.options.clientId})});if(!s.ok){const l=await s.text();throw new Error(`Token exchange failed: ${s.status} ${l}`)}const o=await s.json();if(!o.api_key)throw new Error("Token exchange response missing api_key");if(!o.organization_id)throw new Error("Token exchange response missing organization_id");this.logger.success(`Authentication successful!
80
- `);const a={api_key:o.api_key,key_id:"device-flow",expires_at:Date.now()+o.expires_in*1e3,organization_id:o.organization_id,prefix:"agiflow_"};return await this.checkAndOfferAgentProfiles(a),a}async loadApiKey(){try{return await D.FileSystemUtils.exists(this.apiKeyPath)?await D.FileSystemUtils.readJson(this.apiKeyPath):null}catch{return null}}async storeApiKey(e){await this.ensureAgiflowDir(),await D.FileSystemUtils.writeJson(this.apiKeyPath,e),this.logger.debug(`API key stored at ${this.apiKeyPath}`)}async ensureAgiflowDir(){await D.FileSystemUtils.ensureDir(D.FileSystemUtils.AGIFLOW_DIR)}isTokenValid(e){return Date.now()<e-3e5}async clearTokens(){try{await D.FileSystemUtils.exists(this.apiKeyPath)&&await D.FileSystemUtils.remove(this.apiKeyPath)}catch{}this.logger.debug("Cleared stored tokens")}async getOrganizationId(){return(await this.loadApiKey())?.organization_id||null}async getDeviceId(){return(await this.loadApiKey())?.device_id||null}async updateDeviceId(e){const n=await this.loadApiKey();n&&(n.device_id=e,await this.storeApiKey(n),this.logger.debug(`Updated device ID in stored API key: ${e}`))}async checkAndOfferAgentProfiles(e){try{this.logger.info("Checking for local agent profiles...");const r=await new gh().getAllAgentProfiles();if(r.length===0){this.logger.info("No local agent profiles found.");return}this.logger.info(`Found ${r.length} local agent profile(s):`),r.forEach((s,o)=>{this.logger.info(` ${o+1}. ${s.name} - ${s.description.substring(0,80)}...`)}),await et.confirm({message:"Would you like to add these agent profiles to your organization?",default:!1})?await this.uploadAgentProfiles(r,e):this.logger.info("Skipping agent profile upload.")}catch(n){this.logger.warn(`Could not check agent profiles: ${n instanceof Error?n.message:n}`)}}async uploadAgentProfiles(e,n){this.logger.info("Uploading agent profiles to organization...");try{const r=await fetch(`${this.options.baseUrl}/api/v1/organizations/${n.organization_id}/members/agents`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":n.api_key},body:JSON.stringify({agents:e.map(i=>({name:i.name,description:i.description,prompt:i.prompt}))})});if(r.ok){const i=await r.json(),s=i.created?.length||0,o=i.errors?.length||0;s>0&&(this.logger.success(`Successfully uploaded ${s} agent profile(s) to your organization!`),i.created.forEach(a=>{this.logger.info(`✅ Created: ${a.user.name}`)})),o>0&&(this.logger.warn(`Failed to upload ${o} agent profile(s):`),i.errors.forEach(a=>{this.logger.warn(`❌ ${a.name}: ${a.error}`)}))}else{const i=await r.text();this.logger.warn(`❌ Failed to upload agent profiles: ${r.status} ${i}`)}}catch(r){this.logger.warn(`❌ Error uploading agent profiles: ${r instanceof Error?r.message:r}`)}}}class fh{permits;waitQueue=[];constructor(e=1){this.permits=e}async acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>{this.waitQueue.push(e)})}release(){if(this.waitQueue.length>0){const e=this.waitQueue.shift();e&&e()}else this.permits++}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}get available(){return this.permits}get waiting(){return this.waitQueue.length}}class ph{semaphores=new Map;permits;constructor(e=1){this.permits=e}getSemaphore(e){let n=this.semaphores.get(e);return n||(n=new fh(this.permits),this.semaphores.set(e,n)),n}async acquire(e){return this.getSemaphore(e).acquire()}release(e){const n=this.semaphores.get(e);n&&(n.release(),n.available===this.permits&&n.waiting===0&&this.semaphores.delete(e))}async runExclusive(e,n){return this.getSemaphore(e).runExclusive(n)}isLocked(e){const n=this.semaphores.get(e);return n?n.available===0:!1}clear(){this.semaphores.clear()}}class mh extends Ir{geminiPath;tempExtensionConfigPath=null;agentInputReady=!1;optionBuffer="";optionTimeout=null;isCollectingOptions=!1;OPTION_WAIT_MS=1e3;constructor(e){super({...e,agentType:J.GEMINI_CLI}),this.geminiPath=e.geminiPath||"gemini"}async launchAgent(e){const{payload:n}=e,r=n.agentSessionId,i=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd(),s=n.agentConfig?.xterm??!1;this.setXtermEnabled(s);const o=n.agentConfig?.hooks?.preAgentStartHooks||n.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(o,i,r),this.logger.debug("Agent config MCPs:",n.agentConfig?.mcps);const a=await this.writeGeminiExtensionFile(n.agentConfig?.mcps,i);this.logger.debug("Custom Gemini extension config result:",a);const l=C.join(i,"agiflow-extension.json");this.logger.debug("Project Gemini extension config path:",l),await this.connectToSession(r),await this.setupDockerRepository(e);const g=this.buildGeminiArgs(e);T.existsSync(l)?this.logger.debug(`Found project Gemini extension config: ${l}`):this.logger.debug("No project agiflow-extension.json found in working directory"),a&&this.logger.debug(`Created Gemini extension config: ${a}`);try{const p=this.getAgentEnvironmentVariables(),E=this.configureNodeOptions(p),m=this.ptyRunner.spawn({command:this.geminiPath,args:g,workingDir:i,agentSessionId:r,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{...p,NODE_OPTIONS:E,GEMINI_SESSION_ID:r,GEMINI_AGENT_SESSION_ID:r,GEMINI_AGENT_MODE:"true",...a?{GEMINI_EXTENSION_CONFIG_FILE:a}:{}}},{onData:async k=>{this.verifyAgentReady(k),this.processDataForOptions(k),this.xtermEnabled&&this.sendStdoutEvent(k)},onExit:async(k,u)=>{if(this.tempExtensionConfigPath){try{T.unlinkSync(this.tempExtensionConfigPath),this.logger.debug(`Deleted temp Gemini extension config file: ${this.tempExtensionConfigPath}`)}catch(c){this.logger.warn("Failed to delete temp Gemini extension config file",c)}this.tempExtensionConfigPath=null}this.logger.info(`Gemini PTY exited with code ${k}, signal: ${u}`),this.sendAgentStatus({agentType:J.GEMINI_CLI,status:k===0?H.STOPPED:H.ERROR,message:`Gemini session ended (exit code: ${k})`}),this.wsService&&this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:"natural",exitCode:k,signal:u})}});this.logger.success(`Gemini launched successfully for session agentSessionId: ${r}`),this.ptySessionId=m.id,s?this.resizePty(80,24):this.setupInitialPtySize();const F={agentSessionId:r,agentType:J.GEMINI_CLI,status:H.IDLE,workingDir:i,process:m.ptyProcess,metadata:{agentSessionId:r,agentType:n.agentType,config:n.agentConfig,ptySessionId:m.id}};return this.setAgentInfo(F),F}catch(p){throw new Error(`Failed to launch Gemini: ${p instanceof Error?p.message:String(p)}`)}}async isAvailable(){return!0}async getVersion(){return"gemini-pty-agent"}verifyAgentReady(e){if(this.agentInputReady)return;const r=(o=>o.replace(/\x1b\[[0-9;]*m/g,""))(e);[/Type (your )?(message|prompt)/i,/Enter (your )?(message|command)/i,/gemini>/i,/Ready for input/i,/Session started/i,/╭[\s\S]*?╰/m,/┌[\s\S]*?└/m,/>/].some(o=>o.test(r))&&(this.agentInputReady=!0,this.logger.debug("Gemini agent detected as ready for input"),this.sendAgentStatus({agentType:J.GEMINI_CLI,status:H.IDLE,message:"Gemini ready for commands"}))}buildGeminiArgs(e){const n=e.payload?.agentConfig?.args||[],r=e.payload?.agentConfig?.conversationSessionId;return r&&n.push("--session-id",r),n}processDataForOptions(e){this.optionBuffer+=e;const n=we(e);(/Do you want to proceed\?/m.test(n)||/●\s*\d+\.\s+/.test(n)||/\n\s{0,4}\d+\.\s+[^\n]+/.test(n))&&!this.isCollectingOptions&&this.startOptionCollection()}startOptionCollection(){this.isCollectingOptions=!0,this.optionTimeout&&clearTimeout(this.optionTimeout),this.optionTimeout=setTimeout(()=>{this.processCollectedOptions()},this.OPTION_WAIT_MS)}async processCollectedOptions(){const e=we(this.optionBuffer),n=this.extractOptions(e);n.length&&await this.handleDetectedOptions(n),this.resetOptionState()}resetOptionState(){this.optionBuffer="",this.optionTimeout=null,this.isCollectingOptions=!1}extractOptions(e){const n=[],r=e.split(`
81
- `);for(const s of r){const o=s.trim();let a=o.match(/^●\s*(\d+)\.\s+(.+)$/);if(a){n.push({number:parseInt(a[1],10),text:a[2].trim(),selected:!0});continue}a=o.match(/^(?:[│|]?\s*)?(\d+)\.\s+(.+)$/),a&&n.push({number:parseInt(a[1],10),text:a[2].trim()})}const i=new Set;return n.filter(s=>i.has(s.number)?!1:(i.add(s.number),!0))}async handleDetectedOptions(e){if(!e.length||!this.agentInfo||!this.httpService)return;const n=new Date().toISOString();try{const r=e.map(a=>({label:a.text,value:a.number,selected:!!a.selected})),i=D.createSelectComponent(r),s=D.createToolInvocationInput(!1,i),o=[D.createTextPart("Gemini has detected available options. Please select one:"),D.createToolInvocationPart({toolName:"selectOption",toolCallId:`gemini-option-selection-${Date.now()}`,args:{timestamp:n},state:"call"},s)];await this.httpService.sendMessage({sessionId:this.agentInfo.agentSessionId,messageType:"output",parts:o,metadata:{optionDetection:!0,optionsCount:e.length,timestamp:n}}),this.logger.debug("Sent structured Gemini options message")}catch(r){this.logger.warn("Failed to send Gemini options message",r)}}async writeGeminiExtensionFile(e,n){if(this.logger.debug("writeGeminiExtensionFile called",{rawMcps:e,workingDir:n}),!e)return this.logger.debug("No MCPs provided, returning null"),null;try{const r={};if(Array.isArray(e))for(const p of e){if(!p||typeof p!="object")continue;const E=p.name||p.id||p.key;if(!E)continue;const m={};p.type==="sse"?(m.url=p.url,p.headers&&Object.keys(p.headers).length>0&&(m.headers=p.headers)):(m.command=p.command,p.args&&p.args.length>0&&(m.args=p.args)),p.env&&Object.keys(p.env).length>0&&(m.env=p.env),p.disabled&&(m.disabled=p.disabled),r[E]=m}else if(typeof e=="object"){for(const[p,E]of Object.entries(e))if(E&&typeof E=="object"){const m=E,F={};m.type==="sse"||m.url?(F.url=m.url,m.headers&&Object.keys(m.headers).length>0&&(F.headers=m.headers)):(F.command=m.command,m.args&&m.args.length>0&&(F.args=m.args)),m.env&&Object.keys(m.env).length>0&&(F.env=m.env),m.disabled&&(F.disabled=m.disabled),r[p]=F}}if(Object.keys(r).length===0)return null;const i=await this.findGitRepoRoot(n),s=i||ae.homedir();this.logger.debug(`Using base directory for Gemini extension: ${s}`);const o=C.join(s,".gemini","extensions");T.existsSync(o)||(T.mkdirSync(o,{recursive:!0}),this.logger.debug(`Created directory: ${o}`));const a={name:"agiflow-mcps",version:"1.0.0",mcpServers:r,contextFileName:"GEMINI.md",excludeTools:["run_shell_command"]},g=C.join(o,"agiflow-extension.json");return T.writeFileSync(g,JSON.stringify(a,null,2),"utf8"),this.logger.debug(`Gemini extension config written to: ${g}`),this.tempExtensionConfigPath=g,i&&await this.ensureGitignoreEntry(i,".gemini/extensions/agiflow-extension.json"),g}catch(r){return this.logger.warn("Failed to write Gemini extension config file",r),null}}async findGitRepoRoot(e){let n=C.resolve(e);const r=C.parse(n).root;for(;n!==r;){const i=C.join(n,".git");if(T.existsSync(i))return n;n=C.dirname(n)}return null}async ensureGitignoreEntry(e,n){const r=C.join(e,".gitignore");try{let i="";if(T.existsSync(r)&&(i=T.readFileSync(r,"utf8")),i.split(`
82
- `).some(a=>a.trim()===n))this.logger.debug(`Entry '${n}' already exists in .gitignore`);else{const a=i.endsWith(`
83
- `)||i===""?i+n+`
84
- `:i+`
85
- `+n+`
86
- `;T.writeFileSync(r,a,"utf8"),this.logger.debug(`Added '${n}' to .gitignore`)}}catch(i){this.logger.warn(`Failed to update .gitignore: ${i instanceof Error?i.message:String(i)}`)}}}class Dh{logger;repositoryPath;originalRepositoryPath;activeWorktrees=new Map;canPush=null;constructor(e,n){if(this.originalRepositoryPath=C.resolve(e),this.repositoryPath=this.originalRepositoryPath,this.logger=n??new D.Logger({verbose:!1}),!this.isGitRepository())throw new Error(`Path ${this.originalRepositoryPath} is not a git repository`)}isGitRepository(){try{let e=C.resolve(this.repositoryPath);const n=C.resolve("/");let r=0;const i=15;for(;e!==n&&r<i;){const s=C.join(e,".git");if(T.existsSync(s))return this.repositoryPath=e,!0;const o=C.resolve(e,"..");if(o===e)break;e=o,r++}return!1}catch{return!1}}execGit(e,n){try{return ie.execSync(`git ${e}`,{cwd:n||this.repositoryPath,encoding:"utf8",stdio:"pipe"}).trim()}catch(r){this.logger.error(`Git command failed: git ${e}`,r);const i=new Error(`Git command failed: ${r.message}`);throw i.status=r.status,i.signal=r.signal,i.output=r.output,i}}getCurrentBranch(){return this.execGit("branch --show-current")}getCurrentCommit(){return this.execGit("rev-parse HEAD")}listWorktrees(){try{const e=this.execGit("worktree list --porcelain"),n=[],r=e.split(`
87
-
88
- `).filter(i=>i.trim());for(const i of r){const s=i.split(`
89
- `);let o="",a="",l="";for(const g of s)g.startsWith("worktree ")?o=g.substring(9):g.startsWith("branch ")?a=g.substring(7):g.startsWith("HEAD ")&&(l=g.substring(5));o&&n.push({path:o,branch:a||"detached",commit:l,isActive:o===this.repositoryPath,name:C.basename(o)})}return n}catch{return this.logger.debug("No worktrees found or git worktree not supported"),[]}}async createWorktree(e){const{branch:n,worktreeName:r}=e,i=this.repositoryPath,s=C.basename(i),o=n||this.generateUniqueBranchName(),a=this.sanitizeBranchName(o),l=`${s}-worktrees`,g=r||a,p=C.join(this.repositoryPath,".."),E=C.join(p,l),m=C.join(E,g);T.existsSync(E)||await(await import("fs/promises")).mkdir(E,{recursive:!0});try{let F=`worktree add "${m}"`;if(this.isBranchCheckedOutInWorktree(o))throw new Error(`Branch '${o}' is already checked out in another worktree. Use a different branch name or specify a unique branch.`);const k=this.checkBranchExists(`refs/heads/${o}`);let u=!1;k?F+=` ${o}`:(u=this.checkBranchExists(`refs/remotes/origin/${o}`),u?F+=` -b ${o} origin/${o}`:F+=` -b ${o}`),this.logger.info(`Creating worktree at ${m}`),this.execGit(F);const c=this.execGit("rev-parse HEAD",m),h=o||this.execGit("branch --show-current",m),d={path:m,branch:h,commit:c,isActive:!1,name:g};if(this.activeWorktrees.set(g,d),this.logger.success(`Worktree created successfully at ${m}`),!k&&!u)try{this.logger.info(`Pushing new branch ${h} to remote`),this.execGit(`push --set-upstream origin ${h}`,m),this.logger.success(`Branch ${h} pushed to remote`)}catch(f){this.logger.warn(`Could not push branch to remote: ${f.message}`)}return d}catch(F){throw this.logger.error(`Failed to create worktree: ${F.message}`),F}}async commitChanges(e,n,r=!0,i=!1){try{try{this.execGit("clean -fd -e node_modules",e)}catch(o){this.logger.debug("Git clean warning (non-fatal):",o)}r&&(this.execGit("add -u",e),this.execGit("add .",e));try{this.execGit("diff --cached --exit-code",e),this.logger.info("No changes to commit in worktree");return}catch(o){if(o.status!==1)throw o}const s=i?"--no-verify":"";this.execGit(`commit ${s} -m "${n}"`.trim(),e),this.logger.success(`Changes committed in worktree: ${e}`)}catch(s){throw this.logger.error(`Failed to commit changes: ${s.message}`),s}}async pushChanges(e,n="origin",r){if(!await this.canPushToRemote(n))throw new Error(`Cannot push to remote '${n}' - no valid authentication method found. Please set up SSH keys or store HTTPS credentials.`);try{const s=r||this.execGit("branch --show-current",e);if(!s)throw new Error("No branch to push (detached HEAD)");try{this.logger.debug(`Pushing branch ${s} to ${n}`),this.execGit(`push --set-upstream ${n} ${s}`,e)}catch{try{this.logger.debug(`Retrying push without --set-upstream for ${s}`),this.execGit(`push ${n} ${s}`,e)}catch(a){const l=a.message||"";throw l.includes("permission")||l.includes("denied")?this.logger.error(`Push failed: No permission to push to ${n}/${s}`):l.includes("Could not read from remote repository")?this.logger.error("Push failed: Cannot access remote repository. Check your SSH keys or credentials."):l.includes("does not appear to be a git repository")?this.logger.error(`Push failed: Remote '${n}' is not configured properly`):this.logger.error(`Failed to push branch ${s}: ${l}`),a}}this.logger.success(`Changes pushed to ${n}/${s}`),await this.createPullRequestIfPossible(e,s)}catch(s){throw this.logger.error(`Failed to push changes: ${s.message}`),s}}async commitAndPush(e,n,r="origin",i,s=!1){await this.commitChanges(e,n,!0,s),await this.pushChanges(e,r,i)}async removeWorktree(e,n=!1){try{const r=n?"--force":"";this.execGit(`worktree remove ${r} "${e}"`);for(const[i,s]of this.activeWorktrees.entries())if(s.path===e){this.activeWorktrees.delete(i);break}this.logger.success(`Worktree removed: ${e}`)}catch(r){throw this.logger.error(`Failed to remove worktree: ${r.message}`),r}}switchToWorktree(e){if(!T.existsSync(e))throw new Error(`Worktree path does not exist: ${e}`);try{const n=this.execGit("rev-parse HEAD",e),r=this.execGit("branch --show-current",e),i={path:e,branch:r||"detached",commit:n,isActive:!0,name:C.basename(e)};return this.logger.info(`Switched to worktree: ${e} (${r})`),i}catch(n){throw this.logger.error(`Failed to switch to worktree: ${n.message}`),n}}getWorktreeInfo(e){try{const n=this.execGit("rev-parse HEAD",e),r=this.execGit("branch --show-current",e);return{path:e,branch:r||"detached",commit:n,isActive:!1,name:C.basename(e)}}catch{return null}}async cleanup(e=!0,n="Agent work completed"){this.logger.info("Cleaning up worktrees...");let r=!1;e&&(r=await this.canPushToRemote(),r||this.logger.warn("Cannot push to remote - will only commit changes locally"));for(const[,i]of this.activeWorktrees.entries())try{if(e)try{r?(await this.commitAndPush(i.path,n,"origin",void 0,!0),this.logger.info(`Committed and pushed changes for worktree: ${i.path}`)):(await this.commitChanges(i.path,n,!0,!0),this.logger.info(`Committed changes locally for worktree: ${i.path}`))}catch(s){this.logger.warn(`Failed to commit/push worktree ${i.path}: ${s}`)}await this.removeWorktree(i.path,!0)}catch(s){this.logger.warn(`Failed to remove worktree ${i.path}: ${s}`)}this.activeWorktrees.clear(),this.logger.success("Worktree cleanup completed")}getRepositoryPath(){return this.repositoryPath}getActiveWorktrees(){return new Map(this.activeWorktrees)}isWorktreeSupported(){try{return this.execGit("worktree --help"),!0}catch{return!1}}async canPushToRemote(e="origin"){if(this.canPush!==null)return this.canPush;try{const n=this.execGit(`remote get-url ${e}`);return n.startsWith("git@")||n.includes("ssh://")?this.canPush=await this.testSshConnection(n):n.startsWith("https://")?this.canPush=await this.testHttpsCredentials(e):(this.logger.warn(`Unknown git remote protocol: ${n}`),this.canPush=!1)}catch(n){return this.logger.debug(`Cannot determine push capability: ${n}`),this.canPush=!1}}async testSshConnection(e){try{const n=e.split("@")[1]?.split(":")[0]||e.split("/")[2];return n?(ie.execSync(`ssh -T -o ConnectTimeout=5 -o BatchMode=yes git@${n}`,{stdio:"pipe",timeout:1e4}),!0):!1}catch(n){return n.status===1&&n.stderr?.includes("successfully authenticated")?!0:(this.logger.debug(`SSH test failed: ${n.message}`),!1)}}async testHttpsCredentials(e){try{return ie.execSync(`git ls-remote --exit-code ${e} HEAD`,{cwd:this.repositoryPath,stdio:"pipe",timeout:1e4}),!0}catch(n){return this.logger.debug(`HTTPS credentials test failed: ${n}`),!1}}checkBranchExists(e){try{return ie.execSync(`git show-ref --verify --quiet ${e}`,{cwd:this.repositoryPath,stdio:"pipe"}),!0}catch{return!1}}isBranchCheckedOutInWorktree(e){try{return this.listWorktrees().some(r=>r.branch===e&&r.path!==this.repositoryPath)}catch{return!1}}generateUniqueBranchName(){const e=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),n=Math.random().toString(36).substring(2,8);return`agent-work-${e}-${n}`}sanitizeBranchName(e){return e.replace(/[^a-zA-Z0-9-_]/g,"-").replace(/--+/g,"-").replace(/^-|-$/g,"").toLowerCase()}isGhCliAvailable(){try{return ie.execSync("gh --version",{stdio:"pipe"}),!0}catch{return!1}}getMainBranch(){try{const n=this.execGit("config --get init.defaultBranch").trim();if(n)return n}catch{}try{const n=this.execGit("symbolic-ref refs/remotes/origin/HEAD").trim();if(n)return n.replace("refs/remotes/origin/","")}catch{}const e=["main","master"];for(const n of e)if(this.checkBranchExists(`refs/heads/${n}`)||this.checkBranchExists(`refs/remotes/origin/${n}`))return n;return"main"}async createPullRequestIfPossible(e,n){if(!this.isGhCliAvailable()){this.logger.debug("GitHub CLI not available, skipping PR creation");return}const r=this.getMainBranch();if(n===r){this.logger.debug(`Already on main branch (${r}), skipping PR creation`);return}try{const i=ie.execSync(`gh pr list --head "${n}" --json number`,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim(),s=JSON.parse(i||"[]");if(s.length>0){this.logger.info(`Pull request already exists for branch ${n}: #${s[0].number}`);return}let o=`Agent work: ${n}`;n.includes("agent-work")&&(o=`🤖 ${n.replace(/-/g," ").replace("agent work","Agent Work:")}`);const a=`## 🤖 Automated Changes by AI Agent
90
-
91
- This pull request contains automated changes made by the Agiflow AI Agent.
92
-
93
- ### Branch Information
94
- - **Source Branch:** \`${n}\`
95
- - **Target Branch:** \`${r}\`
96
- - **Created:** ${new Date().toISOString()}
97
-
98
- ### Review Checklist
99
- - [ ] Code follows project conventions
100
- - [ ] Tests pass (if applicable)
101
- - [ ] No security vulnerabilities introduced
102
- - [ ] Documentation updated (if needed)
103
-
104
- ### Notes
105
- Please review the changes carefully before merging. The AI agent has attempted to follow best practices, but human review is essential.
106
-
107
- ---
108
- *Generated by [Agiflow Agent](https://agiflow.io)*`,l=`gh pr create --base "${r}" --head "${n}" --title "${o}" --body "${a}"`,g=ie.execSync(l,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim();this.logger.success(`Pull request created: ${g}`)}catch(i){i.message?.includes("authentication")||i.message?.includes("gh auth login")?this.logger.warn('GitHub CLI not authenticated. Run "gh auth login" to enable PR creation.'):this.logger.debug(`Could not create PR: ${i.message}`)}}}class Eh{logger;credentialsService;terminationService;gitWorktreeService;currentWorktree;agentHttpService;instance;isTerminating=!1;onFullscreenChange;constructor(e,n,r){this.logger=e??new D.Logger({verbose:!1}),this.credentialsService=new D.CredentialsService,this.terminationService=n??new Le(this.logger),this.onFullscreenChange=r;const i=ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT;if(!i)throw new Error("VITE_INJECT_AGIFLOW_APP_ENDPOINT is required but not configured");this.agentHttpService=new D.AgentHttpService({apiUrl:i,logger:this.logger,credentials:this.credentialsService}),this.setupTerminationHandlers()}handleInput(e){this.instance.sendInputToAgent(e)}get isFullscreen(){return this.instance?.isFullscreen??!1}setupTerminationHandlers(){this.isTerminating||(this.terminationService.on("daemon:terminating",async()=>{this.logger.info(`Daemon shutting down, terminating agent ${this.instance.getAgentInfo()?.agentSessionId}`);try{this.instance.disconnect()}catch(e){this.logger.error(`Error terminating agent during daemon shutdown: ${e}`)}}),this.terminationService.on("pty:terminated",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&(this.logger.info(`PTY terminated for agent ${e.agentSessionId}, clearing reference`),this.isTerminating=!0)}),this.terminationService.on("agent:cleanup",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&(this.logger.info(`Agent cleanup for ${e.agentSessionId}, clearing reference`),this.isTerminating=!0)}),this.terminationService.on("agent:sigint",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&this.logger.info(`Agent ${e.agentSessionId} received SIGINT, will be terminated via daemon`)}))}async terminateAgent(){if(this.isTerminating)return this.logger.debug("Agent is already terminating, skipping duplicate termination"),!0;this.logger.info("Starting agent termination process"),this.instance.setFullscreen(!1),this.logger.debug("Agent removed from fullscreen mode");try{this.instance.disconnect(),this.logger.debug("Agent disconnected successfully")}catch(e){this.logger.warn("Error disconnecting agent:",e)}return this.logger.info("Checking for worktree cleanup..."),await this.cleanupWorktrees(),this.logger.info("Agent termination completed"),!0}async launchAgent(e){const{payload:n}=e,{sessionId:r,agentType:i,agentSessionId:s}=n,o=await this.credentialsService.getAgentCreds();this.logger.info(`Launching agent - Type: ${i}, Session: ${r}, AgentSession: ${s}`),!this.gitWorktreeService&&n.agentConfig?.worktree&&await this.initializeGitWorktreeService(e);const a=n.agentConfig?.worktree;let l=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):void 0;if(a&&this.gitWorktreeService){let c,h;typeof a=="boolean"&&a||typeof a=="object"&&(c=a.branch,h=a.name);const d=await this.gitWorktreeService.createWorktree({repositoryPath:this.gitWorktreeService.getRepositoryPath(),branch:c,worktreeName:h,logger:this.logger});this.currentWorktree=d,l=d.path,this.logger.success(`Created worktree for agent: ${d.path} (${d.branch})`);try{if(s){const _={worktrees:[{name:d.name,branch:d.branch,path:d.path,createdAt:new Date().toISOString()}],currentSession:s};await this.agentHttpService.updateTaskDevInfo(s,_),this.logger.debug("Updated task devInfo with worktree information");const O=`🌳 Git worktree created for agent session
109
- - Location: \`${d.path}\`
110
- - Branch: \`${d.branch}\`
111
- - Name: ${d.name}`;await this.agentHttpService.createTaskComment(s,O),this.logger.debug("Added task comment about worktree creation");const A={sessionId:s,messageType:"output",content:`Creating git worktree for isolated development:
112
- • Branch: ${d.branch}
113
- • Location: ${d.path}
114
- • This provides a clean workspace for the agent to work without affecting your main branch.`,metadata:{eventType:"worktree_created",worktreePath:d.path,worktreeBranch:d.branch,worktreeName:d.name}};await this.agentHttpService.sendMessage(A),this.logger.debug("Sent message about worktree creation")}}catch(f){this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${f}`)}await this.setupWorktree(d.path,this.gitWorktreeService.getRepositoryPath(),s)}const g=i===J.GEMINI_CLI,p=i===J.CLAUDE_CODE;if(!g&&!p)throw this.logger.error(`Unsupported agent type: ${i}`),new Error(`Unsupported agent type: ${i}`);const E={agentType:i,serverUrl:ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT,apiUrl:ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT,...o,logger:this.logger,credentialsService:this.credentialsService,terminationService:this.terminationService,onFullscreenChange:this.onFullscreenChange},m=n.agentConfig?.docker===!0,F=n.agentConfig?.autonomous===!0;let k;g?k=new mh(E):p&&(m||F?(this.logger.info("Docker execution requested for Claude agent"),k=new Or({...E,onBeforeTerminate:async()=>{this.logger.info("Docker agent cleanup callback triggered"),this.logger.info("Checking for worktree cleanup..."),await this.cleanupWorktrees(),this.logger.info("Docker agent cleanup callback completed")}})):k=new $r(E));const u=g?"Gemini":m?"Claude Docker":"Claude";if(this.logger.debug(`Created ${u} agent instance`),!k)throw new Error(`Sorry, the agent ${u} is not supported!`);return l&&l!==n.agentConfig?.workingDirectory&&e.payload.agentConfig&&(e.payload.agentConfig.workingDirectory=l),await k.launchAgent(e),this.instance=k,this.instance.setFullscreen(!0),this.logger.debug("Agent set to fullscreen mode for stdin handling"),this.logger.success(`Agent launched successfully - AgentSession: ${s}`),k}async initializeGitWorktreeService(e){try{const n=e.payload.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(e.payload.agentConfig.workingDirectory):process.cwd();this.gitWorktreeService=new Dh(n,this.logger),this.logger.debug(`Git worktree service initialized for: ${n}`)}catch(n){this.logger.debug(`Git worktree service not available - not in a git repository: ${n}`)}}async createWorktree(e,n){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),null;try{const r=await this.gitWorktreeService.createWorktree({repositoryPath:this.gitWorktreeService.getRepositoryPath(),branch:e,worktreeName:n,logger:this.logger});if(this.currentWorktree=r,this.instance&&this.instance.getAgentInfo()){const s=this.instance.getAgentInfo();s.workingDir=r.path,this.logger.info(`Agent working directory updated to worktree: ${r.path}`);try{const o=s.agentSessionId;if(o){const l={worktrees:[{name:r.name,branch:r.branch,path:r.path,createdAt:new Date().toISOString()}],currentSession:o};await this.agentHttpService.updateTaskDevInfo(o,l),this.logger.debug("Updated task devInfo with worktree information");const g=`🌳 Git worktree created
115
- - Location: \`${r.path}\`
116
- - Branch: \`${r.branch}\`
117
- - Name: ${r.name}`;await this.agentHttpService.createTaskComment(o,g),this.logger.debug("Added task comment about worktree creation");const p={sessionId:o,messageType:"output",content:`Git worktree created:
118
- • Branch: ${r.branch}
119
- • Location: ${r.path}
120
- • The agent is now working in an isolated workspace.`,metadata:{eventType:"worktree_created",worktreePath:r.path,worktreeBranch:r.branch,worktreeName:r.name}};await this.agentHttpService.sendMessage(p),this.logger.debug("Sent message about worktree creation")}}catch(o){this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${o}`)}}this.logger.success(`Created worktree: ${r.path} (${r.branch})`);const i=this.instance?.getAgentInfo()?.agentSessionId;return await this.setupWorktree(r.path,this.gitWorktreeService.getRepositoryPath(),i),r}catch(r){return this.logger.error(`Failed to create worktree: ${r}`),null}}async setupWorktree(e,n,r){try{if(this.logger.info("Setting up worktree with environment files and dependencies..."),r)try{const l={sessionId:r,messageType:"output",content:`🔧 Setting up development environment in the worktree...
121
- Copying environment files...`,metadata:{eventType:"worktree_setup_start",worktreePath:e}};await this.agentHttpService.sendMessage(l)}catch(l){this.logger.debug(`Failed to send setup start message: ${l}`)}const s=await new $t({targetDirectory:e,originalDirectory:n,logger:this.logger}).setup();let o=`✅ Environment setup completed:
122
- `,a=!1;if(s.envFilesCopied.length>0){const l=s.envFilesCopied.filter(g=>g.copied).length;this.logger.success(`Copied ${l} environment files to worktree`),o+=`• Copied ${l} environment files
123
- `,a=!0}if(s.errors.length>0&&(this.logger.warn(`Worktree setup completed with ${s.errors.length} errors`),s.errors.forEach(l=>this.logger.debug(`Setup error: ${l}`)),o+=`• ⚠️ ${s.errors.length} setup warnings occurred
124
- `),r&&a)try{const l={sessionId:r,messageType:"output",content:o+"The workspace is ready for development.",metadata:{eventType:"worktree_setup_complete",worktreePath:e,envFilesCopied:s.envFilesCopied.filter(g=>g.copied).length,errorsCount:s.errors.length}};await this.agentHttpService.sendMessage(l)}catch(l){this.logger.debug(`Failed to send setup complete message: ${l}`)}}catch(i){if(this.logger.error(`Failed to setup worktree: ${i}`),r)try{const s={sessionId:r,messageType:"output",content:`⚠️ Worktree setup encountered issues: ${i}
125
- The workspace is created but may require manual setup.`,metadata:{eventType:"worktree_setup_error",worktreePath:e,error:String(i)}};await this.agentHttpService.sendMessage(s)}catch(s){this.logger.debug(`Failed to send setup error message: ${s}`)}}}switchToWorktree(e){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),null;try{const n=this.gitWorktreeService.switchToWorktree(e);if(this.currentWorktree=n,this.instance&&this.instance.getAgentInfo()){const r=this.instance.getAgentInfo();r.workingDir=n.path,this.logger.info(`Agent working directory updated to worktree: ${n.path}`)}return this.logger.success(`Switched to worktree: ${n.path} (${n.branch})`),n}catch(n){return this.logger.error(`Failed to switch to worktree: ${n}`),null}}getCurrentWorktree(){return this.currentWorktree}listWorktrees(){return this.gitWorktreeService?this.gitWorktreeService.listWorktrees():[]}async removeWorktree(e,n=!1){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),!1;try{return await this.gitWorktreeService.removeWorktree(e,n),this.currentWorktree?.path===e&&(this.currentWorktree=void 0),!0}catch(r){return this.logger.error(`Failed to remove worktree: ${r}`),!1}}async commitWorktreeChanges(e,n=!0){if(!this.gitWorktreeService||!this.currentWorktree)return this.logger.warn("No active worktree to commit changes"),!1;try{return await this.gitWorktreeService.commitChanges(this.currentWorktree.path,e,n),!0}catch(r){return this.logger.error(`Failed to commit worktree changes: ${r}`),!1}}async pushWorktreeChanges(e="origin",n){if(!this.gitWorktreeService||!this.currentWorktree)return this.logger.warn("No active worktree to push changes"),!1;try{return await this.gitWorktreeService.pushChanges(this.currentWorktree.path,e,n),!0}catch(r){return this.logger.error(`Failed to push worktree changes: ${r}`),!1}}async commitAndPushWorktreeChanges(e,n="origin",r){if(!this.gitWorktreeService||!this.currentWorktree)return this.logger.warn("No active worktree to commit and push changes"),!1;try{return await this.gitWorktreeService.commitAndPush(this.currentWorktree.path,e,n,r),!0}catch(i){return this.logger.error(`Failed to commit and push worktree changes: ${i}`),!1}}async cleanupWorktrees(e=!0,n="Agent work completed"){if(this.logger.info(`cleanupWorktrees called - gitWorktreeService exists: ${!!this.gitWorktreeService}, currentWorktree: ${!!this.currentWorktree}`),!this.gitWorktreeService){this.logger.info("No gitWorktreeService available, skipping worktree cleanup");return}if(!this.currentWorktree){this.logger.info("No active worktree to clean up");return}try{this.logger.info(`Cleaning up worktree at: ${this.currentWorktree.path}`),await this.gitWorktreeService.cleanup(e,n),this.currentWorktree=void 0,this.logger.success("Worktrees cleaned up successfully")}catch(r){this.logger.warn(`Error cleaning up worktrees: ${r}`)}}isWorktreeSupported(){return this.gitWorktreeService?.isWorktreeSupported()??!1}getGitWorktreeService(){return this.gitWorktreeService}getAgentHttpService(){return this.agentHttpService}}class vh{agents=new Map;agentLaunchSemaphore;logger;credentials;constructor(e){this.logger=e.logger,this.agentLaunchSemaphore=new ph(1),this.credentials=e.credentials??new D.CredentialsService}listAgentIds(){return Array.from(this.agents.keys())}getAgent(e){return this.agents.get(e)}getActiveAgent(){return Array.from(this.agents.values()).find(n=>n.isFullscreen)}handleFullscreenChange=(e,n)=>{if(n){for(const[r,i]of this.agents.entries())r!==e&&i.isFullscreen&&(i.instance.setFullscreen(!1,!0),this.logger.debug(`Agent ${r} removed from fullscreen mode`));this.logger.debug(`Agent ${e} is now in fullscreen mode`)}};async stopAgent(e){const n=this.getAgent(e);return n?(n?.terminateAgent(),this.agents.delete(e),!0):!1}async startAgent(e,n){const r=e.payload.agentSessionId;if(this.agentLaunchSemaphore.isLocked(r)){this.logger.warn(`Agent launch already in progress for session: ${r}`),n(e.payload.sessionId,"AGENT_ALREADY_LAUNCHING",`Agent with session ${r} is already being launched`);return}await this.agentLaunchSemaphore.runExclusive(r,async()=>{if(this.getAgent(r)){this.logger.info(`Agent already exists for session: ${r}`);return}this.logger.info("Launching agent:",e.payload.agentType);const s=await this.credentials.getApiKey(),o=await this.credentials.getOrganizationId();if(!s||!o)throw new Error("Missing credentials to launch agent");const a=new Eh(this.logger,void 0,this.handleFullscreenChange);await a.launchAgent(e),this.agents.set(e.payload.agentSessionId,a),this.logger.debug("Waiting for agent PTY to initialize..."),await new Promise(l=>setTimeout(l,1e3)),this.logger.debug("Agent PTY should now be ready for stdin forwarding"),this.logger.success(`Agent launched successfully: ${e.payload.agentSessionId}`)})}}class yh{logger;constructor(e){this.logger=e??new D.Logger({verbose:!1})}async detectAgents(){const e=[{name:J.CLAUDE_CODE,executable:"claude"},{name:J.GEMINI_CLI,executable:"gemini"}],n=[];for(const i of e){const s=await this.detectAgent(i.name,i.executable);n.push(s)}const r=n.filter(i=>i.isInstalled).length;return this.logger.info(`🔍 Agent detection complete: ${r}/${n.length} agents installed`),{availableAgents:n,installedCount:r}}async detectAgent(e,n){let r={name:e,executable:n,isInstalled:!1};try{const i=this.executeCommand(`${n} --version`);if(i){const s=this.executeCommand(`which ${n}`);this.logger.info(`✅ Found ${e}: ${i.trim()}`),r={name:e,executable:n,isInstalled:!0,version:i.trim(),path:s?.trim()}}}catch{try{this.executeCommand(`${n} --help`),this.logger.info(`✅ Found ${e} (version unknown)`),r={name:e,executable:n,isInstalled:!0,version:"unknown"}}catch{this.logger.info(`❌ ${e} not found`)}}return r.isInstalled&&(r.hostAuthed=this.checkHostAuth(e),r.dockerAuthed=this.checkDockerAuth(e),this.logger.info(`🔐 ${e} auth status: host=${r.hostAuthed}, docker=${r.dockerAuthed}`)),r}async isAgentInstalled(e,n){return(await this.detectAgent(e,n)).isInstalled}async getInstalledAgents(){return(await this.detectAgents()).availableAgents.filter(n=>n.isInstalled)}async getAgentTypesForRegistration(){return(await this.getInstalledAgents()).map(n=>({agentType:n.name,hostEnabled:n.hostAuthed??!1,dockerEnabled:n.dockerAuthed??!1,hostAuthed:n.hostAuthed??!1,dockerAuthed:n.dockerAuthed??!1}))}executeCommand(e){try{return ie.execSync(e,{encoding:"utf8",stdio:"pipe",timeout:5e3})}catch{return null}}checkHostAuth(e){if(e!==J.CLAUDE_CODE)return!1;const n=ae.homedir(),r=ae.platform()==="darwin";try{if(r){const i=C.join(n,".claude_tmp.json"),s=C.join(n,".claude_tmp");return T.existsSync(i)||T.existsSync(s)}else{const i=C.join(n,".claude.json"),s=C.join(n,".claude");return T.existsSync(i)||T.existsSync(s)}}catch(i){return this.logger.debug(`Error checking host auth for ${e}:`,i),!1}}checkDockerAuth(e){if(e!==J.CLAUDE_CODE||!this.isDockerAvailableSync())return!1;const n=ae.homedir(),r=ae.platform()==="darwin";try{if(r){const i=C.join(n,".claude_tmp.json"),s=C.join(n,".claude_tmp");return T.existsSync(i)||T.existsSync(s)}else{const i=C.join(n,".claude.json"),s=C.join(n,".claude");return T.existsSync(i)||T.existsSync(s)}}catch(i){return this.logger.debug(`Error checking Docker auth for ${e}:`,i),!1}}isDockerAvailableSync(){try{return!!this.executeCommand("docker --version")}catch{return!1}}async isDockerAvailable(){try{const e=this.executeCommand("docker --version");if(e)return this.logger.info(`🐳 Docker available: ${e.trim()}`),!0}catch{this.logger.info("🐳 Docker not available")}return!1}async getSystemCapabilities(){const[e,n]=await Promise.all([this.getInstalledAgents(),this.isDockerAvailable()]),r=e.map(i=>({agentType:i.name,hostEnabled:!0,dockerEnabled:n}));return{hostExecution:e.length>0,dockerExecution:n,installedAgents:e,agentTypesForRegistration:r}}}class Pr{options;authService;databaseDeviceId=null;credentials;logger;agentDetection;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new D.CredentialsService,this.logger=e.logger??new D.Logger({verbose:!1}),this.agentDetection=e.agentDetection??new yh(this.logger)}setDatabaseDeviceId(e){this.databaseDeviceId=e}getDatabaseDeviceId(){return this.databaseDeviceId}async getAuthHeaders(){let e=await this.credentials.getApiKey(),n=await this.credentials.getOrganizationId();if((!e||!n)&&this.authService){const i=await this.authService.getValidApiKey();e=i.api_key,n=i.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:n,expiresAt:i.expires_at})}if(e&&n)return this.options.organizationId=n,{"Content-Type":"application/json","x-api-key":e};const r=this.options.authToken;if(!r)throw new Error("Authentication token is required for daemon registration");if(!this.options.organizationId)throw new Error("Organization ID is required for daemon registration");return{"Content-Type":"application/json",Authorization:`Bearer ${r}`}}async makeAuthenticatedRequest(e,n,r=!0){const i=await fetch(e,n);if(i.status===401&&r&&this.authService&&(await i.text()).includes("Invalid API key")){this.logger.info("🔑 API key expired or invalid, clearing tokens and retrying authentication..."),await this.authService.clearTokens();try{await this.credentials.clear()}catch{}this.logger.info("🔄 Retrying authentication...");const o=await this.getAuthHeaders(),a={...n,headers:{...n.headers,...o}};return await fetch(e,a)}return i.status===429&&this.logger.warn("🚫 Rate limit exceeded, keeping credentials but not retrying"),i}async registerDaemon(){const{deviceGuid:e}=this.options;if(this.authService&&!this.databaseDeviceId){const l=await this.authService.getDeviceId();l&&(this.databaseDeviceId=l,this.logger.info(`📋 Loaded existing device ID from storage: ${this.databaseDeviceId}`))}this.authService&&this.logger.info("🔐 Authenticating via OAuth flow...");const n=await this.getAuthHeaders(),r=this.options.organizationId,i=br(),s=process.cwd();this.logger.info("🔍 Detecting available agent types...");const o=await this.agentDetection.getAgentTypesForRegistration();o.length>0?this.logger.info(`✅ Found ${o.length} agent type(s): ${o.map(l=>l.agentType).join(", ")}`):this.logger.warn("⚠️ No agent types detected - daemon will register without agent capabilities");const a={deviceGuid:e,hostname:i.hostname,platform:i.platform,workingDirectory:s,agentTypes:o.length>0?o:void 0};this.logger.info("📝 Registering daemon with API...");try{const l=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${r}/daemons`,{method:"POST",headers:n,body:JSON.stringify(a)});if(!l.ok){const p=await l.text();throw new Error(`Registration failed: ${l.status} ${p}`)}const g=await l.json();if(g.device?.id?this.databaseDeviceId=g.device.id:g.deviceGuid&&(this.databaseDeviceId=g.deviceGuid),this.databaseDeviceId){this.authService&&await this.authService.updateDeviceId(this.databaseDeviceId);try{await this.credentials.setDeviceId(this.databaseDeviceId)}catch{}}return this.logger.success(`Daemon registered successfully: ${g.id}`),this.logger.info(` Device ID (database): ${this.databaseDeviceId}`),g}catch(l){throw new Error(`Failed to register daemon: ${l instanceof Error?l.message:l}`)}}async sendHeartbeat(e){if(!e){this.logger.warn("⚠️ No daemon registration available for heartbeat");return}try{const n=await this.getAuthHeaders(),r=this.options.organizationId;if(!r){this.logger.warn("⚠️ Organization ID not available for heartbeat");return}const i={lastHeartbeat:new Date().toISOString(),status:De.IDLE},s=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${r}/daemons/${e.id}`,{method:"PATCH",headers:n,body:JSON.stringify(i)},!0);if(!s.ok){const o=await s.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to send heartbeat: ${s.status} ${o}`)}}catch(n){this.logger.warn("⚠️ Failed to send heartbeat:",n)}}async unregisterDaemon(e){if(e)try{const n=await this.getAuthHeaders(),r=this.options.organizationId;if(!r){this.logger.warn("⚠️ Organization ID not available for unregistration");return}this.logger.info("📝 Unregistering daemon from API...");const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${r}/daemons/${e.id}`,{method:"DELETE",headers:n},!1);if(i.ok)this.logger.success("Daemon unregistered successfully");else{const s=await i.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to unregister daemon: ${i.status} ${s}`)}}catch(n){this.logger.warn("⚠️ Failed to unregister daemon:",n)}}}class Rr{ws=null;options;callbacks;reconnectTimer=null;isConnected=!1;shouldReconnect=!0;sessionManager;credentials;logger;agentsManager;constructor(e,n={}){this.options={reconnectInterval:5e3,...e},this.callbacks=n,this.sessionManager=e.sessionManager,this.logger=e.logger??new D.Logger({verbose:e.verbose||!1}),this.credentials=e.credentials??new D.CredentialsService,this.agentsManager=e.agentsManager}async connect(e){return this.connectToDaemonChannel(e)}disconnect(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.isConnected=!1}isWebSocketConnected(){return this.isConnected}sendMessage(e){this.ws&&this.ws.readyState===_e.OPEN?this.ws.send(JSON.stringify(e)):this.logger.warn("Cannot send message - WebSocket not connected")}sendError(e,n,r,i){const s=mr.parse({payload:{sessionId:e,data:r,error:{code:n,message:r,details:i instanceof Error?i.message:i}}});this.sendMessage(s)}async connectToDaemonChannel(e){return new Promise(async(n,r)=>{const{authToken:i,deviceGuid:s}=this.options;if(!e){r(new Error("Daemon must be registered before connecting to daemon channel"));return}let o=await this.credentials.getApiKey(),a=await this.credentials.getOrganizationId();if((!o||!a)&&this.options.authService)try{const m=await this.options.authService.getValidApiKey();o=m.api_key,a=m.organization_id,await this.credentials.setApiKey({apiKey:o,organizationId:a,deviceId:m.device_id})}catch(m){this.logger.warn("Unable to refresh credentials:",m.message)}a||(a=this.options.organizationId),!o&&i&&(o=i);const l=a||this.options.organizationId;if(!l){r(new Error("Organization ID missing for daemon WebSocket connection"));return}const g=new URL(this.options.serverUrl);g.protocol==="http:"?g.protocol="ws:":g.protocol==="https:"&&(g.protocol="wss:");const p=e.id;g.pathname=`/api/v1/organizations/${l}/daemons/${p}/ws`,g.searchParams.set("clientType","daemon");const E=await this.credentials.buildDeviceAuthHeaders(s);if(!E["x-api-key"]){r(new Error("No API key available for WebSocket connection"));return}this.logger.info(`Connecting to daemon WebSocket: ${g.toString()}`),this.ws=new _e(g.toString(),{headers:E}),this.ws.on("open",()=>{this.isConnected=!0,this.logger.info("Daemon WebSocket connection established");const m=It.parse({payload:{sessionId:s,data:"Daemon ready",status:De.IDLE}});this.sendMessage(m),this.callbacks.onConnect&&this.callbacks.onConnect(),n()}),this.ws.on("message",m=>{try{const F=m.toString(),k=JSON.parse(F);this.handleServerMessage(k)}catch(F){this.logger.error("Failed to parse server message:",F),this.logger.error(`Raw data: ${m.toString()}`)}}),this.ws.on("close",(m,F)=>{this.isConnected=!1,this.logger.info(`Daemon WebSocket disconnected (${m}): ${F}`),this.callbacks.onDisconnect&&this.callbacks.onDisconnect(m,F.toString()),this.shouldReconnect&&this.scheduleReconnect(e)}),this.ws.on("error",m=>{this.logger.error("WebSocket error:",m),this.callbacks.onError&&this.callbacks.onError(m),this.isConnected||r(m)}),setTimeout(()=>{this.isConnected||r(new Error("WebSocket connection timeout"))},1e4)})}scheduleReconnect(e){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.shouldReconnect)try{this.logger.info("Attempting to reconnect..."),await this.connect(e)}catch{this.logger.warn("Reconnection failed, will retry..."),this.scheduleReconnect(e)}},this.options.reconnectInterval)}async handleServerMessage(e){try{if(e.eventType){e.eventType===B.STATUS&&e.command===S.REQUEST?await this.handleStatusRequest(e):e.eventType===B.START_AGENT&&e.command===S.REQUEST?await this.handleLaunchAgent(e):e.eventType===B.STOP_AGENT&&e.command===S.REQUEST?await this.handleStopAgent(e):e.eventType===B.TERMINATE&&e.command===S.REQUEST?await this.handleTerminateDaemon(e):e.eventType===B.LIST&&e.command===S.REQUEST?await this.handleListAgentSessions(e):e.eventType?.startsWith("agent-")?this.logger.debug(`Received agent message on daemon WebSocket (ignoring): ${e.eventType}-${e.command||"unknown"}`):this.logger.warn(`Unknown daemon message: ${e.eventType}-${e.command||"unknown"}`);return}this.callbacks.onMessage&&await this.callbacks.onMessage(e)}catch(n){this.logger.error("Failed to process server message:",n),this.sendError(e.payload?.sessionId||"","COMMAND_ERROR","Failed to process server command",n)}}async handleStatusRequest(e){try{const n=pr.parse(e),r=It.parse({eventType:B.STATUS,command:S.RESPONSE,payload:{sessionId:n.payload.sessionId,timestamp:Date.now(),data:"Daemon is running",status:De.IDLE}});this.sendMessage(r)}catch(n){this.logger.error("Failed to handle daemon status request:",n),this.sendError(e.payload?.sessionId||"","STATUS_REQUEST_FAILED","Failed to handle status request",n)}}async handleLaunchAgent(e){try{const n=zt.parse(e),r=n.payload.agentSessionId;if(this.agentsManager.getAgent(r))return;this.agentsManager.startAgent(n,s=>{this.logger.warn(`Agent launch already in progress for session: ${r}`),this.sendError(s)})}catch(n){this.logger.error("Failed to launch agent:",n),this.sendError(e.payload?.sessionId||"","LAUNCH_AGENT_FAILED","Failed to launch agent",n)}}async handleStopAgent(e){try{const n=_r.parse(e),r=n.payload.agentSessionId,i=await this.agentsManager.stopAgent(r),s=Sr.parse({eventType:B.STOP_AGENT,command:S.RESPONSE,payload:{sessionId:n.payload.sessionId,timestamp:Date.now(),data:i?"Agent stopped successfully":"Agent not found",agentSessionId:r,status:i?"stopped":"not_found",message:i?`Agent ${r} has been stopped`:`Agent ${r} was not found`}});this.sendMessage(s),i?this.logger.success(`Agent stopped successfully: ${r}`):this.logger.warn(`Agent not found: ${r}`)}catch(n){this.logger.error("Failed to stop agent:",n),this.sendError(e.payload?.sessionId||"","STOP_AGENT_FAILED","Failed to stop agent",n)}}async handleTerminateDaemon(e){try{const n=Dr.parse(e);if(this.logger.info("Received daemon terminate request"),this.ws&&this.ws.readyState===_e.OPEN){const r=Er.parse({payload:{sessionId:n.payload.sessionId,data:"Daemon terminating gracefully"}});this.sendMessage(r),this.logger.info("Daemon terminate response sent")}else this.logger.warn("WebSocket not connected, cannot send terminate response");if(this.options.onTerminate)this.logger.info("Initiating graceful daemon shutdown..."),setTimeout(async()=>{try{await this.options.onTerminate(!0),this.logger.info("Graceful shutdown complete, disconnecting WebSocket..."),this.disconnect()}catch(r){this.logger.error("Error during graceful shutdown:",r),process.exit(1)}},500);else{this.logger.warn("No onTerminate callback provided, using fallback shutdown");const r=this.sessionManager.getAllSessions();for(const i of r)i.status===H.IDLE&&await this.sessionManager.terminateSession(i.id);setTimeout(()=>{this.disconnect(),this.logger.info("Daemon shutting down..."),process.exit(0)},1e3)}}catch(n){this.logger.error("Failed to handle daemon terminate request:",n),this.sendError(e.payload?.sessionId||"","TERMINATE_DAEMON_FAILED","Failed to terminate daemon",n)}}async handleListAgentSessions(e){try{const n=vr.parse(e),r=this.sessionManager.getAllSessions(),i=yr.parse({payload:{sessionId:n.payload.sessionId,data:"Agent sessions list",sessions:r}});this.sendMessage(i)}catch(n){this.logger.error("Failed to handle list agent sessions request:",n),this.sendError(e.payload?.sessionId||"","LIST_SESSIONS_FAILED","Failed to list agent sessions",n)}}getSessionManager(){return this.sessionManager}}class _h{terminationService;options;daemonRegistration=null;authService;httpService;wsService;isShuttingDown=!1;heartbeat;logger;agentsManager;stdinForwarding;constructor(e){this.options={reconnectInterval:5e3,stableDeviceId:!0,...e,apiUrl:e.apiUrl||Ar(e.serverUrl)},this.options.deviceGuid=e.deviceGuid||Cr(this.options.stableDeviceId!==!1),this.logger=new D.Logger({verbose:this.options.verbose||!1,logFile:this.options.logFile,logDir:this.options.logDir||Xr.join(fe.tmpdir(),"agiflow-agents","daemon",`session-${process.pid}`),maxFiles:7,maxFileSize:"10m"});const n=this.logger.getLogFilePath();n&&this.logger.info(`Logging to file: ${n}`),this.agentsManager=new vh({logger:this.logger}),this.logger.debug("Setting up StdinForwarding service..."),this.stdinForwarding=new kr({logger:this.logger,onData:this.onData.bind(this),onExit:this.onExit.bind(this)}),this.logger.debug("StdinForwarding service initialized"),this.terminationService=new Le(this.logger),this.terminationService.registerCallbacks({onPtyTerminated:async r=>{await this.agentsManager.stopAgent(r.agentSessionId)},onAgentTerminated:async r=>{this.logger.info(`Agent ${r.agentSessionId} terminated, cleaning up`),await this.agentsManager.stopAgent(r.agentSessionId)},onDaemonTerminating:async()=>{this.logger.info("Daemon is terminating, preparing cleanup")},onAgentSigint:async r=>{this.logger.info(`Agent ${r.agentSessionId} received SIGINT, stopping agent via daemon`),await this.agentsManager.stopAgent(r.agentSessionId)}}),this.authService=new Mt({...e.options,logger:this.logger}),this.httpService=new Pr({apiUrl:this.options.apiUrl,deviceGuid:this.options.deviceGuid,organizationId:this.options.organizationId,authToken:this.options.authToken,authService:this.authService,logger:this.logger}),this.wsService=new Rr({serverUrl:this.options.serverUrl,deviceGuid:this.options.deviceGuid,organizationId:this.options.organizationId,authToken:this.options.authToken,verbose:this.options.verbose,reconnectInterval:this.options.reconnectInterval,authService:this.authService,databaseDeviceId:this.httpService.getDatabaseDeviceId()||void 0,sessionManager:this,logger:this.logger,agentsManager:this.agentsManager,onTerminate:r=>this.stop(r)}),this.heartbeat=Tr(async()=>{this.daemonRegistration&&!this.isShuttingDown&&(this.logger.debug("Heartbeat..."),await this.httpService.sendHeartbeat(this.daemonRegistration))},3e5,this.logger)}async onExit(e){this.logger.debug(`Daemon received exit signal: ${JSON.stringify(e)}`);const n=this.agentsManager.getActiveAgent();n?(this.logger.info(`Stopping agent due to exit signal: ${n.instance.getAgentInfo()?.agentSessionId}`),await this.agentsManager.stopAgent(n.instance.getAgentInfo()?.agentSessionId||"")):(this.logger.info("No active agent, stopping daemon gracefully"),await this.stop())}onData(e){try{this.logger.debug("=== DAEMON ONDATA CALLED ==="),this.logger.debug(`Daemon received stdin data: ${JSON.stringify(e)} (length: ${e.length})`);const n=this.agentsManager.getActiveAgent();if(n){const r=n.instance.getAgentInfo();this.logger.debug(`Found active agent: ${r?.agentSessionId}`),this.logger.debug("About to call agentWorker.handleInput..."),n.handleInput(e),this.logger.debug("agentWorker.handleInput completed successfully")}else this.logger.warn("No active agent to handle stdin data"),e===""&&this.logger.info("Ctrl+C received (no active agent). Press Ctrl+C again to exit daemon.")}catch(n){this.logger.error("Error in daemon onData:",n)}}async start(){const{serverUrl:e}=this.options;this.logger.info("Starting Daemon..."),this.logger.debug("API URL:",this.options.apiUrl),this.logger.debug("WebSocket URL:",e);try{this.daemonRegistration=await this.httpService.registerDaemon();let n;if(this.authService){const r=await this.authService.getValidApiKey();n=r.api_key,this.options.organizationId=r.organization_id}else n=this.options.authToken;if(!n)throw new Error("No API key available for SessionManager");await this.wsService.connect(this.daemonRegistration),this.heartbeat.start(),this.logger.success("Daemon connected"),this.logger.info("Daemon ID:",this.daemonRegistration?.id)}catch(n){throw this.logger.error("Failed to start daemon:",n),n}}async stop(e=!1){if(this.isShuttingDown){this.logger.debug("Already shutting down, skipping duplicate stop call");return}this.isShuttingDown=!0;const n=setTimeout(()=>{this.logger.error("Force exit after cleanup timeout (10s)"),process.exit(1)},1e4);try{this.logger.info("Beginning graceful daemon shutdown..."),this.logger.info("Stopping heartbeat..."),this.heartbeat.stop();const r=this.agentsManager.listAgentIds();r.length>0?(this.logger.info(`Terminating ${r.length} active agent(s)...`),await this.terminationService.shutdownDaemon(r),await this.terminationService.waitForActiveTerminations(),this.logger.info("All agents terminated successfully")):this.logger.info("No active agents to terminate");try{this.daemonRegistration&&this.httpService&&(this.logger.info("Unregistering daemon from backend..."),await this.httpService.unregisterDaemon(this.daemonRegistration),this.logger.info("Daemon unregistered successfully"))}catch(i){this.logger.warn("Failed to unregister daemon (non-fatal):",i)}e?this.logger.info("WebSocket-initiated shutdown, WebSocket will handle its own disconnect"):(this.logger.info("Disconnecting WebSocket..."),this.wsService.disconnect()),this.logger.info("Cleaning up termination service..."),this.terminationService.cleanup(),this.logger.info("Restoring stdio handler to terminal..."),this.stdinForwarding.restore(),this.logger.success("✅ Daemon stopped gracefully"),clearTimeout(n),process.exit(0)}catch(r){this.logger.error("❌ Error during daemon shutdown:",r),clearTimeout(n),process.exit(1)}}getStats(){return{daemonId:this.daemonRegistration?.id,deviceGuid:this.daemonRegistration?.deviceGuid}}getAllSessions(){return this.agentsManager.listAgentIds().map(n=>({id:n,status:"IDLE"}))}async terminateSession(e){this.logger.info(`Terminating session: ${e}`),await this.agentsManager.stopAgent(e)}}class Nr extends ze{register(e){e.command("connect").description("Connect Agiflow daemon to receive commands from remote server").option("-u, --server-url <url>","WebSocket server URL to connect to").option("--api-url <url>","HTTP API base URL for daemon registration").option("-v, --verbose","Enable verbose logging").option("--reconnect-interval <ms>","Reconnection interval in milliseconds","5000").option("--unique-instance","Create unique daemon instance (default: reuse by working directory)").action(async n=>{try{await this.execute(n)}catch(r){this.handleError(r)}})}async execute(e){const n=e.serverUrl||ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT,r=e.apiUrl||ue.VITE_INJECT_AGIFLOW_APP_ENDPOINT;n||(this.error("Server URL is required. Provide via --server-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable."),process.exit(1)),r||(this.error("API URL is required. Provide via --api-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable."),process.exit(1));try{new URL(n)}catch{this.error("Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://)."),process.exit(1)}try{new URL(r)}catch{this.error("Invalid API URL. Must be a valid HTTP URL."),process.exit(1)}const i=e.reconnectInterval?parseInt(e.reconnectInterval,10):5e3;(isNaN(i)||i<1e3)&&(this.error("Invalid reconnect interval. Must be at least 1000ms."),process.exit(1));const s=new Mt({clientId:"agiflow-cli-daemon",baseUrl:r,verbose:e.verbose});let o;try{e.verbose&&console.log("🔐 Authenticating..."),o=await s.getValidApiKey()}catch(g){const p=g instanceof Error?g.message:String(g);p.includes("cancelled by user")?(this.info(`
126
- Authentication cancelled`),process.exit(0)):(this.error(`Authentication failed: ${p}`),process.exit(1))}const a=new _h({serverUrl:n,apiUrl:r,authToken:o.api_key,organizationId:o.organization_id,verbose:e.verbose,reconnectInterval:i,stableDeviceId:!e.uniqueInstance,options:{clientId:"agiflow-cli-daemon",baseUrl:r,verbose:e.verbose}}),l=async g=>{console.log(`
127
- 📡 Received ${g}, initiating graceful shutdown...`);try{await a.stop()}catch(p){this.error(`Error during shutdown: ${p}`),process.exit(1)}};process.on("SIGINT",()=>l("SIGINT")),process.on("SIGTERM",()=>l("SIGTERM")),process.on("SIGHUP",()=>l("SIGHUP"));try{await a.start();const g=a.getStats();this.success("Agiflow Daemon connected successfully"),this.info(`🆔 Daemon ID: ${g.daemonId}`),this.info(`💻 Device GUID: ${g.deviceGuid}`),this.info(`Press Ctrl+C to disconnect
128
- `)}catch(g){this.error(`Failed to connect daemon: ${g}`),process.exit(1)}}}class Br extends ze{register(e){e.command("logout").description("Log out and clean up stored credentials").option("-v, --verbose","Enable verbose logging").option("--remove-all","Remove entire .agiflow directory (default: remove only credential files)").action(async n=>{try{await this.execute(n)}catch(r){this.handleError(r)}})}async execute(e){e.verbose&&console.log("🔐 Logging out and cleaning up credentials...");try{if(!await D.FileSystemUtils.exists(D.FileSystemUtils.AGIFLOW_DIR)){this.info("No stored credentials found. You are already logged out.");return}if(e.removeAll)await D.FileSystemUtils.remove(D.FileSystemUtils.AGIFLOW_DIR),e.verbose&&this.info(`Removed entire directory: ${D.FileSystemUtils.AGIFLOW_DIR}`),this.success("Successfully logged out and removed all Agiflow configuration");else{const r=["api-key.json","credentials.json"];let i=0;for(const s of r){const o=require("path").join(D.FileSystemUtils.AGIFLOW_DIR,s);await D.FileSystemUtils.exists(o)&&(await D.FileSystemUtils.remove(o),i++,e.verbose&&this.info(`Removed: ${s}`))}i===0?this.info("No credential files found. You are already logged out."):this.success(`Successfully logged out and removed ${i} credential file(s)`)}}catch(n){const r=n instanceof Error?n.message:String(n);this.error(`Failed to clean up credentials: ${r}`),process.exit(1)}}}class Ur extends ze{register(e){e.command("router").description("Manage LLM routing configuration for active sessions").option("-v, --verbose","Enable verbose logging").option("--clear","Clear all session routing configurations").action(async n=>{try{await this.execute(n)}catch(r){this.handleError(r)}})}async execute(e){try{if(e.clear){await D.SessionSettingsManager.clearAllSessions(),this.success("All session routing configurations have been cleared.");return}const n=await D.SessionSettingsManager.getAllSessions(),r=Object.keys(n);if(r.length===0){this.warn("No active sessions found."),this.info("Start a Claude agent first using: agiflow claude");return}const i=r.map(p=>{const E=n[p],m=E?.alias||p,F=E?.provider&&E?.model?`${E.provider}/${E.model}${E.reasoningEffort?` (${E.reasoningEffort})`:""}`:"default";return{name:`${m} [${F}]`,value:p,description:`Current routing: ${F}`}}),s=await et.select({message:"Select a session to configure routing:",choices:i});e.verbose&&this.info(`Selected session: ${s}`);const o=[{name:"Default (Claude)",value:null,description:"Use default Claude routing (no LLM proxy)"},{name:"GPT-5 (Reasoning: High)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"high"},description:"Route to GPT-5 with high reasoning effort"},{name:"GPT-5 (Reasoning: Medium)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"medium"},description:"Route to GPT-5 with medium reasoning effort"},{name:"GPT-5 (Reasoning: Low)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"low"},description:"Route to GPT-5 with low reasoning effort"},{name:"GPT-5 (Reasoning: Minimal)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"minimal"},description:"Route to GPT-5 with minimal reasoning effort"},{name:"GPT-5 Codex (Reasoning: High)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"high"},description:"Route to GPT-5 Codex with high reasoning effort"},{name:"GPT-5 Codex (Reasoning: Medium)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"medium"},description:"Route to GPT-5 Codex with medium reasoning effort"},{name:"GPT-5 Codex (Reasoning: Low)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"low"},description:"Route to GPT-5 Codex with low reasoning effort"}],a=await et.select({message:"Select LLM routing configuration:",choices:o.map(p=>({name:p.name,value:p.value,description:p.description}))}),l=n[s],g=l?.alias||s;if(a===null){const p={...l?.alias&&{alias:l.alias}};await D.SessionSettingsManager.setSessionSettings(s,p),this.success(`Routing cleared for session "${g}". Using default Claude.`)}else{const p={...a,alias:l?.alias};await D.SessionSettingsManager.setSessionSettings(s,p),this.success(`Routing configured for session "${g}": ${a.provider}/${a.model}${a.reasoningEffort?` (${a.reasoningEffort})`:""}`)}this.info("Note: Restart the agent for changes to take effect.")}catch(n){if(n instanceof Error&&n.message.includes("User force closed")){this.info("Operation cancelled by user");return}throw n}}}Nn.config();async function Sh(){const t=new ui;t.name("agiflow").description("@agiflowai/agent-cli").option("-v, --verbose","enable verbose logging").option("--debug","enable debug mode");const e=new xr;"register"in e&&typeof e.register=="function"?e.register(t):t.command("claude").description("Launch Claude Code agent").action(async()=>{await e.run?.([])});const n=new Nr;"register"in n&&typeof n.register=="function"?n.register(t):t.command("connect").description("Connect agent").action(async()=>{await n.run?.([])});const r=new Br;"register"in r&&typeof r.register=="function"?r.register(t):t.command("logout").description("Logout and clean up credentials").action(async()=>{await r.run?.([])});const i=new Ur;"register"in i&&typeof i.register=="function"?i.register(t):t.command("router").description("Manage Agiflow routing configuration").action(async()=>{await i.run?.([])});try{await t.parseAsync(process.argv)}catch(s){console.error("[cli] error",s.message),t.opts().debug&&s instanceof Error&&console.error(s.stack),process.exit(1)}}Sh();exports.BaseCommand=ze;exports.ClaudeCommand=xr;exports.ConfigSchema=Fr;exports.ConnectCommand=Nr;exports.DaemonHttpService=Pr;exports.DaemonWsService=Rr;exports.DeviceCodeAuthService=Mt;exports.LogoutCommand=Br;exports.RouterCommand=Ur;exports.config=ue;exports.createHeartbeat=Tr;exports.generateDeviceId=Cr;exports.getServerUrl=wr;exports.getSystemInfo=br;exports.getWebSocketUrl=oh;exports.httpToWebSocket=ah;exports.webSocketToHttp=Ar;
129
- //# sourceMappingURL=cli-2Wesya-Z.js.map