@agiflowai/agent-cli 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,129 +0,0 @@
1
- "use strict";var Br=Object.create;var Gt=Object.defineProperty;var Ur=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var Mr=Object.getPrototypeOf,Gr=Object.prototype.hasOwnProperty;var jr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zr(e))!Gr.call(t,s)&&s!==n&&Gt(t,s,{get:()=>e[s],enumerable:!(r=Ur(e,s))||r.enumerable});return t};var ht=(t,e,n)=>(n=t!=null?Br(Mr(t)):{},jr(e||!t||!t.__esModule?Gt(n,"default",{value:t,enumerable:!0}):n,t));const D=require("./AgentHttpService-CYYuD3Wj.js"),Lr=require("node:events"),Wr=require("node:child_process"),$n=require("node:path"),Zr=require("node:fs"),q=require("node:process"),k=require("fs"),C=require("path"),le=require("os"),Vr=require("crypto"),pe=require("fs/promises"),_e=require("ws"),Hr=require("node-pty"),On=require("ulidx"),se=require("child_process"),Kr=require("events"),jt=require("@inquirer/prompts"),qr=require("node:crypto"),Yr=require("node:os"),Jr=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 Qr=Be($n),Xr=Be(k),es=Be(Hr),ts=Be(qr),fe=Be(Yr);var oe={},Le={},We={},Lt;function st(){if(Lt)return We;Lt=1;class t extends Error{constructor(r,s,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=s,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 We.CommanderError=t,We.InvalidArgumentError=e,We}var Wt;function $t(){if(Wt)return Le;Wt=1;const{InvalidArgumentError:t}=st();class e{constructor(s,i){switch(this.description=i||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,s[0]){case"<":this.required=!0,this._name=s.slice(1,-1);break;case"[":this.required=!1,this._name=s.slice(1,-1);break;default:this.required=!0,this._name=s;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(s,i){return i===this.defaultValue||!Array.isArray(i)?[s]:i.concat(s)}default(s,i){return this.defaultValue=s,this.defaultValueDescription=i,this}argParser(s){return this.parseArg=s,this}choices(s){return this.argChoices=s.slice(),this.parseArg=(i,o)=>{if(!this.argChoices.includes(i))throw new t(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,o):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function n(r){const s=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+s+">":"["+s+"]"}return Le.Argument=e,Le.humanReadableArgName=n,Le}var dt={},gt={},Zt;function xn(){if(Zt)return gt;Zt=1;const{humanReadableArgName:t}=$t();class e{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(r){const s=r.commands.filter(o=>!o._hidden),i=r._getHelpCommand();return i&&!i._hidden&&s.push(i),this.sortSubcommands&&s.sort((o,a)=>o.name().localeCompare(a.name())),s}compareOptions(r,s){const i=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return i(r).localeCompare(i(s))}visibleOptions(r){const s=r.options.filter(o=>!o.hidden),i=r._getHelpOption();if(i&&!i.hidden){const o=i.short&&r._findOption(i.short),a=i.long&&r._findOption(i.long);!o&&!a?s.push(i):i.long&&!a?s.push(r.createOption(i.long,i.description)):i.short&&!o&&s.push(r.createOption(i.short,i.description))}return this.sortOptions&&s.sort(this.compareOptions),s}visibleGlobalOptions(r){if(!this.showGlobalOptions)return[];const s=[];for(let i=r.parent;i;i=i.parent){const o=i.options.filter(a=>!a.hidden);s.push(...o)}return this.sortOptions&&s.sort(this.compareOptions),s}visibleArguments(r){return r._argsDescription&&r.registeredArguments.forEach(s=>{s.description=s.description||r._argsDescription[s.name()]||""}),r.registeredArguments.find(s=>s.description)?r.registeredArguments:[]}subcommandTerm(r){const s=r.registeredArguments.map(i=>t(i)).join(" ");return r._name+(r._aliases[0]?"|"+r._aliases[0]:"")+(r.options.length?" [options]":"")+(s?" "+s:"")}optionTerm(r){return r.flags}argumentTerm(r){return r.name()}longestSubcommandTermLength(r,s){return s.visibleCommands(r).reduce((i,o)=>Math.max(i,s.subcommandTerm(o).length),0)}longestOptionTermLength(r,s){return s.visibleOptions(r).reduce((i,o)=>Math.max(i,s.optionTerm(o).length),0)}longestGlobalOptionTermLength(r,s){return s.visibleGlobalOptions(r).reduce((i,o)=>Math.max(i,s.optionTerm(o).length),0)}longestArgumentTermLength(r,s){return s.visibleArguments(r).reduce((i,o)=>Math.max(i,s.argumentTerm(o).length),0)}commandUsage(r){let s=r._name;r._aliases[0]&&(s=s+"|"+r._aliases[0]);let i="";for(let o=r.parent;o;o=o.parent)i=o.name()+" "+i;return i+s+" "+r.usage()}commandDescription(r){return r.description()}subcommandDescription(r){return r.summary()||r.description()}optionDescription(r){const s=[];return r.argChoices&&s.push(`choices: ${r.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),r.defaultValue!==void 0&&(r.required||r.optional||r.isBoolean()&&typeof r.defaultValue=="boolean")&&s.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),r.presetArg!==void 0&&r.optional&&s.push(`preset: ${JSON.stringify(r.presetArg)}`),r.envVar!==void 0&&s.push(`env: ${r.envVar}`),s.length>0?`${r.description} (${s.join(", ")})`:r.description}argumentDescription(r){const s=[];if(r.argChoices&&s.push(`choices: ${r.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),r.defaultValue!==void 0&&s.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),s.length>0){const i=`(${s.join(", ")})`;return r.description?`${r.description} ${i}`:i}return r.description}formatHelp(r,s){const i=s.padWidth(r,s),o=s.helpWidth||80,a=2,l=2;function f(c,h){if(h){const d=`${c.padEnd(i+l)}${h}`;return s.wrap(d,o-a,i+l)}return c}function m(c){return c.join(`
2
- `).replace(/^/gm," ".repeat(a))}let E=[`Usage: ${s.commandUsage(r)}`,""];const p=s.commandDescription(r);p.length>0&&(E=E.concat([s.wrap(p,o,0),""]));const _=s.visibleArguments(r).map(c=>f(s.argumentTerm(c),s.argumentDescription(c)));_.length>0&&(E=E.concat(["Arguments:",m(_),""]));const T=s.visibleOptions(r).map(c=>f(s.optionTerm(c),s.optionDescription(c)));if(T.length>0&&(E=E.concat(["Options:",m(T),""])),this.showGlobalOptions){const c=s.visibleGlobalOptions(r).map(h=>f(s.optionTerm(h),s.optionDescription(h)));c.length>0&&(E=E.concat(["Global Options:",m(c),""]))}const u=s.visibleCommands(r).map(c=>f(s.subcommandTerm(c),s.subcommandDescription(c)));return u.length>0&&(E=E.concat(["Commands:",m(u),""])),E.join(`
3
- `)}padWidth(r,s){return Math.max(s.longestOptionTermLength(r,s),s.longestGlobalOptionTermLength(r,s),s.longestSubcommandTermLength(r,s),s.longestArgumentTermLength(r,s))}wrap(r,s,i,o=40){const a=" \\f\\t\\v   -    \uFEFF",l=new RegExp(`[\\n][${a}]+`);if(r.match(l))return r;const f=s-i;if(f<o)return r;const m=r.slice(0,i),E=r.slice(i).replace(`\r
4
- `,`
5
- `),p=" ".repeat(i),T="\\s​",u=new RegExp(`
6
- |.{1,${f-1}}([${T}]|$)|[^${T}]+?([${T}]|$)`,"g"),c=E.match(u)||[];return m+c.map((h,d)=>h===`
7
- `?"":(d>0?p:"")+h.trimEnd()).join(`
8
- `)}}return gt.Help=e,gt}var Ze={},Vt;function Pn(){if(Vt)return Ze;Vt=1;const{InvalidArgumentError:t}=st();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=s(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 f=this.negativeOptions.get(l).presetArg,m=f!==void 0?f:!1;return a.negate===(m===o)}}function r(i){return i.split("-").reduce((o,a)=>o+a[0].toUpperCase()+a.slice(1))}function s(i){let o,a;const l=i.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 Ze.Option=e,Ze.DualOptions=n,Ze}var ft={},Ht;function ns(){if(Ht)return ft;Ht=1;const t=3;function e(r,s){if(Math.abs(r.length-s.length)>t)return Math.max(r.length,s.length);const i=[];for(let o=0;o<=r.length;o++)i[o]=[o];for(let o=0;o<=s.length;o++)i[0][o]=o;for(let o=1;o<=s.length;o++)for(let a=1;a<=r.length;a++){let l=1;r[a-1]===s[o-1]?l=0:l=1,i[a][o]=Math.min(i[a-1][o]+1,i[a][o-1]+1,i[a-1][o-1]+l),a>1&&o>1&&r[a-1]===s[o-2]&&r[a-2]===s[o-1]&&(i[a][o]=Math.min(i[a][o],i[a-2][o-2]+1))}return i[r.length][s.length]}function n(r,s){if(!s||s.length===0)return"";s=Array.from(new Set(s));const i=r.startsWith("--");i&&(r=r.slice(2),s=s.map(f=>f.slice(2)));let o=[],a=t;const l=.4;return s.forEach(f=>{if(f.length<=1)return;const m=e(r,f),E=Math.max(r.length,f.length);(E-m)/E>l&&(m<a?(a=m,o=[f]):m===a&&o.push(f))}),o.sort((f,m)=>f.localeCompare(m)),i&&(o=o.map(f=>`--${f}`)),o.length>1?`
9
- (Did you mean one of ${o.join(", ")}?)`:o.length===1?`
10
- (Did you mean ${o[0]}?)`:""}return ft.suggestSimilar=n,ft}var Kt;function rs(){if(Kt)return dt;Kt=1;const t=Lr.EventEmitter,e=Wr,n=$n,r=Zr,s=q,{Argument:i,humanReadableArgName:o}=$t(),{CommanderError:a}=st(),{Help:l}=xn(),{Option:f,DualOptions:m}=Pn(),{suggestSimilar:E}=ns();class p 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=>s.stdout.write(c),writeErr:c=>s.stderr.write(c),getOutHelpWidth:()=>s.stdout.isTTY?s.stdout.columns:void 0,getErrHelpWidth:()=>s.stderr.isTTY?s.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,g=h;typeof d=="object"&&d!==null&&(g=d,d=null),g=g||{};const[,F,$]=u.match(/([^ ]+) *(.*)/),A=this.createCommand(F);return d&&(A.description(d),A._executableHandler=!0),g.isDefault&&(this._defaultCommandName=A._name),A._hidden=!!(g.noHelp||g.hidden),A._executableFile=g.executableFile||null,$&&A.arguments($),this._registerCommand(A),A.parent=this,A.copyInheritedSettings(this),d?this:A}createCommand(u){return new p(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 i(u,c)}argument(u,c,h,d){const g=this.createArgument(u,c);return typeof h=="function"?g.default(d).argParser(h):g.default(h),this.addArgument(g),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(/([^ ]+) *(.*)/),g=c??"display help for command",F=this.createCommand(h);return F.helpOption(!1),d&&F.arguments(d),g&&F.description(g),this._addImplicitHelpCommand=!0,this._helpCommand=F,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)),s.exit(u)}action(u){const c=h=>{const d=this.registeredArguments.length,g=h.slice(0,d);return this._storeOptionsAsProperties?g[d]=this:g[d]=this.opts(),g.push(this),u.apply(this,g)};return this._actionHandler=c,this}createOption(u,c){return new f(u,c)}_callParseArg(u,c,h,d){try{return u.parseArg(c,h)}catch(g){if(g.code==="commander.invalidArgument"){const F=`${d} ${g.message}`;this.error(F,{exitCode:g.exitCode,code:g.code})}throw g}}_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("|"),g=c(u).join("|");throw new Error(`cannot add command '${g}' 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 g=u.long.replace(/^--no-/,"--");this._findOption(g)||this.setOptionValueWithSource(h,u.defaultValue===void 0?!0:u.defaultValue,"default")}else u.defaultValue!==void 0&&this.setOptionValueWithSource(h,u.defaultValue,"default");const d=(g,F,$)=>{g==null&&u.presetArg!==void 0&&(g=u.presetArg);const A=this.getOptionValue(h);g!==null&&u.parseArg?g=this._callParseArg(u,g,A,F):g!==null&&u.variadic&&(g=u._concatValue(g,A)),g==null&&(u.negate?g=!1:u.isBoolean()||u.optional?g=!0:g=""),this.setOptionValueWithSource(h,g,$)};return this.on("option:"+c,g=>{const F=`error: option '${u.flags}' argument '${g}' is invalid.`;d(g,F,"cli")}),u.envVar&&this.on("optionEnv:"+c,g=>{const F=`error: option '${u.flags}' value '${g}' from env '${u.envVar}' is invalid.`;d(g,F,"env")}),this}_optionEx(u,c,h,d,g){if(typeof c=="object"&&c instanceof f)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const F=this.createOption(c,h);if(F.makeOptionMandatory(!!u.mandatory),typeof d=="function")F.default(g).argParser(d);else if(d instanceof RegExp){const $=d;d=(A,B)=>{const R=$.exec(A);return R?R[0]:B},F.default(g).argParser(d)}else F.default(d);return this.addOption(F)}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){s.versions?.electron&&(c.from="electron");const d=s.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(c.from="eval")}u===void 0&&(u=s.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":s.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 g(R,X){const j=n.resolve(R,X);if(r.existsSync(j))return j;if(d.includes(n.extname(X)))return;const w=d.find(z=>r.existsSync(`${j}${z}`));if(w)return`${j}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let F=u._executableFile||`${this._name}-${u._name}`,$=this._executableDir||"";if(this._scriptPath){let R;try{R=r.realpathSync(this._scriptPath)}catch{R=this._scriptPath}$=n.resolve(n.dirname(R),$)}if($){let R=g($,F);if(!R&&!u._executableFile&&this._scriptPath){const X=n.basename(this._scriptPath,n.extname(this._scriptPath));X!==this._name&&(R=g($,`${X}-${u._name}`))}F=R||F}h=d.includes(n.extname(F));let A;s.platform!=="win32"?h?(c.unshift(F),c=_(s.execArgv).concat(c),A=e.spawn(s.argv[0],c,{stdio:"inherit"})):A=e.spawn(F,c,{stdio:"inherit"}):(c.unshift(F),c=_(s.execArgv).concat(c),A=e.spawn(s.execPath,c,{stdio:"inherit"})),A.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(X=>{s.on(X,()=>{A.killed===!1&&A.exitCode===null&&A.kill(X)})});const B=this._exitCallback;A.on("close",R=>{R=R??1,B?B(new a(R,"commander.executeSubCommandAsync","(close)")):s.exit(R)}),A.on("error",R=>{if(R.code==="ENOENT"){const X=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",j=`'${F}' 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
- - ${X}`;throw new Error(j)}else if(R.code==="EACCES")throw new Error(`'${F}' not executable`);if(!B)s.exit(1);else{const X=new a(1,"commander.executeSubCommandAsync","(error)");X.nestedError=R,B(X)}}),this.runningCommand=A}_dispatchSubcommand(u,c,h){const d=this._findCommand(u);d||this.help({error:!0});let g;return g=this._chainOrCallSubCommandHook(g,d,"preSubcommand"),g=this._chainOrCall(g,()=>{if(d._executableHandler)this._executeSubCommand(d,c.concat(h));else return d._parseCommand(c,h)}),g}_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,g)=>{let F=d;if(d!==null&&h.parseArg){const $=`error: command-argument value '${d}' is invalid for argument '${h.name()}'.`;F=this._callParseArg(h,d,g,$)}return F};this._checkNumberOfArguments();const c=[];this.registeredArguments.forEach((h,d)=>{let g=h.defaultValue;h.variadic?d<this.args.length?(g=this.args.slice(d),h.parseArg&&(g=g.reduce((F,$)=>u(h,$,F),h.defaultValue))):g===void 0&&(g=[]):d<this.args.length&&(g=this.args[d],h.parseArg&&(g=u(h,g,h.defaultValue))),c[d]=g}),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(g=>g._lifeCycleHooks[c]!==void 0).forEach(g=>{g._lifeCycleHooks[c].forEach(F=>{d.push({hookedCommand:g,callback:F})})}),c==="postAction"&&d.reverse(),d.forEach(g=>{h=this._chainOrCall(h,()=>g.callback(g.hookedCommand,this))}),h}_chainOrCallSubCommandHook(u,c,h){let d=u;return this._lifeCycleHooks[h]!==void 0&&this._lifeCycleHooks[h].forEach(g=>{d=this._chainOrCall(d,()=>g(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])},g=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let F;return F=this._chainOrCallHooks(F,"preAction"),F=this._chainOrCall(F,()=>this._actionHandler(this.processedArgs)),this.parent&&(F=this._chainOrCall(F,()=>{this.parent.emit(g,u,c)})),F=this._chainOrCallHooks(F,"postAction"),F}if(this.parent&&this.parent.listenerCount(g))d(),this._processArguments(),this.parent.emit(g,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(g=>h.conflictsWith.includes(g.attributeName()));d&&this._conflictingOption(h,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(u=>{u._checkForConflictingLocalOptions()})}parseOptions(u){const c=[],h=[];let d=c;const g=u.slice();function F(A){return A.length>1&&A[0]==="-"}let $=null;for(;g.length;){const A=g.shift();if(A==="--"){d===h&&d.push(A),d.push(...g);break}if($&&!F(A)){this.emit(`option:${$.name()}`,A);continue}if($=null,F(A)){const B=this._findOption(A);if(B){if(B.required){const R=g.shift();R===void 0&&this.optionMissingArgument(B),this.emit(`option:${B.name()}`,R)}else if(B.optional){let R=null;g.length>0&&!F(g[0])&&(R=g.shift()),this.emit(`option:${B.name()}`,R)}else this.emit(`option:${B.name()}`);$=B.variadic?B:null;continue}}if(A.length>2&&A[0]==="-"&&A[1]!=="-"){const B=this._findOption(`-${A[1]}`);if(B){B.required||B.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${B.name()}`,A.slice(2)):(this.emit(`option:${B.name()}`),g.unshift(`-${A.slice(2)}`));continue}}if(/^--[^=]+=/.test(A)){const B=A.indexOf("="),R=this._findOption(A.slice(0,B));if(R&&(R.required||R.optional)){this.emit(`option:${R.name()}`,A.slice(B+1));continue}}if(F(A)&&(d=h),(this._enablePositionalOptions||this._passThroughOptions)&&c.length===0&&h.length===0){if(this._findCommand(A)){c.push(A),g.length>0&&h.push(...g);break}else if(this._getHelpCommand()&&A===this._getHelpCommand().name()){c.push(A),g.length>0&&c.push(...g);break}else if(this._defaultCommandName){h.push(A),g.length>0&&h.push(...g);break}}if(this._passThroughOptions){d.push(A),g.length>0&&d.push(...g);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,g=h.code||"commander.error";this._exit(d,g,u)}_parseOptionsEnv(){this.options.forEach(u=>{if(u.envVar&&u.envVar in s.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()}`,s.env[u.envVar]):this.emit(`optionEnv:${u.name()}`))}})}_parseOptionsImplied(){const u=new m(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=F=>{const $=F.attributeName(),A=this.getOptionValue($),B=this.options.find(X=>X.negate&&$===X.attributeName()),R=this.options.find(X=>!X.negate&&$===X.attributeName());return B&&(B.presetArg===void 0&&A===!1||B.presetArg!==void 0&&A===B.presetArg)?B:R||F},d=F=>{const $=h(F),A=$.attributeName();return this.getOptionValueSource(A)==="env"?`environment variable '${$.envVar}'`:`option '${$.flags}'`},g=`error: ${d(u)} cannot be used with ${d(c)}`;this.error(g,{code:"commander.conflictingOption"})}unknownOption(u){if(this._allowUnknownOption)return;let c="";if(u.startsWith("--")&&this._showSuggestionAfterError){let d=[],g=this;do{const F=g.createHelp().visibleOptions(g).filter($=>$.long).map($=>$.long);d=d.concat(F),g=g.parent}while(g&&!g._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",g=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${c} argument${h} but got ${u.length}.`;this.error(g,{code:"commander.excessArguments"})}unknownCommand(){const u=this.args[0];let c="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(g=>{d.push(g.name()),g.alias()&&d.push(g.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(g=>g.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(g=>g.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=s.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,g=>{let F;typeof c=="function"?F=c({error:g.error,command:g.command}):F=c,F&&g.write(`${F}
22
- `)}),this}_outputHelpIfRequested(u){const c=this._getHelpOption();c&&u.find(d=>c.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function _(T){return T.map(u=>{if(!u.startsWith("--inspect"))return u;let c,h="127.0.0.1",d="9229",g;return(g=u.match(/^(--inspect(-brk)?)$/))!==null?c=g[1]:(g=u.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(c=g[1],/^\d+$/.test(g[3])?d=g[3]:h=g[3]):(g=u.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(c=g[1],h=g[3],d=g[4]),c&&d!=="0"?`${c}=${h}:${parseInt(d)+1}`:u})}return dt.Command=p,dt}var qt;function ss(){if(qt)return oe;qt=1;const{Argument:t}=$t(),{Command:e}=rs(),{CommanderError:n,InvalidArgumentError:r}=st(),{Help:s}=xn(),{Option:i}=Pn();return oe.program=new e,oe.createCommand=o=>new e(o),oe.createOption=(o,a)=>new i(o,a),oe.createArgument=(o,a)=>new t(o,a),oe.Command=e,oe.Option=i,oe.Argument=t,oe.Help=s,oe.CommanderError=n,oe.InvalidArgumentError=r,oe.InvalidOptionArgumentError=r,oe}var is=ss();const os=D.getDefaultExportFromCjs(is),{program:Sh,createCommand:wh,createArgument:Ch,createOption:bh,CommanderError:Ah,InvalidArgumentError:Th,InvalidOptionArgumentError:kh,Command:as,Argument:Ih,Option:$h,Help:Oh}=os;var de={exports:{}};const us="17.2.1",cs={version:us};var Yt;function ls(){if(Yt)return de.exports;Yt=1;const t=k,e=C,n=le,r=Vr,i=cs.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 f(){return process.stdout.isTTY}function m(w){return f()?`\x1B[2m${w}\x1B[0m`:w}const E=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function p(w){const z={};let M=w.toString();M=M.replace(/\r\n?/mg,`
23
- `);let G;for(;(G=E.exec(M))!=null;){const ee=G[1];let L=G[2]||"";L=L.trim();const x=L[0];L=L.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),x==='"'&&(L=L.replace(/\\n/g,`
24
- `),L=L.replace(/\\r/g,"\r")),z[ee]=L}return z}function _(w){w=w||{};const z=g(w);w.path=z;const M=j.configDotenv(w);if(!M.parsed){const x=new Error(`MISSING_DATA: Cannot parse ${z} for an unknown reason`);throw x.code="MISSING_DATA",x}const G=h(w).split(","),ee=G.length;let L;for(let x=0;x<ee;x++)try{const te=G[x].trim(),ue=d(M,te);L=j.decrypt(ue.ciphertext,ue.key);break}catch(te){if(x+1>=ee)throw te}return j.parse(L)}function T(w){console.error(`[dotenv@${i}][WARN] ${w}`)}function u(w){console.log(`[dotenv@${i}][DEBUG] ${w}`)}function c(w){console.log(`[dotenv@${i}] ${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 M;try{M=new URL(z)}catch(te){if(te.code==="ERR_INVALID_URL"){const ue=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 ue.code="INVALID_DOTENV_KEY",ue}throw te}const G=M.password;if(!G){const te=new Error("INVALID_DOTENV_KEY: Missing key part");throw te.code="INVALID_DOTENV_KEY",te}const ee=M.searchParams.get("environment");if(!ee){const te=new Error("INVALID_DOTENV_KEY: Missing environment part");throw te.code="INVALID_DOTENV_KEY",te}const L=`DOTENV_VAULT_${ee.toUpperCase()}`,x=w.parsed[L];if(!x){const te=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${L} in your .env.vault file.`);throw te.code="NOT_FOUND_DOTENV_ENVIRONMENT",te}return{ciphertext:x,key:G}}function g(w){let z=null;if(w&&w.path&&w.path.length>0)if(Array.isArray(w.path))for(const M of w.path)t.existsSync(M)&&(z=M.endsWith(".vault")?M:`${M}.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 F(w){return w[0]==="~"?e.join(n.homedir(),w.slice(1)):w}function $(w){const z=l(process.env.DOTENV_CONFIG_DEBUG||w&&w.debug),M=l(process.env.DOTENV_CONFIG_QUIET||w&&w.quiet);(z||!M)&&c("Loading env from encrypted .env.vault");const G=j._parseVault(w);let ee=process.env;return w&&w.processEnv!=null&&(ee=w.processEnv),j.populate(ee,G,w),{parsed:G}}function A(w){const z=e.resolve(process.cwd(),".env");let M="utf8",G=process.env;w&&w.processEnv!=null&&(G=w.processEnv);let ee=l(G.DOTENV_CONFIG_DEBUG||w&&w.debug),L=l(G.DOTENV_CONFIG_QUIET||w&&w.quiet);w&&w.encoding?M=w.encoding:ee&&u("No encoding is specified. UTF-8 is used by default");let x=[z];if(w&&w.path)if(!Array.isArray(w.path))x=[F(w.path)];else{x=[];for(const ce of w.path)x.push(F(ce))}let te;const ue={};for(const ce of x)try{const ve=j.parse(t.readFileSync(ce,{encoding:M}));j.populate(ue,ve,w)}catch(ve){ee&&u(`Failed to load ${ce} ${ve.message}`),te=ve}const lt=j.populate(G,ue,w);if(ee=l(G.DOTENV_CONFIG_DEBUG||ee),L=l(G.DOTENV_CONFIG_QUIET||L),ee||!L){const ce=Object.keys(lt).length,ve=[];for(const Mt of x)try{const je=e.relative(process.cwd(),Mt);ve.push(je)}catch(je){ee&&u(`Failed to load ${Mt} ${je.message}`),te=je}c(`injecting env (${ce}) from ${ve.join(",")} ${m(`-- tip: ${a()}`)}`)}return te?{parsed:ue,error:te}:{parsed:ue}}function B(w){if(h(w).length===0)return j.configDotenv(w);const z=g(w);return z?j._configVault(w):(T(`You set DOTENV_KEY but you are missing a .env.vault file at ${z}. Did you forget to build it?`),j.configDotenv(w))}function R(w,z){const M=Buffer.from(z.slice(-64),"hex");let G=Buffer.from(w,"base64");const ee=G.subarray(0,12),L=G.subarray(-16);G=G.subarray(12,-16);try{const x=r.createDecipheriv("aes-256-gcm",M,ee);return x.setAuthTag(L),`${x.update(G)}${x.final()}`}catch(x){const te=x instanceof RangeError,ue=x.message==="Invalid key length",lt=x.message==="Unsupported state or unable to authenticate data";if(te||ue){const ce=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw ce.code="INVALID_DOTENV_KEY",ce}else if(lt){const ce=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw ce.code="DECRYPTION_FAILED",ce}else throw x}}function X(w,z,M={}){const G=!!(M&&M.debug),ee=!!(M&&M.override),L={};if(typeof z!="object"){const x=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw x.code="OBJECT_REQUIRED",x}for(const x of Object.keys(z))Object.prototype.hasOwnProperty.call(w,x)?(ee===!0&&(w[x]=z[x],L[x]=z[x]),G&&u(ee===!0?`"${x}" is already defined and WAS overwritten`:`"${x}" is already defined and was NOT overwritten`)):(w[x]=z[x],L[x]=z[x]);return L}const j={configDotenv:A,_configVault:$,_parseVault:_,config:B,decrypt:R,parse:p,populate:X};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 hs=ls();const Rn=D.getDefaultExportFromCjs(hs),pt=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`,Z={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(Z.modifier);const ds=Object.keys(Z.color),gs=Object.keys(Z.bgColor);[...ds,...gs];function fs(){const t=new Map;for(const[e,n]of Object.entries(Z)){for(const[r,s]of Object.entries(n))Z[r]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[r]=Z[r],t.set(s[0],s[1]);Object.defineProperty(Z,e,{value:n,enumerable:!1})}return Object.defineProperty(Z,"codes",{value:t,enumerable:!1}),Z.color.close="\x1B[39m",Z.bgColor.close="\x1B[49m",Z.color.ansi=Jt(),Z.color.ansi256=Qt(),Z.color.ansi16m=Xt(),Z.bgColor.ansi=Jt(pt),Z.bgColor.ansi256=Qt(pt),Z.bgColor.ansi16m=Xt(pt),Object.defineProperties(Z,{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(i=>i+i).join(""));const s=Number.parseInt(r,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:e=>Z.rgbToAnsi256(...Z.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let n,r,s;if(e>=232)n=((e-232)*10+8)/255,r=n,s=n;else{e-=16;const a=e%36;n=Math.floor(e/36)/5,r=Math.floor(a/6)/5,s=a%6/5}const i=Math.max(n,r,s)*2;if(i===0)return 30;let o=30+(Math.round(s)<<2|Math.round(r)<<1|Math.round(n));return i===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,n,r)=>Z.ansi256ToAnsi(Z.rgbToAnsi256(e,n,r)),enumerable:!1},hexToAnsi:{value:e=>Z.ansi256ToAnsi(Z.hexToAnsi256(e)),enumerable:!1}}),Z}const ge=fs(),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},ps={stdout:tn,stderr:tn};function ms(t,e,n){let r=t.indexOf(e);if(r===-1)return t;const s=e.length;let i=0,o="";do o+=t.slice(i,r)+e+n,i=r+s,r=t.indexOf(e,i);while(r!==-1);return o+=t.slice(i),o}function Ds(t,e,n,r){let s=0,i="";do{const o=t[r-1]==="\r";i+=t.slice(s,o?r-1:r)+e+(o?`\r
25
- `:`
26
- `)+n,s=r+1,r=t.indexOf(`
27
- `,s)}while(r!==-1);return i+=t.slice(s),i}const{stdout:nn,stderr:rn}=ps,_t=Symbol("GENERATOR"),ke=Symbol("STYLER"),xe=Symbol("IS_EMPTY"),sn=["ansi","ansi","ansi256","ansi16m"],Ie=Object.create(null),Es=(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},ys=t=>{const e=(...n)=>n.join(" ");return Es(e,t),Object.setPrototypeOf(e,Ue.prototype),e};function Ue(t){return ys(t)}Object.setPrototypeOf(Ue.prototype,Function.prototype);for(const[t,e]of Object.entries(ge))Ie[t]={get(){const n=Xe(this,St(e.open,e.close,this[ke]),this[xe]);return Object.defineProperty(this,t,{value:n}),n}};Ie.visible={get(){const t=Xe(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),vs=["rgb","hex","ansi256"];for(const t of vs){Ie[t]={get(){const{level:n}=this;return function(...r){const s=St(Ft(t,sn[n],"color",...r),ge.color.close,this[ke]);return Xe(this,s,this[xe])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);Ie[e]={get(){const{level:n}=this;return function(...r){const s=St(Ft(t,sn[n],"bgColor",...r),ge.bgColor.close,this[ke]);return Xe(this,s,this[xe])}}}}const _s=Object.defineProperties(()=>{},{...Ie,level:{enumerable:!0,get(){return this[_t].level},set(t){this[_t].level=t}}}),St=(t,e,n)=>{let r,s;return n===void 0?(r=t,s=e):(r=n.openAll+t,s=e+n.closeAll),{open:t,close:e,openAll:r,closeAll:s,parent:n}},Xe=(t,e,n)=>{const r=(...s)=>Fs(r,s.length===1?""+s[0]:s.join(" "));return Object.setPrototypeOf(r,_s),r[_t]=t,r[ke]=e,r[xe]=n,r},Fs=(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:s}=n;if(e.includes("\x1B"))for(;n!==void 0;)e=ms(e,n.close,n.open),n=n.parent;const i=e.indexOf(`
28
- `);return i!==-1&&(e=Ds(e,s,r,i)),r+e+s};Object.defineProperties(Ue.prototype,Ie);const Ss=Ue();Ue({level:rn?rn.level:0});const ws=(t,e,n,r)=>{if(n==="length"||n==="prototype"||n==="arguments"||n==="caller")return;const s=Object.getOwnPropertyDescriptor(t,n),i=Object.getOwnPropertyDescriptor(e,n);!Cs(s,i)&&r||Object.defineProperty(t,n,i)},Cs=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)},bs=(t,e)=>{const n=Object.getPrototypeOf(e);n!==Object.getPrototypeOf(t)&&Object.setPrototypeOf(t,n)},As=(t,e)=>`/* Wrapped ${t}*/
29
- ${e}`,Ts=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ks=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Is=(t,e,n)=>{const r=n===""?"":`with ${n.trim()}() `,s=As.bind(null,r,e.toString());Object.defineProperty(s,"name",ks);const{writable:i,enumerable:o,configurable:a}=Ts;Object.defineProperty(t,"toString",{value:s,writable:i,enumerable:o,configurable:a})};function $s(t,e,{ignoreNonConfigurable:n=!1}={}){const{name:r}=t;for(const s of Reflect.ownKeys(e))ws(t,e,s,n);return bs(t,e),Is(t,e,r),t}const et=new WeakMap,Nn=(t,e={})=>{if(typeof t!="function")throw new TypeError("Expected a function");let n,r=0;const s=t.displayName||t.name||"<anonymous>",i=function(...o){if(et.set(i,++r),r===1)n=t.apply(this,o),t=void 0;else if(e.throw===!0)throw new Error(`Function \`${s}\` can only be called once`);return n};return $s(i,t),et.set(i,r),i};Nn.callCount=t=>{if(!et.has(t))throw new Error(`The given function \`${t.name}\` is not wrapped by the \`onetime\` package`);return et.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 Qe=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",mt=Symbol.for("signal-exit emitter"),Dt=globalThis,Os=Object.defineProperty.bind(Object);class xs{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Dt[mt])return Dt[mt];Os(Dt,mt,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,n){this.listeners[e].push(n)}removeListener(e,n){const r=this.listeners[e],s=r.indexOf(n);s!==-1&&(s===0&&r.length===1?r.length=0:r.splice(s,1))}emit(e,n,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let s=!1;for(const i of this.listeners[e])s=i(n,r)===!0||s;return e==="exit"&&(s=this.emit("afterExit",n,r)||s),s}}class Bn{}const Ps=t=>({onExit(e,n){return t.onExit(e,n)},load(){return t.load()},unload(){return t.unload()}});class Rs extends Bn{onExit(){return()=>{}}load(){}unload(){}}class Ns extends Bn{#o=wt.platform==="win32"?"SIGINT":"SIGHUP";#n=new xs;#e;#s;#d;#t={};#i=!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:s}=this.#n;const i=e;if(typeof i.__signal_exit_emitter__=="object"&&typeof i.__signal_exit_emitter__.count=="number"&&(s+=i.__signal_exit_emitter__.count),r.length===s){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.#s=e.emit}onExit(e,n){if(!Qe(this.#e))return()=>{};this.#i===!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.#i){this.#i=!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.#i&&(this.#i=!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.#s,this.#e.reallyExit=this.#d,this.#n.count-=1)}#r(e){return Qe(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.#s;if(e==="exit"&&Qe(this.#e)){typeof n[0]=="number"&&(this.#e.exitCode=n[0]);const s=r.call(this.#e,e,...n);return this.#n.emit("exit",this.#e.exitCode,null),s}else return r.call(this.#e,e,...n)}}const wt=globalThis.process,{onExit:Bs}=Ps(Qe(wt)?new Ns(wt):new Rs),on=q.stderr.isTTY?q.stderr:q.stdout.isTTY?q.stdout:void 0,Us=on?Nn(()=>{Bs(()=>{on.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{};let tt=!1;const Se={};Se.show=(t=q.stderr)=>{t.isTTY&&(tt=!1,t.write("\x1B[?25h"))};Se.hide=(t=q.stderr)=>{t.isTTY&&(Us(),tt=!0,t.write("\x1B[?25l"))};Se.toggle=(t,e)=>{t!==void 0&&(tt=t),tt?Se.show(e):Se.hide(e)};const zs={interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},Ms={interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},Gs={interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},js={interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},Ls={interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},Ws={interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},Zs={interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},Vs={interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},Hs={interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},Ks={interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},qs={interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},Ys={interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},Js={interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},Qs={interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},Xs={interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},ei={interval:130,frames:["-","\\","|","/"]},ti={interval:100,frames:["⠂","-","–","—","–","-"]},ni={interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},ri={interval:400,frames:[". ",".. ","..."," "]},si={interval:200,frames:[". ",".. ","..."," .."," ."," "]},ii={interval:70,frames:["✶","✸","✹","✺","✹","✷"]},oi={interval:80,frames:["+","x","*"]},ai={interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},ui={interval:100,frames:["☱","☲","☴"]},ci={interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},li={interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},hi={interval:140,frames:[" ",".","o","O","@","*"," "]},di={interval:120,frames:[".","o","O","°","O","o","."]},gi={interval:100,frames:["▓","▒","░"]},fi={interval:120,frames:["⠁","⠂","⠄","⠂"]},pi={interval:120,frames:["▖","▘","▝","▗"]},mi={interval:100,frames:["▌","▀","▐","▄"]},Di={interval:50,frames:["◢","◣","◤","◥"]},Ei={interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},yi={interval:100,frames:["◜","◠","◝","◞","◡","◟"]},vi={interval:120,frames:["◡","⊙","◠"]},_i={interval:180,frames:["◰","◳","◲","◱"]},Fi={interval:120,frames:["◴","◷","◶","◵"]},Si={interval:50,frames:["◐","◓","◑","◒"]},wi={interval:100,frames:["╫","╪"]},Ci={interval:250,frames:["⊶","⊷"]},bi={interval:80,frames:["▫","▪"]},Ai={interval:120,frames:["□","■"]},Ti={interval:100,frames:["■","□","▪","▫"]},ki={interval:100,frames:["▮","▯"]},Ii={interval:300,frames:["ဝ","၀"]},$i={interval:80,frames:["⦾","⦿"]},Oi={interval:100,frames:["◍","◌"]},xi={interval:100,frames:["◉","◎"]},Pi={interval:100,frames:["㊂","㊀","㊁"]},Ri={interval:50,frames:["⧇","⧆"]},Ni={interval:120,frames:["☗","☖"]},Bi={interval:80,frames:["=","*","-"]},Ui={interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},zi={interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},Mi={interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},Gi={interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},ji={interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},Li={interval:200,frames:["😄 ","😝 "]},Wi={interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},Zi={interval:100,frames:["💛 ","💙 ","💜 ","💚 ","❤️ "]},Vi={interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},Hi={interval:180,frames:["🌍 ","🌎 ","🌏 "]},Ki={interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},qi={interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},Yi={interval:140,frames:["🚶 ","🏃 "]},Ji={interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},Qi={interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},Xi={interval:100,frames:["d","q","p","b"]},eo={interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},to={interval:400,frames:["🌲","🎄"]},no={interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},ro={interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},so={interval:150,frames:["-","=","≡"]},io={interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},oo={interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},ao={interval:80,frames:["🤜    🤛 ","🤜    🤛 ","🤜    🤛 "," 🤜  🤛  ","  🤜🤛   "," 🤜✨🤛   ","🤜 ✨ 🤛  "]},uo={interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},co={interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","  ","  ","  "]},lo={interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},ho={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},go={interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},fo={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},po={interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},mo={interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},Do={interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]},Eo={dots:zs,dots2:Ms,dots3:Gs,dots4:js,dots5:Ls,dots6:Ws,dots7:Zs,dots8:Vs,dots9:Hs,dots10:Ks,dots11:qs,dots12:Ys,dots13:Js,dots8Bit:Qs,sand:Xs,line:ei,line2:ti,pipe:ni,simpleDots:ri,simpleDotsScrolling:si,star:ii,star2:oi,flip:ai,hamburger:ui,growVertical:ci,growHorizontal:li,balloon:hi,balloon2:di,noise:gi,bounce:fi,boxBounce:pi,boxBounce2:mi,triangle:Di,binary:Ei,arc:yi,circle:vi,squareCorners:_i,circleQuarters:Fi,circleHalves:Si,squish:wi,toggle:Ci,toggle2:bi,toggle3:Ai,toggle4:Ti,toggle5:ki,toggle6:Ii,toggle7:$i,toggle8:Oi,toggle9:xi,toggle10:Pi,toggle11:Ri,toggle12:Ni,toggle13:Bi,arrow:Ui,arrow2:zi,arrow3:Mi,bouncingBar:Gi,bouncingBall:ji,smiley:Li,monkey:Wi,hearts:Zi,clock:Vi,earth:Hi,material:Ki,moon:qi,runner:Yi,pong:Ji,shark:Qi,dqpb:Xi,weather:eo,christmas:to,grenade:no,point:ro,layer:so,betaWave:io,fingerDance:oo,fistBump:ao,soccerHeader:uo,mindblown:co,speaker:lo,orangePulse:ho,bluePulse:go,orangeBluePulse:fo,timeTravel:po,aesthetic:mo,dwarfFortress:Do};var Et,an;function yo(){if(an)return Et;an=1;const t=Object.assign({},Eo),e=Object.keys(t);return Object.defineProperty(t,"random",{get(){const n=Math.floor(Math.random()*e.length),r=e[n];return t[r]}}),Et=t,Et}var vo=yo();const Ve=D.getDefaultExportFromCjs(vo),He={info:"ℹ️",success:"✅",warning:"⚠️",error:"❌️"};function _o({onlyFirst:t=!1}={}){const s="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(s,t?void 0:"g")}const Fo=_o();function we(t){if(typeof t!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof t}\``);return t.replace(Fo,"")}function So(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 wo(t){return t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510}function Co(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 bo(t){if(!Number.isSafeInteger(t))throw new TypeError(`Expected a code point, got \`${typeof t}\`.`)}function Ao(t,{ambiguousAsWide:e=!1}={}){return bo(t),wo(t)||Co(t)||e&&So(t)?2:1}const To=()=>/[#*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,ko=new Intl.Segmenter,Io=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function $o(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 s=0;const i={ambiguousAsWide:!n};for(const{segment:o}of ko.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)&&!Io.test(o)){if(To().test(o)){s+=2;continue}s+=Ao(a,i)}}return s}function Oo({stream:t=process.stdout}={}){return!!(t&&t.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function xo(){const{env:t}=q,{TERM:e,TERM_PROGRAM:n}=t;return q.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 Po=3;class Ro{#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(){q.platform==="win32"||!q.stdin.isTTY||(q.stdin.setRawMode(!0),q.stdin.on("data",this.#s),q.stdin.resume())}#e(){q.stdin.isTTY&&(q.stdin.off("data",this.#s),q.stdin.pause(),q.stdin.setRawMode(!1))}#s(e){e[0]===Po&&q.emit("SIGINT")}}const un=new Ro;class No{#o=0;#n=!1;#e=0;#s=-1;#d=0;#t;#i;#r;#g;#p;#c;#l;#h;#m;#a;#u;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:q.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:Oo({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,q.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.#s}}),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.#i.interval??100}get spinner(){return this.#i}set spinner(e){if(this.#s=-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.#i=e}else if(!xo())this.#i=Ve.line;else if(e===void 0)this.#i=Ve.dots;else if(e!=="default"&&Ve[e])this.#i=Ve[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,"-"),s=" ".repeat(this.#h)+n+"--"+this.#m+"--"+r;this.#e=0;for(const i of we(s).split(`
30
- `))this.#e+=Math.max(1,Math.ceil($o(i,{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.#s===-1||e-this.#d>=this.interval)&&(this.#s=++this.#s%this.#i.frames.length,this.#d=e);const{frames:n}=this.#i;let r=n[this.#s];this.color&&(r=Ss[this.color](r));const s=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",i=typeof this.text=="string"?" "+this.text:"",o=typeof this.#u=="string"&&this.#u!==""?" "+this.#u:"";return s+r+i+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&&Se.hide(this.#r),this.#t.discardStdin&&q.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.#s=0,this.clear(),this.#t.hideCursor&&Se.show(this.#r),this.#t.discardStdin&&q.stdin.isTTY&&this.#n&&(un.stop(),this.#n=!1),this):this}succeed(e){return this.stopAndPersist({symbol:He.success,text:e})}fail(e){return this.stopAndPersist({symbol:He.error,text:e})}warn(e){return this.stopAndPersist({symbol:He.warning,text:e})}info(e){return this.stopAndPersist({symbol:He.info,text:e})}stopAndPersist(e={}){if(this.#l)return this;const n=e.prefixText??this.#a,r=this.#D(n," "),s=e.symbol??" ",i=e.text??this.text,a=typeof i=="string"?(s?" ":"")+i:"",l=e.suffixText??this.#u,f=this.#E(l," "),m=r+s+a+f+`
32
- `;return this.stop(),this.#r.write(m),this}}function Bo(t){return new No(t)}class it{spinner;createSpinner(e){return this.spinner=Bo(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 O={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"},Y={CLAUDE_CODE:"claude-code",GEMINI_CLI:"gemini-cli"},V={STARTING:"starting",IDLE:"idle",PAUSED:"paused",STOPPED:"stopped",ERROR:"error"},cn={STDOUT:"stdout",STDERR:"stderr"},N={STATUS:"daemon-status",ERROR:"daemon-error",TERMINATE:"daemon-terminate",LIST:"daemon-list-agent-sessions",START_AGENT:"daemon-start-agent",STOP_AGENT:"daemon-stop-agent"},me={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 f;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(f=a._zod).traits??(f.traits=new Set),a._zod.traits.add(t),e(a,l);for(const m in o.prototype)m in a||Object.defineProperty(a,m,{value:o.prototype[m].bind(a)});a._zod.constr=o,a._zod.def=l}const s=n?.Parent??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function o(a){var l;const f=n?.Parent?new i:this;r(f,a),(l=f._zod).deferred??(l.deferred=[]);for(const m of f._zod.deferred)m();return f}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 Un={};function De(t){return Un}function Uo(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function zo(t,e){return typeof e=="bigint"?e.toString():e}function zn(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ot(t){return t==null}function xt(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Mo(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}function H(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 Pt(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function $e(t){return JSON.stringify(t)}const Mn=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Go=zn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function nt(t){if(Ct(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const n=e.prototype;return!(Ct(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const jo=new Set(["string","number","symbol"]);function ze(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 Lo(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const Wo={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 Zo(t,e){const n={},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return be(t,{...t._zod.def,shape:n,checks:[]})}function Vo(t,e){const n={...t._zod.def.shape},r=t._zod.def;for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return be(t,{...t._zod.def,shape:n,checks:[]})}function Ho(t,e){if(!nt(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 Pt(this,"shape",r),r},checks:[]};return be(t,n)}function Ko(t,e){return be(t,{...t._zod.def,get shape(){const n={...t._zod.def.shape,...e._zod.def.shape};return Pt(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function qo(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=t?new t({type:"optional",innerType:r[i]}):r[i])}else for(const i in r)s[i]=t?new t({type:"optional",innerType:r[i]}):r[i];return be(e,{...e._zod.def,shape:s,checks:[]})}function Yo(t,e,n){const r=e._zod.def.shape,s={...r};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new t({type:"nonoptional",innerType:r[i]}))}else for(const i in r)s[i]=new t({type:"nonoptional",innerType:r[i]});return be(e,{...e._zod.def,shape:s,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 Fe(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Ke(t){return typeof t=="string"?t:t?.message}function Ee(t,e,n){const r={...t,path:t.path??[]};if(!t.message){const s=Ke(t.inst?._zod.def?.error?.(t))??Ke(e?.error?.(t))??Ke(n.customError?.(t))??Ke(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Rt(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 Gn=(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,zo,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},jn=y("$ZodError",Gn),Ln=y("$ZodError",Gn,{Parent:Error});function Jo(t,e=n=>n.message){const n={},r=[];for(const s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function Qo(t,e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>s({issues:a}));else if(o.code==="invalid_key")s({issues:o.issues});else if(o.code==="invalid_element")s({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 f=o.path[l];l===o.path.length-1?(a[f]=a[f]||{_errors:[]},a[f]._errors.push(n(o))):a[f]=a[f]||{_errors:[]},a=a[f],l++}}};return s(t),r}const Xo=t=>(e,n,r,s)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Pe;if(o.issues.length){const a=new(s?.Err??t)(o.issues.map(l=>Ee(l,i,De())));throw Mn(a,s?.callee),a}return o.value},ea=t=>async(e,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=e._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const a=new(s?.Err??t)(o.issues.map(l=>Ee(l,i,De())));throw Mn(a,s?.callee),a}return o.value},Wn=t=>(e,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Pe;return i.issues.length?{success:!1,error:new(t??jn)(i.issues.map(o=>Ee(o,s,De())))}:{success:!0,data:i.value}},ta=Wn(Ln),Zn=t=>async(e,n,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(o=>Ee(o,s,De())))}:{success:!0,data:i.value}},na=Zn(Ln),ra=/^[cC][^\s-]{8,}$/,sa=/^[0-9a-z]+$/,ia=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,oa=/^[0-9a-vA-V]{20}$/,aa=/^[A-Za-z0-9]{27}$/,ua=/^[a-zA-Z0-9_-]{21}$/,ca=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,la=/^([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)$/,ha=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,da="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ga(){return new RegExp(da,"u")}const fa=/^(?:(?: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])$/,pa=/^(([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})$/,ma=/^((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])$/,Da=/^(([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])$/,Ea=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vn=/^[A-Za-z0-9_-]*$/,ya=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,va=/^\+(?:[0-9]){6,14}[0-9]$/,Hn="(?:(?:\\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])))",_a=new RegExp(`^${Hn}$`);function Kn(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(`^${Kn(t)}$`)}function Sa(t){const e=Kn({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(`^${Hn}T(?:${r})$`)}const wa=t=>{const e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ca=/^\d+$/,ba=/^-?\d+(?:\.\d+)?/i,Aa=/true|false/i,Ta=/^[^A-Z]*$/,ka=/^[^a-z]*$/,ie=y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),qn={number:"number",bigint:"bigint",object:"date"},Yn=y("$ZodCheckLessThan",(t,e)=>{ie.init(t,e);const n=qn[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?s.maximum=e.value:s.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})}}),Jn=y("$ZodCheckGreaterThan",(t,e)=>{ie.init(t,e);const n=qn[typeof e.value];t._zod.onattach.push(r=>{const s=r._zod.bag,i=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?s.minimum=e.value:s.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})}}),Ia=y("$ZodCheckMultipleOf",(t,e)=>{ie.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):Mo(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})}}),$a=y("$ZodCheckNumberFormat",(t,e)=>{ie.init(t,e),e.format=e.format||"float64";const n=e.format?.includes("int"),r=n?"int":"number",[s,i]=Wo[e.format];t._zod.onattach.push(o=>{const a=o._zod.bag;a.format=e.format,a.minimum=s,a.maximum=i,n&&(a.pattern=Ca)}),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<s&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>i&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:t})}}),Oa=y("$ZodCheckMaxLength",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ot(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const s=r.value;if(s.length<=e.maximum)return;const o=Rt(s);r.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),xa=y("$ZodCheckMinLength",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ot(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const s=r.value;if(s.length>=e.minimum)return;const o=Rt(s);r.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Pa=y("$ZodCheckLengthEquals",(t,e)=>{var n;ie.init(t,e),(n=t._zod.def).when??(n.when=r=>{const s=r.value;return!Ot(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{const s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{const s=r.value,i=s.length;if(i===e.length)return;const o=Rt(s),a=i>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})}}),ot=y("$ZodCheckStringFormat",(t,e)=>{var n,r;ie.init(t,e),t._zod.onattach.push(s=>{const i=s._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),Ra=y("$ZodCheckRegex",(t,e)=>{ot.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})}}),Na=y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ta),ot.init(t,e)}),Ba=y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=ka),ot.init(t,e)}),Ua=y("$ZodCheckIncludes",(t,e)=>{ie.init(t,e);const n=ze(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{const i=s._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),za=y("$ZodCheckStartsWith",(t,e)=>{ie.init(t,e);const n=new RegExp(`^${ze(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),Ma=y("$ZodCheckEndsWith",(t,e)=>{ie.init(t,e);const n=new RegExp(`.*${ze(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),Ga=y("$ZodCheckOverwrite",(t,e)=>{ie.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),s=Math.min(...r.map(o=>o.length-o.trimStart().length)),i=r.map(o=>o.slice(s)).map(o=>" ".repeat(this.indent*2)+o);for(const o of i)this.content.push(o)}compile(){const e=Function,n=this?.args,s=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...n,s.join(`
38
- `))}}const La={major:4,minor:0,patch:0},W=y("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=La;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const i of s._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const s=(i,o,a)=>{let l=Oe(i),f;for(const m of o){if(m._zod.def.when){if(!m._zod.def.when(i))continue}else if(l)continue;const E=i.issues.length,p=m._zod.check(i);if(p instanceof Promise&&a?.async===!1)throw new Pe;if(f||p instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await p,i.issues.length!==E&&(l||(l=Oe(i,E)))});else{if(i.issues.length===E)continue;l||(l=Oe(i,E))}}return f?f.then(()=>i):i};t._zod.run=(i,o)=>{const a=t._zod.parse(i,o);if(a instanceof Promise){if(o.async===!1)throw new Pe;return a.then(l=>s(l,r,o))}return s(a,r,o)}}t["~standard"]={validate:s=>{try{const i=ta(t,s);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return na(t,s).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),Nt=y("$ZodString",(t,e)=>{W.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??wa(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}}),K=y("$ZodStringFormat",(t,e)=>{ot.init(t,e),Nt.init(t,e)}),Wa=y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=la),K.init(t,e)}),Za=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());K.init(t,e)}),Va=y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ha),K.init(t,e)}),Ha=y("$ZodURL",(t,e)=>{K.init(t,e),t._zod.check=n=>{try{const r=n.value,s=new URL(r),i=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.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(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.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("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Ka=y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ga()),K.init(t,e)}),qa=y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ua),K.init(t,e)}),Ya=y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ra),K.init(t,e)}),Ja=y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sa),K.init(t,e)}),Qa=y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ia),K.init(t,e)}),Xa=y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=oa),K.init(t,e)}),eu=y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=aa),K.init(t,e)}),tu=y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Sa(e)),K.init(t,e)}),nu=y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=_a),K.init(t,e)}),ru=y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Fa(e)),K.init(t,e)}),su=y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=ca),K.init(t,e)}),iu=y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=fa),K.init(t,e),t._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),ou=y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=pa),K.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})}}}),au=y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ma),K.init(t,e)}),uu=y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Da),K.init(t,e),t._zod.check=n=>{const[r,s]=n.value.split("/");try{if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>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 Qn(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const cu=y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ea),K.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Qn(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function lu(t){if(!Vn.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Qn(n)}const hu=y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Vn),K.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{lu(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),du=y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=va),K.init(t,e)});function gu(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}const fu=y("$ZodJWT",(t,e)=>{K.init(t,e),t._zod.check=n=>{gu(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Xn=y("$ZodNumber",(t,e)=>{W.init(t,e),t._zod.pattern=t._zod.bag.pattern??ba,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const i=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...i?{received:i}:{}}),n}}),pu=y("$ZodNumber",(t,e)=>{$a.init(t,e),Xn.init(t,e)}),mu=y("$ZodBoolean",(t,e)=>{W.init(t,e),t._zod.pattern=Aa,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}}),Du=y("$ZodAny",(t,e)=>{W.init(t,e),t._zod.parse=n=>n}),Eu=y("$ZodUnknown",(t,e)=>{W.init(t,e),t._zod.parse=n=>n}),yu=y("$ZodNever",(t,e)=>{W.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(...Fe(n,t.issues)),e.value[n]=t.value}const vu=y("$ZodArray",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.value=Array(s.length);const i=[];for(let o=0;o<s.length;o++){const a=s[o],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?i.push(l.then(f=>hn(f,n,o))):hn(l,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function qe(t,e,n){t.issues.length&&e.issues.push(...Fe(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(...Fe(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}const _u=y("$ZodObject",(t,e)=>{W.init(t,e);const n=zn(()=>{const E=Object.keys(e.shape);for(const _ of E)if(!(e.shape[_]instanceof W))throw new Error(`Invalid element at key "${_}": expected a Zod schema`);const p=Lo(e.shape);return{shape:e.shape,keys:E,keySet:new Set(E),numKeys:E.length,optionalKeys:new Set(p)}});H(t._zod,"propValues",()=>{const E=e.shape,p={};for(const _ in E){const T=E[_]._zod;if(T.values){p[_]??(p[_]=new Set);for(const u of T.values)p[_].add(u)}}return p});const r=E=>{const p=new ja(["shape","payload","ctx"]),_=n.value,T=d=>{const g=$e(d);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");const u=Object.create(null);let c=0;for(const d of _.keys)u[d]=`key_${c++}`;p.write("const newResult = {}");for(const d of _.keys)if(_.optionalKeys.has(d)){const g=u[d];p.write(`const ${g} = ${T(d)};`);const F=$e(d);p.write(`
39
- if (${g}.issues.length) {
40
- if (input[${F}] === undefined) {
41
- if (${F} in input) {
42
- newResult[${F}] = undefined;
43
- }
44
- } else {
45
- payload.issues = payload.issues.concat(
46
- ${g}.issues.map((iss) => ({
47
- ...iss,
48
- path: iss.path ? [${F}, ...iss.path] : [${F}],
49
- }))
50
- );
51
- }
52
- } else if (${g}.value === undefined) {
53
- if (${F} in input) newResult[${F}] = undefined;
54
- } else {
55
- newResult[${F}] = ${g}.value;
56
- }
57
- `)}else{const g=u[d];p.write(`const ${g} = ${T(d)};`),p.write(`
58
- if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
59
- ...iss,
60
- path: iss.path ? [${$e(d)}, ...iss.path] : [${$e(d)}]
61
- })));`),p.write(`newResult[${$e(d)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const h=p.compile();return(d,g)=>h(E,d,g)};let s;const i=Ct,o=!Un.jitless,l=o&&Go.value,f=e.catchall;let m;t._zod.parse=(E,p)=>{m??(m=n.value);const _=E.value;if(!i(_))return E.issues.push({expected:"object",code:"invalid_type",input:_,inst:t}),E;const T=[];if(o&&l&&p?.async===!1&&p.jitless!==!0)s||(s=r(e.shape)),E=s(E,p);else{E.value={};const g=m.shape;for(const F of m.keys){const $=g[F],A=$._zod.run({value:_[F],issues:[]},p),B=$._zod.optin==="optional"&&$._zod.optout==="optional";A instanceof Promise?T.push(A.then(R=>B?dn(R,E,F,_):qe(R,E,F))):B?dn(A,E,F,_):qe(A,E,F)}}if(!f)return T.length?Promise.all(T).then(()=>E):E;const u=[],c=m.keySet,h=f._zod,d=h.def.type;for(const g of Object.keys(_)){if(c.has(g))continue;if(d==="never"){u.push(g);continue}const F=h.run({value:_[g],issues:[]},p);F instanceof Promise?T.push(F.then($=>qe($,E,g))):qe(F,E,g)}return u.length&&E.issues.push({code:"unrecognized_keys",keys:u,input:_,inst:t}),T.length?Promise.all(T).then(()=>E):E}});function gn(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(i=>Ee(i,r,De())))}),e}const Fu=y("$ZodUnion",(t,e)=>{W.init(t,e),H(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),H(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),H(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),H(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=>xt(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let s=!1;const i=[];for(const o of e.options){const a=o._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)i.push(a),s=!0;else{if(a.issues.length===0)return a;i.push(a)}}return s?Promise.all(i).then(o=>gn(o,n,t,r)):gn(i,n,t,r)}}),Su=y("$ZodIntersection",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=n.value,i=e.left._zod.run({value:s,issues:[]},r),o=e.right._zod.run({value:s,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([l,f])=>fn(n,l,f)):fn(n,i,o)}});function bt(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(nt(t)&&nt(e)){const n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),s={...t,...e};for(const i of r){const o=bt(t[i],e[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};s[i]=o.data}return{valid:!0,data:s}}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 s=t[r],i=e[r],o=bt(s,i);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=bt(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 wu=y("$ZodRecord",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=n.value;if(!nt(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),n;const i=[];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 f=e.valueType._zod.run({value:s[l],issues:[]},r);f instanceof Promise?i.push(f.then(m=>{m.issues.length&&n.issues.push(...Fe(l,m.issues)),n.value[l]=m.value})):(f.issues.length&&n.issues.push(...Fe(l,f.issues)),n.value[l]=f.value)}let a;for(const l in s)o.has(l)||(a=a??[],a.push(l));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{n.value={};for(const o of Reflect.ownKeys(s)){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(f=>Ee(f,r,De())),input:o,path:[o],inst:t}),n.value[a.value]=a.value;continue}const l=e.valueType._zod.run({value:s[o],issues:[]},r);l instanceof Promise?i.push(l.then(f=>{f.issues.length&&n.issues.push(...Fe(o,f.issues)),n.value[a.value]=f.value})):(l.issues.length&&n.issues.push(...Fe(o,l.issues)),n.value[a.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Cu=y("$ZodEnum",(t,e)=>{W.init(t,e);const n=Uo(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"?ze(r):r.toString()).join("|")})$`),t._zod.parse=(r,s)=>{const i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:t}),r}}),bu=y("$ZodLiteral",(t,e)=>{W.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ze(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{const s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}}),Au=y("$ZodTransform",(t,e)=>{W.init(t,e),t._zod.parse=(n,r)=>{const s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(o=>(n.value=o,n));if(s instanceof Promise)throw new Pe;return n.value=s,n}}),Tu=y("$ZodOptional",(t,e)=>{W.init(t,e),t._zod.optin="optional",t._zod.optout="optional",H(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),H(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${xt(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)}),ku=y("$ZodNullable",(t,e)=>{W.init(t,e),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${xt(n.source)}|null)$`):void 0}),H(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)}),Iu=y("$ZodDefault",(t,e)=>{W.init(t,e),t._zod.optin="optional",H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>pn(i,e)):pn(s,e)}});function pn(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const $u=y("$ZodPrefault",(t,e)=>{W.init(t,e),t._zod.optin="optional",H(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))}),Ou=y("$ZodNonOptional",(t,e)=>{W.init(t,e),H(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 s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>mn(i,t)):mn(s,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 xu=y("$ZodCatch",(t,e)=>{W.init(t,e),t._zod.optin="optional",H(t._zod,"optout",()=>e.innerType._zod.optout),H(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(o=>Ee(o,r,De()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>Ee(i,r,De()))},input:n.value}),n.issues=[]),n)}}),Pu=y("$ZodPipe",(t,e)=>{W.init(t,e),H(t._zod,"values",()=>e.in._zod.values),H(t._zod,"optin",()=>e.in._zod.optin),H(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{const s=e.in._zod.run(n,r);return s instanceof Promise?s.then(i=>Dn(i,e,r)):Dn(s,e,r)}});function Dn(t,e,n){return Oe(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}const Ru=y("$ZodReadonly",(t,e)=>{W.init(t,e),H(t._zod,"propValues",()=>e.innerType._zod.propValues),H(t._zod,"values",()=>e.innerType._zod.values),H(t._zod,"optin",()=>e.innerType._zod.optin),H(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{const s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(En):En(s)}});function En(t){return t.value=Object.freeze(t.value),t}const Nu=y("$ZodCustom",(t,e)=>{ie.init(t,e),W.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(i=>yn(i,n,r,t));yn(s,n,r,t)}});function yn(t,e,n,r){if(!t){const s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(Re(s))}}class Bu{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 Uu(){return new Bu}const Ye=Uu();function zu(t,e){return new t({type:"string",...I(e)})}function Mu(t,e){return new t({type:"string",coerce:!0,...I(e)})}function Gu(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...I(e)})}function vn(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 Lu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...I(e)})}function Wu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...I(e)})}function Zu(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...I(e)})}function Vu(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...I(e)})}function Hu(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...I(e)})}function Ku(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...I(e)})}function qu(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...I(e)})}function Yu(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...I(e)})}function Ju(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...I(e)})}function Qu(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...I(e)})}function Xu(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...I(e)})}function ec(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...I(e)})}function tc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...I(e)})}function nc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...I(e)})}function rc(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 ic(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...I(e)})}function oc(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...I(e)})}function ac(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...I(e)})}function uc(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...I(e)})}function cc(t,e){return new t({type:"string",format:"date",check:"string_format",...I(e)})}function lc(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...I(e)})}function hc(t,e){return new t({type:"string",format:"duration",check:"string_format",...I(e)})}function dc(t,e){return new t({type:"number",checks:[],...I(e)})}function gc(t,e){return new t({type:"number",coerce:!0,checks:[],...I(e)})}function fc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...I(e)})}function pc(t,e){return new t({type:"boolean",...I(e)})}function mc(t){return new t({type:"any"})}function Dc(t){return new t({type:"unknown"})}function Ec(t,e){return new t({type:"never",...I(e)})}function _n(t,e){return new Yn({check:"less_than",...I(e),value:t,inclusive:!1})}function yt(t,e){return new Yn({check:"less_than",...I(e),value:t,inclusive:!0})}function Fn(t,e){return new Jn({check:"greater_than",...I(e),value:t,inclusive:!1})}function vt(t,e){return new Jn({check:"greater_than",...I(e),value:t,inclusive:!0})}function Sn(t,e){return new Ia({check:"multiple_of",...I(e),value:t})}function er(t,e){return new Oa({check:"max_length",...I(e),maximum:t})}function rt(t,e){return new xa({check:"min_length",...I(e),minimum:t})}function tr(t,e){return new Pa({check:"length_equals",...I(e),length:t})}function yc(t,e){return new Ra({check:"string_format",format:"regex",...I(e),pattern:t})}function vc(t){return new Na({check:"string_format",format:"lowercase",...I(t)})}function _c(t){return new Ba({check:"string_format",format:"uppercase",...I(t)})}function Fc(t,e){return new Ua({check:"string_format",format:"includes",...I(e),includes:t})}function Sc(t,e){return new za({check:"string_format",format:"starts_with",...I(e),prefix:t})}function wc(t,e){return new Ma({check:"string_format",format:"ends_with",...I(e),suffix:t})}function Me(t){return new Ga({check:"overwrite",tx:t})}function Cc(t){return Me(e=>e.normalize(t))}function bc(){return Me(t=>t.trim())}function Ac(){return Me(t=>t.toLowerCase())}function Tc(){return Me(t=>t.toUpperCase())}function kc(t,e,n){return new t({type:"array",element:e,...I(n)})}function Ic(t,e,n){return new t({type:"custom",check:"custom",fn:e,...I(n)})}const $c=y("ZodISODateTime",(t,e)=>{tu.init(t,e),Q.init(t,e)});function Oc(t){return uc($c,t)}const xc=y("ZodISODate",(t,e)=>{nu.init(t,e),Q.init(t,e)});function Pc(t){return cc(xc,t)}const Rc=y("ZodISOTime",(t,e)=>{ru.init(t,e),Q.init(t,e)});function Nc(t){return lc(Rc,t)}const Bc=y("ZodISODuration",(t,e)=>{su.init(t,e),Q.init(t,e)});function Uc(t){return hc(Bc,t)}const zc=(t,e)=>{jn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Qo(t,n)},flatten:{value:n=>Jo(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},at=y("ZodError",zc,{Parent:Error}),Mc=Xo(at),Gc=ea(at),jc=Wn(at),Lc=Zn(at),J=y("ZodType",(t,e)=>(W.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)=>Mc(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>jc(t,n,r),t.parseAsync=async(n,r)=>Gc(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Lc(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(Rl(n,r)),t.superRefine=n=>t.check(Nl(n)),t.overwrite=n=>t.check(Me(n)),t.optional=()=>bn(t),t.nullable=()=>An(t),t.nullish=()=>bn(An(t)),t.nonoptional=n=>Al(t,n),t.array=()=>Ce(t),t.or=n=>ut([t,n]),t.and=n=>Dl(t,n),t.transform=n=>Tn(t,_l(n)),t.default=n=>wl(t,n),t.prefault=n=>bl(t,n),t.catch=n=>kl(t,n),t.pipe=n=>Tn(t,n),t.readonly=()=>Ol(t),t.describe=n=>{const r=t.clone();return Ye.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Ye.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Ye.get(t);const r=t.clone();return Ye.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),nr=y("_ZodString",(t,e)=>{Nt.init(t,e),J.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(Sc(...r)),t.endsWith=(...r)=>t.check(wc(...r)),t.min=(...r)=>t.check(rt(...r)),t.max=(...r)=>t.check(er(...r)),t.length=(...r)=>t.check(tr(...r)),t.nonempty=(...r)=>t.check(rt(1,...r)),t.lowercase=r=>t.check(vc(r)),t.uppercase=r=>t.check(_c(r)),t.trim=()=>t.check(bc()),t.normalize=(...r)=>t.check(Cc(...r)),t.toLowerCase=()=>t.check(Ac()),t.toUpperCase=()=>t.check(Tc())}),rr=y("ZodString",(t,e)=>{Nt.init(t,e),nr.init(t,e),t.email=n=>t.check(Gu(Wc,n)),t.url=n=>t.check(Vu(Zc,n)),t.jwt=n=>t.check(ac(ol,n)),t.emoji=n=>t.check(Hu(Vc,n)),t.guid=n=>t.check(vn(wn,n)),t.uuid=n=>t.check(ju(Je,n)),t.uuidv4=n=>t.check(Lu(Je,n)),t.uuidv6=n=>t.check(Wu(Je,n)),t.uuidv7=n=>t.check(Zu(Je,n)),t.nanoid=n=>t.check(Ku(Hc,n)),t.guid=n=>t.check(vn(wn,n)),t.cuid=n=>t.check(qu(Kc,n)),t.cuid2=n=>t.check(Yu(qc,n)),t.ulid=n=>t.check(Ju(Yc,n)),t.base64=n=>t.check(sc(rl,n)),t.base64url=n=>t.check(ic(sl,n)),t.xid=n=>t.check(Qu(Jc,n)),t.ksuid=n=>t.check(Xu(Qc,n)),t.ipv4=n=>t.check(ec(Xc,n)),t.ipv6=n=>t.check(tc(el,n)),t.cidrv4=n=>t.check(nc(tl,n)),t.cidrv6=n=>t.check(rc(nl,n)),t.e164=n=>t.check(oc(il,n)),t.datetime=n=>t.check(Oc(n)),t.date=n=>t.check(Pc(n)),t.time=n=>t.check(Nc(n)),t.duration=n=>t.check(Uc(n))});function v(t){return zu(rr,t)}const Q=y("ZodStringFormat",(t,e)=>{K.init(t,e),nr.init(t,e)}),Wc=y("ZodEmail",(t,e)=>{Va.init(t,e),Q.init(t,e)}),wn=y("ZodGUID",(t,e)=>{Wa.init(t,e),Q.init(t,e)}),Je=y("ZodUUID",(t,e)=>{Za.init(t,e),Q.init(t,e)}),Zc=y("ZodURL",(t,e)=>{Ha.init(t,e),Q.init(t,e)}),Vc=y("ZodEmoji",(t,e)=>{Ka.init(t,e),Q.init(t,e)}),Hc=y("ZodNanoID",(t,e)=>{qa.init(t,e),Q.init(t,e)}),Kc=y("ZodCUID",(t,e)=>{Ya.init(t,e),Q.init(t,e)}),qc=y("ZodCUID2",(t,e)=>{Ja.init(t,e),Q.init(t,e)}),Yc=y("ZodULID",(t,e)=>{Qa.init(t,e),Q.init(t,e)}),Jc=y("ZodXID",(t,e)=>{Xa.init(t,e),Q.init(t,e)}),Qc=y("ZodKSUID",(t,e)=>{eu.init(t,e),Q.init(t,e)}),Xc=y("ZodIPv4",(t,e)=>{iu.init(t,e),Q.init(t,e)}),el=y("ZodIPv6",(t,e)=>{ou.init(t,e),Q.init(t,e)}),tl=y("ZodCIDRv4",(t,e)=>{au.init(t,e),Q.init(t,e)}),nl=y("ZodCIDRv6",(t,e)=>{uu.init(t,e),Q.init(t,e)}),rl=y("ZodBase64",(t,e)=>{cu.init(t,e),Q.init(t,e)}),sl=y("ZodBase64URL",(t,e)=>{hu.init(t,e),Q.init(t,e)}),il=y("ZodE164",(t,e)=>{du.init(t,e),Q.init(t,e)}),ol=y("ZodJWT",(t,e)=>{fu.init(t,e),Q.init(t,e)}),Bt=y("ZodNumber",(t,e)=>{Xn.init(t,e),J.init(t,e),t.gt=(r,s)=>t.check(Fn(r,s)),t.gte=(r,s)=>t.check(vt(r,s)),t.min=(r,s)=>t.check(vt(r,s)),t.lt=(r,s)=>t.check(_n(r,s)),t.lte=(r,s)=>t.check(yt(r,s)),t.max=(r,s)=>t.check(yt(r,s)),t.int=r=>t.check(Cn(r)),t.safe=r=>t.check(Cn(r)),t.positive=r=>t.check(Fn(0,r)),t.nonnegative=r=>t.check(vt(0,r)),t.negative=r=>t.check(_n(0,r)),t.nonpositive=r=>t.check(yt(0,r)),t.multipleOf=(r,s)=>t.check(Sn(r,s)),t.step=(r,s)=>t.check(Sn(r,s)),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 dc(Bt,t)}const al=y("ZodNumberFormat",(t,e)=>{pu.init(t,e),Bt.init(t,e)});function Cn(t){return fc(al,t)}const ul=y("ZodBoolean",(t,e)=>{mu.init(t,e),J.init(t,e)});function Ae(t){return pc(ul,t)}const cl=y("ZodAny",(t,e)=>{Du.init(t,e),J.init(t,e)});function he(){return mc(cl)}const ll=y("ZodUnknown",(t,e)=>{Eu.init(t,e),J.init(t,e)});function Ne(){return Dc(ll)}const hl=y("ZodNever",(t,e)=>{yu.init(t,e),J.init(t,e)});function dl(t){return Ec(hl,t)}const gl=y("ZodArray",(t,e)=>{vu.init(t,e),J.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(rt(n,r)),t.nonempty=n=>t.check(rt(1,n)),t.max=(n,r)=>t.check(er(n,r)),t.length=(n,r)=>t.check(tr(n,r)),t.unwrap=()=>t.element});function Ce(t,e){return kc(gl,t,e)}const fl=y("ZodObject",(t,e)=>{_u.init(t,e),J.init(t,e),H(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:dl()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ho(t,n),t.merge=n=>Ko(t,n),t.pick=n=>Zo(t,n),t.omit=n=>Vo(t,n),t.partial=(...n)=>qo(sr,t,n[0]),t.required=(...n)=>Yo(ir,t,n[0])});function ye(t,e){const n={type:"object",get shape(){return Pt(this,"shape",{...t}),this.shape},...I(e)};return new fl(n)}const pl=y("ZodUnion",(t,e)=>{Fu.init(t,e),J.init(t,e),t.options=e.options});function ut(t,e){return new pl({type:"union",options:t,...I(e)})}const ml=y("ZodIntersection",(t,e)=>{Su.init(t,e),J.init(t,e)});function Dl(t,e){return new ml({type:"intersection",left:t,right:e})}const El=y("ZodRecord",(t,e)=>{wu.init(t,e),J.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ct(t,e,n){return new El({type:"record",keyType:t,valueType:e,...I(n)})}const At=y("ZodEnum",(t,e)=>{Cu.init(t,e),J.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{const i={};for(const o of r)if(n.has(o))i[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new At({...e,checks:[],...I(s),entries:i})},t.exclude=(r,s)=>{const i={...e.entries};for(const o of r)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new At({...e,checks:[],...I(s),entries:i})}});function ne(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new At({type:"enum",entries:n,...I(e)})}const yl=y("ZodLiteral",(t,e)=>{bu.init(t,e),J.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 vl=y("ZodTransform",(t,e)=>{Au.init(t,e),J.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(Re(i,n.value,e));else{const o=i;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 s=e.transform(n.value,n);return s instanceof Promise?s.then(i=>(n.value=i,n)):(n.value=s,n)}});function _l(t){return new vl({type:"transform",transform:t})}const sr=y("ZodOptional",(t,e)=>{Tu.init(t,e),J.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)=>{ku.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function An(t){return new Fl({type:"nullable",innerType:t})}const Sl=y("ZodDefault",(t,e)=>{Iu.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function wl(t,e){return new Sl({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const Cl=y("ZodPrefault",(t,e)=>{$u.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bl(t,e){return new Cl({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const ir=y("ZodNonOptional",(t,e)=>{Ou.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Al(t,e){return new ir({type:"nonoptional",innerType:t,...I(e)})}const Tl=y("ZodCatch",(t,e)=>{xu.init(t,e),J.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function kl(t,e){return new Tl({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const Il=y("ZodPipe",(t,e)=>{Pu.init(t,e),J.init(t,e),t.in=e.in,t.out=e.out});function Tn(t,e){return new Il({type:"pipe",in:t,out:e})}const $l=y("ZodReadonly",(t,e)=>{Ru.init(t,e),J.init(t,e)});function Ol(t){return new $l({type:"readonly",innerType:t})}const xl=y("ZodCustom",(t,e)=>{Nu.init(t,e),J.init(t,e)});function Pl(t){const e=new ie({check:"custom"});return e._zod.check=t,e}function Rl(t,e={}){return Ic(xl,t,e)}function Nl(t){const e=Pl(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Re(r,n.value,e._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Re(s))}},t(n.value,n)));return e}function kn(t){return Mu(rr,t)}function In(t){return gc(Bt,t)}const P=ye({eventType:v(),command:v(),payload:ye({sessionId:v(),timestamp:re().default(()=>Date.now())})}),Bl=ne([V.STARTING,V.IDLE,V.PAUSED,V.STOPPED,V.ERROR]),Ul=ne([Y.CLAUDE_CODE,Y.GEMINI_CLI]),zl=ne([cn.STDOUT,cn.STDERR]),or=P.extend({eventType:b(O.STATUS).default(O.STATUS),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default(""),fullscreen:Ae().default(!1).optional()})}),ar=P.extend({eventType:b(O.RESIZE).default(O.RESIZE),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default(""),cols:In(),rows:In()})}),ur=P.extend({eventType:b(O.DIRECT_CONTROL).default(O.DIRECT_CONTROL),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v(),controlType:ne(["interrupt","cancel","eof","signal"]).default("interrupt"),metadata:ct(v(),he()).optional()})}),Tt=P.extend({eventType:b(O.STATUS).default(O.STATUS),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.shape.payload.extend({data:v().default(""),status:Bl.default(V.IDLE),agentType:Ul.optional(),pid:re().optional(),version:v().optional(),capabilities:Ce(v()).optional(),message:v().optional()})}),cr=P.extend({eventType:b(O.MESSAGE_INPUT).default(O.MESSAGE_INPUT),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:kn(),messageId:v(),content:kn(),metadata:ct(v(),he()).optional()})}),Ml=P.extend({eventType:b(O.MESSAGE_INPUT).default(O.MESSAGE_INPUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.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()})}),Gl=P.extend({eventType:b(O.MESSAGE_OUTPUT).default(O.MESSAGE_OUTPUT),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default("")})}),lr=P.extend({eventType:b(O.MESSAGE_OUTPUT).default(O.MESSAGE_OUTPUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.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:zl.optional(),isComplete:Ae().optional().default(!1),metadata:he().nullable(),createdAt:v(),updatedAt:v()})}),jl=P.extend({eventType:b(O.MESSAGE_OUTPUT_PERMISSION_REQUESTED).default(O.MESSAGE_OUTPUT_PERMISSION_REQUESTED),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default(""),messageId:v(),toolName:v(),description:v(),metadata:ct(v(),he()).optional()})}),hr=P.extend({eventType:b(O.MESSAGE_STDIN).default(O.MESSAGE_STDIN),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default("")})}),dr=P.extend({eventType:b(O.MESSAGE_STDOUT).default(O.MESSAGE_STDOUT),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.shape.payload.extend({data:v().default("")})}),Ll=P.extend({eventType:b(O.MESSAGE_OUTPUT_STARTED).default(O.MESSAGE_OUTPUT_STARTED),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.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()})}),Wl=P.extend({eventType:b(O.MESSAGE_OUTPUT_ENDED).default(O.MESSAGE_OUTPUT_ENDED),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.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()})}),Zl=P.extend({eventType:b(O.MESSAGE_DELETED).default(O.MESSAGE_DELETED),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.shape.payload.extend({data:v().default(""),id:v()})}),Vl=P.extend({eventType:b(O.ERROR).default(O.ERROR),command:b(S.REQUEST).default(S.REQUEST),payload:P.shape.payload.extend({data:v().default("")})}),gr=P.extend({eventType:b(O.ERROR).default(O.ERROR),command:b(S.RESPONSE).default(S.RESPONSE),payload:P.shape.payload.extend({data:v().default(""),error:ye({code:v().default("UNKNOWN_ERROR"),message:v().default("An unknown error occurred"),details:he().optional(),stack:v().optional()})})}),Hl=P.extend({eventType:b(O.STATUS).default(O.STATUS),command:b(S.ACK).default(S.ACK),payload:P.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Kl=P.extend({eventType:b(O.MESSAGE_INPUT).default(O.MESSAGE_INPUT),command:b(S.ACK).default(S.ACK),payload:P.shape.payload.extend({data:v().default(""),messageId:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),ql=P.extend({eventType:b(O.MESSAGE_OUTPUT).default(O.MESSAGE_OUTPUT),command:b(S.ACK).default(S.ACK),payload:P.shape.payload.extend({data:v().default(""),messageId:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Yl=P.extend({eventType:b(O.MESSAGE_DELETED).default(O.MESSAGE_DELETED),command:b(S.ACK).default(S.ACK),payload:P.shape.payload.extend({data:v().default(""),id:v(),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})}),Jl=P.extend({eventType:b(O.ERROR).default(O.ERROR),command:b(S.ACK).default(S.ACK),payload:P.shape.payload.extend({data:v().default(""),status:ne(["forwarded","failed"]).default("forwarded"),message:v(),agentSessionsSent:re().default(0)})});ut([or,ar,ur,Tt,cr,Ml,Gl,lr,jl,hr,dr,Ll,Wl,Zl,Vl,gr,Hl,Kl,ql,Yl,Jl]);const U=ye({eventType:v(),command:v(),payload:ye({sessionId:v(),timestamp:re().default(()=>Date.now())})}),Ql=ne([me.IDLE,me.BUSY,me.OFFLINE,me.STARTING]),fr=U.extend({eventType:b(N.STATUS).default(N.STATUS),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default("")})}),kt=U.extend({eventType:b(N.STATUS).default(N.STATUS),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),status:Ql.default(me.IDLE)})}),Xl=U.extend({eventType:b(N.ERROR).default(N.ERROR),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default("")})}),pr=U.extend({eventType:b(N.ERROR).default(N.ERROR),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().default(""),error:ye({code:v().default("UNKNOWN_ERROR"),message:v().default("An unknown error occurred"),details:he().optional()})})}),mr=U.extend({eventType:b(N.TERMINATE).default(N.TERMINATE),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().optional().default("")})}),Dr=U.extend({eventType:b(N.TERMINATE).default(N.TERMINATE),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().optional().default("")})}),Er=U.extend({eventType:b(N.LIST).default(N.LIST),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().optional().default("")})}),yr=U.extend({eventType:b(N.LIST).default(N.LIST),command:b(S.RESPONSE).default(S.RESPONSE),payload:U.shape.payload.extend({data:v().optional().default("")})}),Ut=U.extend({eventType:b(N.START_AGENT).default(N.START_AGENT),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default(""),agentType:v(),agentSessionId:v(),agentConfig:ye({conversationSessionId:v().optional(),workingDirectory:v().nullable(),environment:ct(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:ut([Ae(),ye({branch:v().optional(),name:v().optional()})]).optional().default(!1)}).optional()})}),eh=U.extend({eventType:b(N.START_AGENT).default(N.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()})}),th=U.extend({eventType:b(N.START_AGENT).default(N.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)})}),vr=U.extend({eventType:b(N.STOP_AGENT).default(N.STOP_AGENT),command:b(S.REQUEST).default(S.REQUEST),payload:U.shape.payload.extend({data:v().default(""),agentSessionId:v()})}),_r=U.extend({eventType:b(N.STOP_AGENT).default(N.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()})}),nh=U.extend({eventType:b(N.STOP_AGENT).default(N.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)})}),rh=U.extend({eventType:b(N.TERMINATE).default(N.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(N.LIST).default(N.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)})});ut([fr,kt,Xl,pr,mr,Dr,Er,yr,Ut,eh,th,vr,_r,nh,rh,sh]);const Fr=D.z.object({VITE_INJECT_AGIFLOW_APP_ENDPOINT:D.z.string().url().default("").describe("Server base URL for both HTTP API and WebSocket connections"),VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:D.z.string().url().default("").describe("Server base URL when running inside Docker containers"),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)});Rn.config({override:!1,debug:!1});const ae=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.3",VITE_AGENT_CLI_DOCKER_NETWORK:""});function Sr(t=!1){return process.env.AGENT_CONTAINER_MODE==="true"||t?ae.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT}function ih(t){const e=new URL(t);return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.toString()}function wr(t=!0,e){const r=fe.hostname().replace(/[^a-zA-Z0-9-]/g,"-");if(t){const s=e||process.cwd(),i=ts.createHash("sha256").update(s).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"").slice(0,8);return`claude-daemon-${r}-${i}`}return`claude-daemon-${r}-${Date.now()}`}function Cr(){return{hostname:fe.hostname(),platform:fe.platform(),arch:fe.arch(),release:fe.release(),cpus:fe.cpus().length,totalMemory:fe.totalmem(),type:fe.type()}}function oh(t){return t.replace(/^http/,"ws")}function br(t,e=3e3){return t.replace(/^ws/,"http").replace(/:\d+$/,`:${e}`)}function Ar(t,e=3e5,n){let r=null;const s=n||console,i=()=>{o(),t().catch(a=>{s.warn?.("Heartbeat failed:",a)||console.warn("Heartbeat failed:",a)}),r=setInterval(async()=>{try{await t()}catch(a){s.warn?.("Heartbeat failed:",a)||console.warn("Heartbeat failed:",a)}},e)},o=()=>{r&&(clearInterval(r),r=null)};return{start:i,stop:o}}class ah{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,s)=>{const i={};this.options.apiKey&&(i["x-api-key"]=this.options.apiKey),this.ws=new _e(n,{headers:i}),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||s(o)}),setTimeout(()=>{this.isConnected||s(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:O.STATUS,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:"",status:e.status||V.IDLE,agentType:e.agentType,pid:e.pid,version:e.version,capabilities:e.capabilities,message:e.message}};this.sendMessage(Tt.parse(n))}sendAgentOutput(e){const n=new Date().toISOString(),r={eventType:O.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(lr.parse(r))}sendAgentError(e){const n={eventType:O.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(gr.parse(n))}sendStdoutMessage(e){const n={eventType:O.MESSAGE_STDOUT,command:S.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:e}};this.sendMessage(dr.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 O.STATUS:if(e.command===S.REQUEST){const n=or.parse(e);this.callbacks.onStatusRequest&&this.callbacks.onStatusRequest(n)}break;case O.MESSAGE_INPUT:if(e.command===S.REQUEST){const n=cr.parse(e);this.callbacks.onMessageInput&&this.callbacks.onMessageInput(n)}break;case O.MESSAGE_STDIN:if(e.command===S.REQUEST){const n=hr.parse(e);this.callbacks.onStdinInput&&this.callbacks.onStdinInput(n)}break;case O.RESIZE:if(e.command===S.REQUEST){const n=ar.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 O.DIRECT_CONTROL:if(e.command===S.REQUEST){const n=ur.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,s=n*r;D.SubEnvManager.isContainerMode&&this.logger.info(`🐳 Docker WebSocket reconnection attempt ${this.connectionAttempts}/${this.maxReconnectAttempts} in ${s}ms`),this.reconnectTimer=setTimeout(async()=>{try{await this.connect(e)}catch(i){const o=i instanceof Error?i.message:String(i);D.SubEnvManager.isContainerMode?this.logger.error(`🐳 Docker WebSocket reconnection failed: ${o}`):this.log(`Reconnection failed: ${o}`),this.scheduleReconnect(e)}},s)}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:O.STATUS,command:S.RESPONSE,payload:{sessionId:this.currentSessionId,timestamp:Date.now(),data:"",status:V.IDLE,message:"Heartbeat"}},n=Tt.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 uh{session;logger;constructor(e){this.logger=e??new D.Logger({verbose:!1})}spawn(e,n){const r=e.agentSessionId||On.ulid(),s=e.workingDir||process.cwd(),i={};e.agentApiKey&&(i[D.ENV_KEYS.AGENT_API_KEY]=e.agentApiKey),e.agentOrganizationId&&(i[D.ENV_KEYS.AGENT_ORGANIZATION_ID]=e.agentOrganizationId),e.agentDeviceGuid&&(i[D.ENV_KEYS.AGENT_DEVICE_GUID]=e.agentDeviceGuid),e.agentServerUrl&&(i[D.ENV_KEYS.AGENT_SERVER_URL]=e.agentServerUrl),e.agentType&&(i[D.ENV_KEYS.AGENT_TYPE]=e.agentType),i[D.ENV_KEYS.AGENT_SESSION_ID]=r,this.logger.debug("PTY Environment Variables:",{...process.env,...i,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"});const o=es.spawn(e.command,e.args||[],{name:"xterm-256color",cwd:s,env:{...process.env,...i,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),a={id:r,ptyProcess:o,command:e.command,workingDir:s,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 f=l.exitCode,m=l.signal;a.status=f===0?"stopped":"error",a.lastActivity=new Date,this.logger.info(`PTY process ${r} exited with code ${f}${m?` (signal: ${m})`:""}`),a.logStream&&a.logStream.end(),n?.onExit&&n.onExit(f,m)}),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 It{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}),!k.existsSync(this.targetDirectory))throw new Error(`Target directory does not exist: ${this.targetDirectory}`);if(this.originalDirectory&&!k.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 s=C.relative(this.originalDirectory,r),i=C.join(this.targetDirectory,s),o=C.dirname(i);k.existsSync(o)||await pe.mkdir(o,{recursive:!0}),await pe.copyFile(r,i),e.push({originalPath:r,targetPath:i,relativePath:s,copied:!0}),this.logger.debug(`Copied: ${s}`)}catch(s){e.push({originalPath:r,targetPath:"",relativePath:C.relative(this.originalDirectory,r),copied:!1}),this.logger.warn(`Failed to copy ${r}: ${s.message}`)}return e}async findEnvironmentFiles(e,n=0){const r=[];if(n>=5)return r;try{const i=await pe.readdir(e,{withFileTypes:!0});for(const o of i){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(i){this.logger.debug(`Cannot read directory ${e}: ${i.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(!k.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 se.execSync(r,{cwd:this.targetDirectory,stdio:"pipe",encoding:"utf8"}),!0}catch(s){if(s.message?.includes("EUNSUPPORTEDPROTOCOL")||s.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 s}}catch(n){return this.logger.error(`Failed to install dependencies: ${n.message}`),!1}}isPackageManagerAvailable(e){try{return se.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 k.existsSync(C.join(this.targetDirectory,"package.json"))}isNodeProject(){return["package.json","node_modules","yarn.lock","package-lock.json","pnpm-lock.yaml"].some(n=>k.existsSync(C.join(this.targetDirectory,n)))}isPythonProject(){return["requirements.txt","pyproject.toml","setup.py","Pipfile","poetry.lock","uv.lock"].some(n=>k.existsSync(C.join(this.targetDirectory,n)))}isNxMonorepo(){return["nx.json","workspace.json","angular.json"].some(n=>k.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()&&!k.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()&&(k.existsSync(C.join(this.targetDirectory,".venv"))||k.existsSync(C.join(this.targetDirectory,"venv"))||(this.logger.info("No virtual environment found, adding default Python setup hooks"),k.existsSync(C.join(this.targetDirectory,"uv.lock"))?n.push("uv sync"):k.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 se.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 se.execSync("nx --version",{stdio:"pipe",timeout:5e3}),!0}catch{try{return se.execSync("npx nx --version",{stdio:"pipe",timeout:1e4}),!0}catch{return!1}}}}class Tr{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 Ge extends Kr.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 s=this.performAgentSigintTermination(n);this.activeTerminations.set(e,s);try{await s}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:s}=e;this.logger.info(`PTY terminated naturally for session agent ${n}. Exit code: ${r}, Signal: ${s}`);const i=this.activeTerminations.get(n);if(i)return this.logger.debug(`Termination already in progress for agent ${n}`),i;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:s=5e3}=n;this.logger.info(`Terminating agent ${e} for session force: ${r}`);const i={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(i,{force:r,timeout:s});this.activeTerminations.set(e,a);try{await a}finally{this.activeTerminations.delete(e)}}async performAgentTermination(e,n){const{force:r,timeout:s}=n;try{this.emit("agent:terminating",e);const i=new Promise((a,l)=>{setTimeout(()=>l(new Error(`Termination timeout for agent ${e.agentSessionId}`)),s)}),o=new Promise(a=>{const l=f=>{f.agentSessionId===e.agentSessionId&&(this.off("agent:terminated",l),a())};this.on("agent:terminated",l)});try{await Promise.race([o,i]),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(i){throw this.logger.error(`Error terminating agent: ${i}`),i}}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(s=>{this.logger.error(`Failed to terminate agent ${r}: ${s}`)}));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 kr{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){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 Ge(this.logger),this.onFullscreenChange=e.onFullscreenChange,this.ptyRunner=new uh(this.logger);const n={serverUrl:e.serverUrl,apiKey:e.apiKey,verbose:e.verbose,organizationId:e.organizationId,credentialsService:this.credentialsService,logger:this.logger},r={onStatusRequest:i=>this.handleStatusRequest(i),onMessageInput:i=>this.handleMessageInput(i),onStdinInput:i=>this.handleStdinInput(i),onResizeRequest:i=>this.handleResizeRequest(i),onDirectControl:i=>this.handleDirectControl(i),onConnect:()=>this.onWebSocketConnect(),onDisconnect:(i,o)=>this.onWebSocketDisconnect(i,o),onError:i=>this.onWebSocketError(i)};this.wsService=new ah(n,r);const s=Sr();this.httpService=new D.AgentHttpService({apiUrl:this.apiUrl||s,organizationId:this.organizationId,apiKey:this.apiKey,logger:this.logger}),this.standalone&&this.initializeStdinForwarding()}initializeStdinForwarding(){this.stdinForwarding=new Tr({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){await this.wsService.connect(e),this.wsService.sendAgentStatus({agentType:this.agentType,status:V.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.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}`)}async handleStatusRequest(e){this.logger.debug(`Handling status request for session: ${e.payload.sessionId}`);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=V.IDLE,r=`${this.agentType} agent is idle`;this.agentInfo&&this.agentInfo.agentSessionId===e.payload.sessionId?(n=this.agentInfo.status,n===V.IDLE?r=`${this.agentType} agent is running`:n===V.STARTING?r=`${this.agentType} agent is starting`:n===V.ERROR?r=`${this.agentType} agent encountered an error`:n===V.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(Y.GEMINI_CLI)){this.logger.debug("Gemini agent detected - pasting content with newline");for(const s of[" "," "])await new Promise(i=>{setTimeout(()=>{this.sendInputToPty(s),i(null)},150)});await new Promise(s=>{setTimeout(()=>{this.sendInputToPty(`${n}
64
- `),s(null)},150)}),await new Promise(s=>{setTimeout(()=>{this.sendInputToPty("\r"),s(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 s=this.STDOUT_THROTTLE_MS-r;this.stdoutThrottleTimer=setTimeout(()=>{this.flushStdoutBuffer()},s)}}flushStdoutBuffer(){if(this.stdoutBuffer)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)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.sendAgentStatus(e)}sendAgentOutput(e){this.wsService.sendAgentOutput(e)}sendAgentError(e){this.wsService.sendAgentError(e)}getAgentInfo(){return this.agentInfo}sendInputToPty(e){this.ptyRunner.sendInput(e)}setAgentInfo(e){if(this.agentInfo=e,e.agentSessionId)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"),s=C.join(__dirname,"networkLog.ts"),i=C.join(__dirname,"..","networkLog.js"),o=C.join(__dirname,"..","networkLog.ts");k.existsSync(r)?n=r:k.existsSync(s)?n=s:k.existsSync(i)?n=i:k.existsSync(o)&&(n=o);let l=e["NODE_OPTIONS"]||"";return this.logger.debug("Network logging hook configuration:",{sameDirJs:r,sameDirTs:s,parentDirJs:i,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 i=new It({targetDirectory:n,logger:this.logger}).getDefaultPreAgentHooks(e);if(!i||i.length===0){this.logger.debug("No pre-agent start hooks to execute");return}this.logger.info(`Executing ${i.length} pre-agent start hook(s) in ${n}`);const o=[];for(let a=0;a<i.length;a++){const l=i[a];this.logger.info(`[${a+1}/${i.length}] Executing hook: ${l}`);let f;if(r)try{f=(await this.httpService.startMessage(r,{messageType:"output",metadata:{hookIndex:a+1,totalHooks:i.length,command:l,status:"running"}})).id}catch(m){this.logger.debug("Failed to start hook message:",m)}try{const{spawn:m}=await import("child_process"),E=await new Promise(p=>{const _=m(l,{cwd:n,shell:!0,stdio:["pipe","pipe","pipe"]});let T="",u="";_.stdout?.on("data",c=>{const h=c.toString();T+=h,this.logger.debug(`[Hook stdout] ${h.trim()}`)}),_.stderr?.on("data",c=>{const h=c.toString();u+=h,this.logger.warn(`[Hook stderr] ${h.trim()}`)}),_.on("close",c=>{if(c===0)this.logger.success(`Hook completed successfully: ${l}`),T.trim()&&this.logger.debug(`Hook stdout: ${T.trim()}`),p({success:!0,stdout:T.trim()});else{this.logger.error(`Hook failed with exit code ${c}: ${l}`),T.trim()&&this.logger.error(`Hook stdout (full output): ${T.trim()}`),u.trim()&&this.logger.error(`Hook stderr (full error): ${u.trim()}`);const h=[];u.trim()&&h.push(`stderr: ${u.trim()}`),T.trim()&&h.push(`stdout: ${T.trim()}`);const d=h.length>0?`Hook failed with exit code ${c}. ${h.join(" | ")}`:`Hook failed with exit code ${c}`;p({success:!1,error:d,stderr:u.trim()||T.trim()||void 0})}}),_.on("error",c=>{this.logger.error(`Hook execution error: ${l}`,c),p({success:!1,error:c.message})})});if(r&&f)try{const p=E.success?"completed":"failed",_=E.success?`✅ Hook completed: ${l}`:`❌ Hook failed: ${l}
65
- ${E.error}`;await this.httpService.updateMessage(r,f,{parts:[{type:"text",text:_}],metadata:{hookIndex:a+1,totalHooks:i.length,command:l,status:p,exitCode:E.success?0:1,stdout:E.stdout,stderr:E.stderr,error:E.error}})}catch(p){this.logger.debug("Failed to update hook message:",p)}E.success||o.push({hook:l,error:E.error||"Unknown error",stderr:E.stderr})}catch(m){const E=m instanceof Error?m.message:String(m);if(this.logger.error(`Failed to execute hook: ${l}`,m instanceof Error?m:new Error(E)),r&&f)try{await this.httpService.updateMessage(r,f,{parts:[{type:"text",text:`❌ Hook execution failed: ${l}
66
- Error: ${E}`}],metadata:{hookIndex:a+1,totalHooks:i.length,command:l,status:"failed",error:E}})}catch(p){this.logger.debug("Failed to update hook message with error:",p)}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){try{const s=`⚠️ **Pre-agent start hook(s) failed**
67
-
68
- ${n.map(i=>{let o=`• **Command**: \`${i.hook}\`
69
- **Error**: ${i.error}`;return i.stderr&&(o+=`
70
- **Output**: \`\`\`
71
- ${i.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,s,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 s=n?.workingDirectory||this.agentInfo?.workingDir;if(!s){this.logger.warn("No working directory specified for Docker repository setup");return}try{this.logger.info("Setting up Docker repository with environment files...");const i=process.cwd(),a=await new It({targetDirectory:s,originalDirectory:i,logger:this.logger}).setup();if(a.envFilesCopied.length>0){const m=a.envFilesCopied.filter(E=>E.copied).length;this.logger.success(`Copied ${m} environment files to Docker container`)}a.errors.length>0&&(this.logger.warn(`Docker repository setup completed with ${a.errors.length} errors`),a.errors.forEach(m=>this.logger.debug(`Setup error: ${m}`)));const l=n?.agentSessionId||this.agentInfo?.agentSessionId,f=n?.hooks?.preAgentStartHooks||n?.hooks?.preAgentStart;await this.executePreAgentStartHooks(f,s,l)}catch(i){this.logger.error(`Failed to setup Docker repository: ${i}`)}}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 Ir extends kr{claudePath;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:Y.CLAUDE_CODE}),this.claudePath=e.claudePath||"claude"}extractOptions(e){const n=[],r=e.split(`
77
- `);for(const s of r){const i=s.trim(),o=i.match(/❯\s*(\d+)\.\s+(.+)$/);if(o){n.push({number:parseInt(o[1],10),text:o[2].trim(),selected:!0});continue}const a=i.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){D.SubEnvManager.isContainerMode&&await new Promise(s=>setTimeout(s,3e3));try{let s=e.map(l=>({label:l.text,value:l.number,selected:l.selected||!1}));s=this.deduplicateOptions(s);const i=D.createSelectComponent(s),o=D.createToolInvocationInput(!1,i),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:s.length,timestamp:n}})}catch(s){this.logger.error("Failed to send structured options message:",s)}}}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 s=e[r].value;let i=-1;for(let a=e.length-1;a>=0;a--)if(e[a].value===s){i=a;break}return e.slice(i)}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(i=>i.test(n))&&(this.agentInputReady=!0,this.sendAgentStatus({agentType:Y.CLAUDE_CODE,status:V.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 s={mcpServers:r},i=`claude-mcps-${n}.json`,o=C.join(le.tmpdir(),i);return k.writeFileSync(o,JSON.stringify(s,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(k.existsSync(r)){const o=k.readdirSync(r).filter(a=>a.endsWith(".md"));for(const a of o){const l=C.basename(a,".md");n.push(`${l} (project)`)}}const s=C.join(le.homedir(),".claude","agents");if(k.existsSync(s)){const o=k.readdirSync(s).filter(a=>a.endsWith(".md"));for(const a of o){const l=C.basename(a,".md");n.some(m=>m.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[s]=this.claudeVersion.split(".").map(Number);this.supportsSettingsFlag=s>=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(k.existsSync(a)){r=a;break}if(!r)return this.logger.warn("PostToolUse hook file not found at any expected location"),null;const s={hooks:{PostToolUse:[{matcher:"*",hooks:[{type:"command",command:`node ${r}`}]}]}},i=`claude-settings-${e}.json`,o=C.join(le.tmpdir(),i);return await pe.writeFile(o,JSON.stringify(s,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 s={};try{const f=await pe.readFile(n,"utf-8");s=JSON.parse(f)}catch{this.logger.debug("No existing settings.local.json found, creating new one")}s.hooks||(s.hooks={}),s.hooks.PostToolUse||(s.hooks.PostToolUse=[]);let i=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 f of o)if(k.existsSync(f)){i=f;break}if(!i){this.logger.warn("PostToolUse hook file not found at any expected location");return}const a={matcher:"*",hooks:[{type:"command",command:`node ${i}`}]};s.hooks.PostToolUse.some(f=>f.hooks&&Array.isArray(f.hooks)?f.hooks.some(m=>m.type==="command"&&m.command===`node ${i}`):!1)||(s.hooks.PostToolUse.push(a),await pe.writeFile(n,JSON.stringify(s,null,2)),this.logger.info(`Added PostToolUse hook to ${n}`))}catch(s){this.logger.error(`Failed to add PostToolUse hook: ${s}`)}}async removePostToolUseHook(e){const n=C.join(e,".claude","settings.local.json");try{const r=await pe.readFile(n,"utf-8"),s=JSON.parse(r);if(s.hooks?.PostToolUse){let i=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(k.existsSync(l)){i=l;break}if(!i)return;const a=`node ${i}`;s.hooks.PostToolUse=s.hooks.PostToolUse.filter(l=>l.hooks&&Array.isArray(l.hooks)?(l.hooks=l.hooks.filter(f=>!(f.type==="command"&&f.command===a)),l.hooks.length>0):!0),s.hooks.PostToolUse.length===0&&delete s.hooks.PostToolUse,Object.keys(s.hooks).length===0&&delete s.hooks,await pe.writeFile(n,JSON.stringify(s,null,2)),this.logger.info(`Removed PostToolUse hook from ${n}`)}}catch(r){this.logger.debug(`Could not remove PostToolUse hook: ${r}`)}}async launchAgent(e){const{payload:n}=e,r=n.agentSessionId,s=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd();this.startupCommands=n.agentConfig?.commands??[],this.startupCommandsExecuted=!1;const i=n.agentConfig?.xterm??!1;this.setXtermEnabled(i),await this.detectClaudeVersion();const o=n.agentConfig?.hooks?.preAgentStartHooks||n.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(o,s,r),D.SubEnvManager.isContainerMode&&i&&this.setFullscreen(!0),this.supportsSettingsFlag?await this.createTempSettingsFile(r):await this.addPostToolUseHook(s);const l=await this.discoverSubagents(s);l.length>0&&this.logger.info(`Discovered ${l.length} Claude subagent(s): ${l.join(", ")}`);const f=this.writeMcpConfigFile(n.agentConfig?.mcps,r),m=C.join(s,".mcp.json");await this.connectToSession(r),await this.setupDockerRepository(e);const E=this.buildClaudeArgs(e),p=[];k.existsSync(m)&&p.push(m),f&&p.push(f),p.length&&E.push("--mcp-config",...p);try{const _=this.getAgentEnvironmentVariables(),T=this.configureNodeOptions(_),u=process.listeners("SIGINT"),c=()=>{this.handleCtrlC()?(this.logger.info("Double Ctrl+C detected, terminating Claude agent..."),process.removeListener("SIGINT",c),u.forEach(F=>{typeof F=="function"&&process.on("SIGINT",F)}),this.ptyRunner.kill("SIGINT")):this.ptyRunner.sendInput("")};process.removeAllListeners("SIGINT"),process.on("SIGINT",c);const h=this.ptyRunner.spawn({command:this.claudePath,args:E,workingDir:s,agentSessionId:r,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{..._,NODE_OPTIONS:T,[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(g,F)=>{if(process.removeListener("SIGINT",c),u.forEach($=>{typeof $=="function"&&process.on("SIGINT",$)}),this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.optionTimeout&&(clearTimeout(this.optionTimeout),this.resetOptionState()),this.supportsSettingsFlag){if(this.tempSettingsPath){try{k.unlinkSync(this.tempSettingsPath),this.logger.info(`Removed temporary settings file: ${this.tempSettingsPath}`)}catch($){this.logger.warn("Failed to delete temp settings file",$)}this.tempSettingsPath=null}}else await this.removePostToolUseHook(s);if(this.tempMcpConfigPath){try{k.unlinkSync(this.tempMcpConfigPath)}catch($){this.logger.warn("Failed to delete temp MCP config file",$)}this.tempMcpConfigPath=null}this.logger.info(`Claude Code PTY exited with code ${g}, signal: ${F}`),this.sendAgentStatus({agentType:Y.CLAUDE_CODE,status:g===0?V.STOPPED:V.ERROR,message:`Claude Code session ended (exit code: ${g})`}),this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:F===2?"agent_sigint":"natural",exitCode:g,signal:F})},onData:async g=>{this.processDataForOptions(g),this.verifyAgentReady(g),this.xtermEnabled&&this.sendStdoutEvent(g)}});this.logger.success(`Claude Code launched successfully for session agentSessionId: ${r}`),this.ptySessionId=h.id,i?this.resizePty(80,24):this.setupInitialPtySize();const d={agentSessionId:r,agentType:Y.CLAUDE_CODE,status:V.IDLE,workingDir:s,process:h.ptyProcess,metadata:{agentSessionId:r,agentType:n.agentType,config:n.agentConfig,ptySessionId:h.id}};return this.setAgentInfo(d),d}catch(_){throw new Error(`Failed to launch Claude Code: ${_ instanceof Error?_.message:String(_)}`)}}async isAvailable(){return!0}async getVersion(){return"claude-pty-agent"}buildClaudeArgs(e){const n=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 ch{session;logger;constructor(e){this.logger=e??new D.Logger({verbose:!1})}async isDockerAvailable(){return new Promise(e=>{const n=se.spawn("docker",["--version"],{stdio:"pipe"});n.on("close",r=>{e(r===0)}),n.on("error",()=>{e(!1)})})}spawn(e,n){const r=e.agentSessionId||On.ulid(),s=e.workingDir??process.cwd(),i=e.dockerImage||"agiflow/claude-agent:latest",o=this.buildDockerArgs(r,e,i),a=`docker ${o.join(" ")}`;this.logger.info(`🐳 Docker Command: ${a}`),this.logger.debug("Spawning Docker container with args:",o);const l=se.spawn("docker",o,{stdio:["pipe","pipe","pipe"]}),f=`claude-agent-${r}`,m={id:r,dockerProcess:l,containerId:f,command:`docker ${o.join(" ")}`,workingDir:s,status:"running",createdAt:new Date,lastActivity:new Date,logStream:e.logStream};return l.stdout?.on("data",E=>{m.lastActivity=new Date;const p=E.toString();m.logStream&&m.logStream.write(p),process.stdout.write(p),n?.onData&&n.onData(p)}),l.stderr?.on("data",E=>{const p=E.toString();this.logger.error(`🐳 Container ${f} stderr: ${p.trim()}`),process.stderr.write(p)}),l.on("close",E=>{m.status=E===0?"stopped":"error",m.lastActivity=new Date,this.logger.info(`Container ${f} exited with code ${E}`),m.logStream&&m.logStream.end(),n?.onExit&&n.onExit(E||0,void 0)}),l.on("error",E=>{m.status="error",this.logger.error(`Container ${f} error:`,E),n?.onError&&n.onError(E)}),this.session=m,m}buildDockerArgs(e,n,r){const i=["run","--rm","--name",`claude-agent-${e}`,"-i"];if(n.privileged&&i.push("--privileged"),n.user&&i.push("--user",n.user),n.networkMode&&i.push("--network",n.networkMode),n.ports&&n.ports.length>0)for(const p of n.ports)i.push("-p",`${p.host}:${p.container}`);const o=n.agentServerUrl||D.SubEnvManager.serverUrl;i.push("-e",`${D.ENV_KEYS.AGENT_SERVER_URL}=${o}`);const a=n.agentApiKey||D.SubEnvManager.apiKey;a&&i.push("-e",`${D.ENV_KEYS.AGENT_API_KEY}=${a}`);const l=n.agentOrganizationId||D.SubEnvManager.organizationId;l&&i.push("-e",`${D.ENV_KEYS.AGENT_ORGANIZATION_ID}=${l}`);const f=n.agentType||D.SubEnvManager.agentType;f&&i.push("-e",`${D.ENV_KEYS.AGENT_TYPE}=${f}`);const m=e||D.SubEnvManager.sessionId;if(m&&i.push("-e",`${D.ENV_KEYS.AGENT_SESSION_ID}=${m}`),n.additionalEnvVars)for(const[p,_]of Object.entries(n.additionalEnvVars))i.push("-e",`${p}=${_}`);n.workingDir&&(i.push("-v",`${n.workingDir}:/workspace`),i.push("-w","/workspace"));const E=C.join(le.homedir(),".agiflow");if(Xr.existsSync(E)?(i.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 p of n.additionalVolumes){let _;p.type==="volume"?(_=p.readonly?`${p.host}:${p.container}:ro`:`${p.host}:${p.container}`,this.logger.debug(`Mounting named volume: ${p.host} -> ${p.container}`)):(_=p.readonly?`${p.host}:${p.container}:ro`:`${p.host}:${p.container}`,this.logger.debug(`Mounting bind volume: ${p.host} -> ${p.container}`)),i.push("-v",_)}if(D.SubEnvManager.isDebugMode&&i.push("-v","/var/run/docker.sock:/var/run/docker.sock"),i.push(r),i.push("claude"),i.push("--server-url",o),n.agentApiUrl&&i.push("--api-url",n.agentApiUrl),a&&i.push("--api-key",a),l&&i.push("--organization-id",l),m&&i.push("--agent-session-id",m),n.workingDir&&i.push("--working-directory","/workspace"),n.agentConfig){const p=encodeURIComponent(n.agentConfig);i.push("--agent-config",p)}return n.verbose&&i.push("--verbose"),n.args&&n.args.length>0&&i.push("--args",...n.args),i}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 lh{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 Ge(this.logger),this.dockerImage=e.dockerImage||"agiflow/agent:latest",this.onFullscreenChange=e.onFullscreenChange,this.dockerRunner=new ch(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 $r extends lh{onBeforeTerminate;constructor(e){super({...e,agentType:Y.CLAUDE_CODE,dockerImage:e.dockerImage||ae.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,s=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 i=this.getDockerOptions(e);try{const o=this.dockerRunner.spawn(i,{onExit:async(l,f)=>{if(this.logger.info(`Docker Claude agent exited with code ${l}, signal: ${f}`),this.onBeforeTerminate)try{this.logger.info("Executing cleanup callback before termination..."),await this.onBeforeTerminate(),this.logger.info("Cleanup callback completed successfully")}catch(m){this.logger.error("Error during cleanup callback:",m)}this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:f===2?"agent_sigint":"natural",exitCode:l,signal:f})},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:Y.CLAUDE_CODE,status:V.IDLE,workingDir:s,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,s=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd(),i=ae.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT,o=i.replace(/^http/,"ws");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:s,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:o,agentApiUrl:i,agentType:Y.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:ae.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 i=`${r}/.claude_tmp.json`;k.existsSync(i)||k.writeFileSync(i,"{}","utf8"),n.push({host:i,container:"/root/.claude.json",readonly:!1,type:"bind"});const o=`${r}/.claude_tmp`;k.existsSync(o)||k.mkdirSync(o,{recursive:!0}),n.push({host:o,container:"/root/.claude",readonly:!1,type:"bind"})}else{const i=`${r}/.claude.json`;k.existsSync(i)||k.writeFileSync(i,"{}","utf8"),n.push({host:i,container:"/root/.claude.json",readonly:!1,type:"bind"});const o=`${r}/.claude`;k.existsSync(o)||k.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 s=r.name||r.id||r.key;s&&(n[s]={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,s]of Object.entries(e))s&&typeof s=="object"&&(n[r]={...s,headers:s.headers||{}});return n}}class Or extends it{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").action(async n=>{try{await this.execute(n)}catch(r){this.handleError(r)}})}async execute(e){const n=e.serverUrl||ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,r=e.apiUrl||ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,s=e.apiKey||D.SubEnvManager.apiKey,i=e.organizationId||D.SubEnvManager.organizationId,o=e.agentSessionId||D.SubEnvManager.sessionId;n||(this.error("Server URL is required (--server-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT)"),process.exit(1)),o||(this.error(`Agent session ID is required (--agent-session-id or ${D.ENV_KEYS.AGENT_SESSION_ID})`),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)}if(r)try{new URL(r)}catch{this.error("Invalid API URL. Must be a valid HTTP URL."),process.exit(1)}const a=new D.Logger({verbose:e.verbose});e.verbose&&(this.info(`Starting Claude agent${e.docker?" in Docker container":""}...`),a.debug("Options:",e));const l=new D.CredentialsService,f=new Ge(a),m=e.docker?new $r({agentType:Y.CLAUDE_CODE,serverUrl:n,apiKey:s,organizationId:i,verbose:e.verbose,dockerImage:e.dockerImage,logger:a,terminationService:f}):new Ir({agentType:Y.CLAUDE_CODE,serverUrl:n,apiUrl:r,apiKey:s,organizationId:i,verbose:e.verbose,claudePath:e.claudePath,standalone:!0,logger:a,credentialsService:l,terminationService:f});let E={workingDirectory:e.workingDirectory?D.FileSystemUtils.getAbsolutePath(e.workingDirectory):process.cwd(),args:e.args||[]};if(e.agentConfig)try{const _=decodeURIComponent(e.agentConfig),T=JSON.parse(_);E={...E,...T}}catch(_){try{const T=JSON.parse(e.agentConfig);E={...E,...T}}catch{this.error(`Failed to parse agent config JSON: ${_ instanceof Error?_.message:String(_)}`),process.exit(1)}}const p=Ut.parse({payload:{sessionId:o,agentType:Y.CLAUDE_CODE,agentSessionId:o,agentConfig:E}});try{const _=await m.launchAgent(p);this.success(`Claude agent${e.docker?" (Docker)":""} launched successfully for session: ${_.agentSessionId}`);const T=async u=>{e.verbose&&this.info(`Received ${u}, shutting down Claude agent${e.docker?" container":""}...`);try{m.disconnect(),this.info(`Claude agent${e.docker?" container":""} shutdown complete`),process.exit(0)}catch(c){this.error(`Error during shutdown: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}};process.on("SIGINT",()=>T("SIGINT")),process.on("SIGTERM",()=>T("SIGTERM")),this.info(`Claude agent${e.docker?" container":""} is running. Press Ctrl+C to stop.`),await new Promise(()=>{})}catch(_){this.error(`Failed to start Claude agent: ${_ instanceof Error?_.message:String(_)}`),process.exit(1)}}}const hh=Jr.promisify(se.exec);class dh{claudeAgentsPath;constructor(e={}){this.claudeAgentsPath=e.claudeAgentsPath||C.join(le.homedir(),".claude","agents")}async findAgentsDirectory(){const e=C.join(process.cwd(),".claude","agents");try{if((await k.promises.stat(e)).isDirectory())return e}catch{}try{if((await k.promises.stat(this.claudeAgentsPath)).isDirectory())return this.claudeAgentsPath}catch{}try{const n=le.homedir(),r=[`"${n}/.config"`,`"${n}/.local"`,`"${n}/workspace"`,`"${n}/projects"`,`"${n}/dev"`,`"${n}/code"`,`"${n}/.claude"`,`"${n}"`];for(const s of r)try{const o=s===`"${n}"`?1:5,a=`find ${s} -maxdepth ${o} -type d -name "agents" -path "*/.claude/agents" 2>/dev/null | head -1`,{stdout:l}=await hh(a),f=l.trim();if(f&&f.length>0&&(await k.promises.stat(f)).isDirectory())return f}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 k.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 k.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
- `),s=r.findIndex(m=>m.trim()==="---"),i=r.findIndex((m,E)=>E>s&&m.trim()==="---");if(s===-1||i===-1)return console.error(`Invalid frontmatter in ${n}`),null;const o=r.slice(s+1,i),a={};for(const m of o){const E=m.indexOf(":");if(E>0){const p=m.substring(0,E).trim(),_=m.substring(E+1).trim();a[p]=_}}const f=r.slice(i+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:f,filePath:n}}async getAllAgentProfiles(){const e=await this.listAgentFiles(),n=[];for(const r of e){const s=await this.parseAgentFile(r);s&&n.push(s)}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(s=>s.name.toLowerCase().includes(r)||s.description.toLowerCase().includes(r))}}class zt{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 s=await jt.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}),i=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:s.trim(),client_id:this.options.clientId})});if(!i.ok){const l=await i.text();throw new Error(`Token exchange failed: ${i.status} ${l}`)}const o=await i.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 dh().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((i,o)=>{this.logger.info(` ${o+1}. ${i.name} - ${i.description.substring(0,80)}...`)}),await jt.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(s=>({name:s.name,description:s.description,prompt:s.prompt}))})});if(r.ok){const s=await r.json(),i=s.created?.length||0,o=s.errors?.length||0;i>0&&(this.logger.success(`Successfully uploaded ${i} agent profile(s) to your organization!`),s.created.forEach(a=>{this.logger.info(`✅ Created: ${a.user.name}`)})),o>0&&(this.logger.warn(`Failed to upload ${o} agent profile(s):`),s.errors.forEach(a=>{this.logger.warn(`❌ ${a.name}: ${a.error}`)}))}else{const s=await r.text();this.logger.warn(`❌ Failed to upload agent profiles: ${r.status} ${s}`)}}catch(r){this.logger.warn(`❌ Error uploading agent profiles: ${r instanceof Error?r.message:r}`)}}}class gh{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 fh{semaphores=new Map;permits;constructor(e=1){this.permits=e}getSemaphore(e){let n=this.semaphores.get(e);return n||(n=new gh(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 ph extends kr{geminiPath;tempExtensionConfigPath=null;agentInputReady=!1;optionBuffer="";optionTimeout=null;isCollectingOptions=!1;OPTION_WAIT_MS=1e3;constructor(e){super({...e,agentType:Y.GEMINI_CLI}),this.geminiPath=e.geminiPath||"gemini"}async launchAgent(e){const{payload:n}=e,r=n.agentSessionId,s=n.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(n.agentConfig.workingDirectory):process.cwd(),i=n.agentConfig?.xterm??!1;this.setXtermEnabled(i);const o=n.agentConfig?.hooks?.preAgentStartHooks||n.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(o,s,r),this.logger.debug("Agent config MCPs:",n.agentConfig?.mcps);const a=await this.writeGeminiExtensionFile(n.agentConfig?.mcps,s);this.logger.debug("Custom Gemini extension config result:",a);const l=C.join(s,"agiflow-extension.json");this.logger.debug("Project Gemini extension config path:",l),await this.connectToSession(r),await this.setupDockerRepository(e);const f=this.buildGeminiArgs(e);k.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 m=this.getAgentEnvironmentVariables(),E=this.configureNodeOptions(m),p=this.ptyRunner.spawn({command:this.geminiPath,args:f,workingDir:s,agentSessionId:r,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{...m,NODE_OPTIONS:E,GEMINI_SESSION_ID:r,GEMINI_AGENT_SESSION_ID:r,GEMINI_AGENT_MODE:"true",...a?{GEMINI_EXTENSION_CONFIG_FILE:a}:{}}},{onData:async T=>{this.verifyAgentReady(T),this.processDataForOptions(T),this.xtermEnabled&&this.sendStdoutEvent(T)},onExit:async(T,u)=>{if(this.tempExtensionConfigPath){try{k.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 ${T}, signal: ${u}`),this.sendAgentStatus({agentType:Y.GEMINI_CLI,status:T===0?V.STOPPED:V.ERROR,message:`Gemini session ended (exit code: ${T})`}),this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:"natural",exitCode:T,signal:u})}});this.logger.success(`Gemini launched successfully for session agentSessionId: ${r}`),this.ptySessionId=p.id,i?this.resizePty(80,24):this.setupInitialPtySize();const _={agentSessionId:r,agentType:Y.GEMINI_CLI,status:V.IDLE,workingDir:s,process:p.ptyProcess,metadata:{agentSessionId:r,agentType:n.agentType,config:n.agentConfig,ptySessionId:p.id}};return this.setAgentInfo(_),_}catch(m){throw new Error(`Failed to launch Gemini: ${m instanceof Error?m.message:String(m)}`)}}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:Y.GEMINI_CLI,status:V.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 i of r){const o=i.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 s=new Set;return n.filter(i=>s.has(i.number)?!1:(s.add(i.number),!0))}async handleDetectedOptions(e){if(!e.length||!this.agentInfo)return;const n=new Date().toISOString();try{const r=e.map(a=>({label:a.text,value:a.number,selected:!!a.selected})),s=D.createSelectComponent(r),i=D.createToolInvocationInput(!1,s),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"},i)];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 m of e){if(!m||typeof m!="object")continue;const E=m.name||m.id||m.key;if(!E)continue;const p={};m.type==="sse"?(p.url=m.url,m.headers&&Object.keys(m.headers).length>0&&(p.headers=m.headers)):(p.command=m.command,m.args&&m.args.length>0&&(p.args=m.args)),m.env&&Object.keys(m.env).length>0&&(p.env=m.env),m.disabled&&(p.disabled=m.disabled),r[E]=p}else if(typeof e=="object"){for(const[m,E]of Object.entries(e))if(E&&typeof E=="object"){const p=E,_={};p.type==="sse"||p.url?(_.url=p.url,p.headers&&Object.keys(p.headers).length>0&&(_.headers=p.headers)):(_.command=p.command,p.args&&p.args.length>0&&(_.args=p.args)),p.env&&Object.keys(p.env).length>0&&(_.env=p.env),p.disabled&&(_.disabled=p.disabled),r[m]=_}}if(Object.keys(r).length===0)return null;const s=await this.findGitRepoRoot(n),i=s||le.homedir();this.logger.debug(`Using base directory for Gemini extension: ${i}`);const o=C.join(i,".gemini","extensions");k.existsSync(o)||(k.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"]},f=C.join(o,"agiflow-extension.json");return k.writeFileSync(f,JSON.stringify(a,null,2),"utf8"),this.logger.debug(`Gemini extension config written to: ${f}`),this.tempExtensionConfigPath=f,s&&await this.ensureGitignoreEntry(s,".gemini/extensions/agiflow-extension.json"),f}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 s=C.join(n,".git");if(k.existsSync(s))return n;n=C.dirname(n)}return null}async ensureGitignoreEntry(e,n){const r=C.join(e,".gitignore");try{let s="";if(k.existsSync(r)&&(s=k.readFileSync(r,"utf8")),s.split(`
82
- `).some(a=>a.trim()===n))this.logger.debug(`Entry '${n}' already exists in .gitignore`);else{const a=s.endsWith(`
83
- `)||s===""?s+n+`
84
- `:s+`
85
- `+n+`
86
- `;k.writeFileSync(r,a,"utf8"),this.logger.debug(`Added '${n}' to .gitignore`)}}catch(s){this.logger.warn(`Failed to update .gitignore: ${s instanceof Error?s.message:String(s)}`)}}}class mh{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 s=15;for(;e!==n&&r<s;){const i=C.join(e,".git");if(k.existsSync(i))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 se.execSync(`git ${e}`,{cwd:n||this.repositoryPath,encoding:"utf8",stdio:"pipe"}).trim()}catch(r){this.logger.error(`Git command failed: git ${e}`,r);const s=new Error(`Git command failed: ${r.message}`);throw s.status=r.status,s.signal=r.signal,s.output=r.output,s}}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(s=>s.trim());for(const s of r){const i=s.split(`
89
- `);let o="",a="",l="";for(const f of i)f.startsWith("worktree ")?o=f.substring(9):f.startsWith("branch ")?a=f.substring(7):f.startsWith("HEAD ")&&(l=f.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,s=this.repositoryPath,i=C.basename(s),o=n||this.generateUniqueBranchName(),a=this.sanitizeBranchName(o),l=`${i}-worktrees`,f=r||a,m=C.join(this.repositoryPath,".."),E=C.join(m,l),p=C.join(E,f);k.existsSync(E)||await(await import("fs/promises")).mkdir(E,{recursive:!0});try{let _=`worktree add "${p}"`;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 T=this.checkBranchExists(`refs/heads/${o}`);let u=!1;T?_+=` ${o}`:(u=this.checkBranchExists(`refs/remotes/origin/${o}`),u?_+=` -b ${o} origin/${o}`:_+=` -b ${o}`),this.logger.info(`Creating worktree at ${p}`),this.execGit(_);const c=this.execGit("rev-parse HEAD",p),h=o||this.execGit("branch --show-current",p),d={path:p,branch:h,commit:c,isActive:!1,name:f};if(this.activeWorktrees.set(f,d),this.logger.success(`Worktree created successfully at ${p}`),!T&&!u)try{this.logger.info(`Pushing new branch ${h} to remote`),this.execGit(`push --set-upstream origin ${h}`,p),this.logger.success(`Branch ${h} pushed to remote`)}catch(g){this.logger.warn(`Could not push branch to remote: ${g.message}`)}return d}catch(_){throw this.logger.error(`Failed to create worktree: ${_.message}`),_}}async commitChanges(e,n,r=!0,s=!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 i=s?"--no-verify":"";this.execGit(`commit ${i} -m "${n}"`.trim(),e),this.logger.success(`Changes committed in worktree: ${e}`)}catch(i){throw this.logger.error(`Failed to commit changes: ${i.message}`),i}}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 i=r||this.execGit("branch --show-current",e);if(!i)throw new Error("No branch to push (detached HEAD)");try{this.logger.debug(`Pushing branch ${i} to ${n}`),this.execGit(`push --set-upstream ${n} ${i}`,e)}catch{try{this.logger.debug(`Retrying push without --set-upstream for ${i}`),this.execGit(`push ${n} ${i}`,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}/${i}`):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 ${i}: ${l}`),a}}this.logger.success(`Changes pushed to ${n}/${i}`),await this.createPullRequestIfPossible(e,i)}catch(i){throw this.logger.error(`Failed to push changes: ${i.message}`),i}}async commitAndPush(e,n,r="origin",s,i=!1){await this.commitChanges(e,n,!0,i),await this.pushChanges(e,r,s)}async removeWorktree(e,n=!1){try{const r=n?"--force":"";this.execGit(`worktree remove ${r} "${e}"`);for(const[s,i]of this.activeWorktrees.entries())if(i.path===e){this.activeWorktrees.delete(s);break}this.logger.success(`Worktree removed: ${e}`)}catch(r){throw this.logger.error(`Failed to remove worktree: ${r.message}`),r}}switchToWorktree(e){if(!k.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),s={path:e,branch:r||"detached",commit:n,isActive:!0,name:C.basename(e)};return this.logger.info(`Switched to worktree: ${e} (${r})`),s}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[,s]of this.activeWorktrees.entries())try{if(e)try{r?(await this.commitAndPush(s.path,n,"origin",void 0,!0),this.logger.info(`Committed and pushed changes for worktree: ${s.path}`)):(await this.commitChanges(s.path,n,!0,!0),this.logger.info(`Committed changes locally for worktree: ${s.path}`))}catch(i){this.logger.warn(`Failed to commit/push worktree ${s.path}: ${i}`)}await this.removeWorktree(s.path,!0)}catch(i){this.logger.warn(`Failed to remove worktree ${s.path}: ${i}`)}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?(se.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 se.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 se.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 se.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 s=se.execSync(`gh pr list --head "${n}" --json number`,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim(),i=JSON.parse(s||"[]");if(i.length>0){this.logger.info(`Pull request already exists for branch ${n}: #${i[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}"`,f=se.execSync(l,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim();this.logger.success(`Pull request created: ${f}`)}catch(s){s.message?.includes("authentication")||s.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: ${s.message}`)}}}class Dh{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 Ge(this.logger),this.onFullscreenChange=r,this.agentHttpService=new D.AgentHttpService({apiUrl:ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,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:s,agentSessionId:i}=n,o=await this.credentialsService.getAgentCreds();this.logger.info(`Launching agent - Type: ${s}, Session: ${r}, AgentSession: ${i}`),!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(i){const F={worktrees:[{name:d.name,branch:d.branch,path:d.path,createdAt:new Date().toISOString()}],currentSession:i};await this.agentHttpService.updateTaskDevInfo(i,F),this.logger.debug("Updated task devInfo with worktree information");const $=`🌳 Git worktree created for agent session
109
- - Location: \`${d.path}\`
110
- - Branch: \`${d.branch}\`
111
- - Name: ${d.name}`;await this.agentHttpService.createTaskComment(i,$),this.logger.debug("Added task comment about worktree creation");const A={sessionId:i,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(g){this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${g}`)}await this.setupWorktree(d.path,this.gitWorktreeService.getRepositoryPath(),i)}const f=s===Y.GEMINI_CLI,m=s===Y.CLAUDE_CODE;if(!f&&!m)throw this.logger.error(`Unsupported agent type: ${s}`),new Error(`Unsupported agent type: ${s}`);const E={agentType:s,serverUrl:ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,apiUrl:ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,...o,logger:this.logger,credentialsService:this.credentialsService,terminationService:this.terminationService,onFullscreenChange:this.onFullscreenChange},p=n.agentConfig?.docker===!0,_=n.agentConfig?.autonomous===!0;let T;f?T=new ph(E):m&&(p||_?(this.logger.info("Docker execution requested for Claude agent"),T=new $r({...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")}})):T=new Ir(E));const u=f?"Gemini":p?"Claude Docker":"Claude";if(this.logger.debug(`Created ${u} agent instance`),!T)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 T.launchAgent(e),this.instance=T,this.instance.setFullscreen(!0),this.logger.debug("Agent set to fullscreen mode for stdin handling"),this.logger.success(`Agent launched successfully - AgentSession: ${i}`),T}async initializeGitWorktreeService(e){try{const n=e.payload.agentConfig?.workingDirectory?D.FileSystemUtils.getAbsolutePath(e.payload.agentConfig.workingDirectory):process.cwd();this.gitWorktreeService=new mh(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 i=this.instance.getAgentInfo();i.workingDir=r.path,this.logger.info(`Agent working directory updated to worktree: ${r.path}`);try{const o=i.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 f=`🌳 Git worktree created
115
- - Location: \`${r.path}\`
116
- - Branch: \`${r.branch}\`
117
- - Name: ${r.name}`;await this.agentHttpService.createTaskComment(o,f),this.logger.debug("Added task comment about worktree creation");const m={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(m),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 s=this.instance?.getAgentInfo()?.agentSessionId;return await this.setupWorktree(r.path,this.gitWorktreeService.getRepositoryPath(),s),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 i=await new It({targetDirectory:e,originalDirectory:n,logger:this.logger}).setup();let o=`✅ Environment setup completed:
122
- `,a=!1;if(i.envFilesCopied.length>0){const l=i.envFilesCopied.filter(f=>f.copied).length;this.logger.success(`Copied ${l} environment files to worktree`),o+=`• Copied ${l} environment files
123
- `,a=!0}if(i.errors.length>0&&(this.logger.warn(`Worktree setup completed with ${i.errors.length} errors`),i.errors.forEach(l=>this.logger.debug(`Setup error: ${l}`)),o+=`• ⚠️ ${i.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:i.envFilesCopied.filter(f=>f.copied).length,errorsCount:i.errors.length}};await this.agentHttpService.sendMessage(l)}catch(l){this.logger.debug(`Failed to send setup complete message: ${l}`)}}catch(s){if(this.logger.error(`Failed to setup worktree: ${s}`),r)try{const i={sessionId:r,messageType:"output",content:`⚠️ Worktree setup encountered issues: ${s}
125
- The workspace is created but may require manual setup.`,metadata:{eventType:"worktree_setup_error",worktreePath:e,error:String(s)}};await this.agentHttpService.sendMessage(i)}catch(i){this.logger.debug(`Failed to send setup error message: ${i}`)}}}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(s){return this.logger.error(`Failed to commit and push worktree changes: ${s}`),!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 Eh{agents=new Map;agentLaunchSemaphore;logger;credentials;constructor(e){this.logger=e.logger,this.agentLaunchSemaphore=new fh(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,s]of this.agents.entries())r!==e&&s.isFullscreen&&(s.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 i=await this.credentials.getApiKey(),o=await this.credentials.getOrganizationId();if(!i||!o)throw new Error("Missing credentials to launch agent");const a=new Dh(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:Y.CLAUDE_CODE,executable:"claude"},{name:Y.GEMINI_CLI,executable:"gemini"}],n=[];for(const s of e){const i=await this.detectAgent(s.name,s.executable);n.push(i)}const r=n.filter(s=>s.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 s=this.executeCommand(`${n} --version`);if(s){const i=this.executeCommand(`which ${n}`);this.logger.info(`✅ Found ${e}: ${s.trim()}`),r={name:e,executable:n,isInstalled:!0,version:s.trim(),path:i?.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 se.execSync(e,{encoding:"utf8",stdio:"pipe",timeout:5e3})}catch{return null}}checkHostAuth(e){if(e!==Y.CLAUDE_CODE)return!1;const n=le.homedir(),r=le.platform()==="darwin";try{if(r){const s=C.join(n,".claude_tmp.json"),i=C.join(n,".claude_tmp");return k.existsSync(s)||k.existsSync(i)}else{const s=C.join(n,".claude.json"),i=C.join(n,".claude");return k.existsSync(s)||k.existsSync(i)}}catch(s){return this.logger.debug(`Error checking host auth for ${e}:`,s),!1}}checkDockerAuth(e){if(e!==Y.CLAUDE_CODE||!this.isDockerAvailableSync())return!1;const n=le.homedir(),r=le.platform()==="darwin";try{if(r){const s=C.join(n,".claude_tmp.json"),i=C.join(n,".claude_tmp");return k.existsSync(s)||k.existsSync(i)}else{const s=C.join(n,".claude.json"),i=C.join(n,".claude");return k.existsSync(s)||k.existsSync(i)}}catch(s){return this.logger.debug(`Error checking Docker auth for ${e}:`,s),!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(s=>({agentType:s.name,hostEnabled:!0,dockerEnabled:n}));return{hostExecution:e.length>0,dockerExecution:n,installedAgents:e,agentTypesForRegistration:r}}}class xr{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 s=await this.authService.getValidApiKey();e=s.api_key,n=s.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:n,expiresAt:s.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 s=await fetch(e,n);if(s.status===401&&r&&this.authService&&(await s.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 s.status===429&&this.logger.warn("🚫 Rate limit exceeded, keeping credentials but not retrying"),s}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,s=Cr(),i=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:s.hostname,platform:s.platform,workingDirectory:i,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 m=await l.text();throw new Error(`Registration failed: ${l.status} ${m}`)}const f=await l.json();if(f.device?.id?this.databaseDeviceId=f.device.id:f.deviceGuid&&(this.databaseDeviceId=f.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: ${f.id}`),this.logger.info(` Device ID (database): ${this.databaseDeviceId}`),f}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 s={lastHeartbeat:new Date().toISOString(),status:me.IDLE},i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${r}/daemons/${e.id}`,{method:"PATCH",headers:n,body:JSON.stringify(s)},!0);if(!i.ok){const o=await i.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to send heartbeat: ${i.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 s=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${r}/daemons/${e.id}`,{method:"DELETE",headers:n},!1);if(s.ok)this.logger.success("Daemon unregistered successfully");else{const i=await s.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to unregister daemon: ${s.status} ${i}`)}}catch(n){this.logger.warn("⚠️ Failed to unregister daemon:",n)}}}class Pr{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,s){const i=pr.parse({payload:{sessionId:e,data:r,error:{code:n,message:r,details:s instanceof Error?s.message:s}}});this.sendMessage(i)}async connectToDaemonChannel(e){return new Promise(async(n,r)=>{const{authToken:s,deviceGuid:i}=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 p=await this.options.authService.getValidApiKey();o=p.api_key,a=p.organization_id,await this.credentials.setApiKey({apiKey:o,organizationId:a,deviceId:p.device_id})}catch(p){this.logger.warn("Unable to refresh credentials:",p.message)}a||(a=this.options.organizationId),!o&&s&&(o=s);const l=a||this.options.organizationId;if(!l){r(new Error("Organization ID missing for daemon WebSocket connection"));return}const f=new URL(this.options.serverUrl);f.protocol==="http:"?f.protocol="ws:":f.protocol==="https:"&&(f.protocol="wss:");const m=e.id;f.pathname=`/api/v1/organizations/${l}/daemons/${m}/ws`,f.searchParams.set("clientType","daemon");const E=await this.credentials.buildDeviceAuthHeaders(i);if(!E["x-api-key"]){r(new Error("No API key available for WebSocket connection"));return}this.logger.info(`Connecting to daemon WebSocket: ${f.toString()}`),this.ws=new _e(f.toString(),{headers:E}),this.ws.on("open",()=>{this.isConnected=!0,this.logger.info("Daemon WebSocket connection established");const p=kt.parse({payload:{sessionId:i,data:"Daemon ready",status:me.IDLE}});this.sendMessage(p),this.callbacks.onConnect&&this.callbacks.onConnect(),n()}),this.ws.on("message",p=>{try{const _=p.toString(),T=JSON.parse(_);this.handleServerMessage(T)}catch(_){this.logger.error("Failed to parse server message:",_),this.logger.error(`Raw data: ${p.toString()}`)}}),this.ws.on("close",(p,_)=>{this.isConnected=!1,this.logger.info(`Daemon WebSocket disconnected (${p}): ${_}`),this.callbacks.onDisconnect&&this.callbacks.onDisconnect(p,_.toString()),this.shouldReconnect&&this.scheduleReconnect(e)}),this.ws.on("error",p=>{this.logger.error("WebSocket error:",p),this.callbacks.onError&&this.callbacks.onError(p),this.isConnected||r(p)}),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===N.STATUS&&e.command===S.REQUEST?await this.handleStatusRequest(e):e.eventType===N.START_AGENT&&e.command===S.REQUEST?await this.handleLaunchAgent(e):e.eventType===N.STOP_AGENT&&e.command===S.REQUEST?await this.handleStopAgent(e):e.eventType===N.TERMINATE&&e.command===S.REQUEST?await this.handleTerminateDaemon(e):e.eventType===N.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=fr.parse(e),r=kt.parse({eventType:N.STATUS,command:S.RESPONSE,payload:{sessionId:n.payload.sessionId,timestamp:Date.now(),data:"Daemon is running",status:me.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=Ut.parse(e),r=n.payload.agentSessionId;if(this.agentsManager.getAgent(r))return;this.agentsManager.startAgent(n,i=>{this.logger.warn(`Agent launch already in progress for session: ${r}`),this.sendError(i)})}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=vr.parse(e),r=n.payload.agentSessionId,s=await this.agentsManager.stopAgent(r),i=_r.parse({eventType:N.STOP_AGENT,command:S.RESPONSE,payload:{sessionId:n.payload.sessionId,timestamp:Date.now(),data:s?"Agent stopped successfully":"Agent not found",agentSessionId:r,status:s?"stopped":"not_found",message:s?`Agent ${r} has been stopped`:`Agent ${r} was not found`}});this.sendMessage(i),s?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=mr.parse(e);if(this.logger.info("Received daemon terminate request"),this.ws&&this.ws.readyState===_e.OPEN){const r=Dr.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 s of r)s.status===V.IDLE&&await this.sessionManager.terminateSession(s.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=Er.parse(e),r=this.sessionManager.getAllSessions(),s=yr.parse({payload:{sessionId:n.payload.sessionId,data:"Agent sessions list",sessions:r}});this.sendMessage(s)}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 vh{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||br(e.serverUrl)},this.options.deviceGuid=e.deviceGuid||wr(this.options.stableDeviceId!==!1),this.logger=new D.Logger({verbose:this.options.verbose||!1,logFile:this.options.logFile,logDir:this.options.logDir||Qr.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 Eh({logger:this.logger}),this.logger.debug("Setting up StdinForwarding service..."),this.stdinForwarding=new Tr({logger:this.logger,onData:this.onData.bind(this),onExit:this.onExit.bind(this)}),this.logger.debug("StdinForwarding service initialized"),this.terminationService=new Ge(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 zt({...e.options,logger:this.logger}),this.httpService=new xr({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 Pr({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=Ar(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(s){this.logger.warn("Failed to unregister daemon (non-fatal):",s)}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 Rr extends it{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||ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT,r=e.apiUrl||ae.VITE_INJECT_AGIFLOW_APP_ENDPOINT;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 s=e.reconnectInterval?parseInt(e.reconnectInterval,10):5e3;(isNaN(s)||s<1e3)&&(this.error("Invalid reconnect interval. Must be at least 1000ms."),process.exit(1));const i=new zt({clientId:"agiflow-cli-daemon",baseUrl:r,verbose:e.verbose});let o;try{e.verbose&&console.log("🔐 Authenticating..."),o=await i.getValidApiKey()}catch(f){const m=f instanceof Error?f.message:String(f);m.includes("cancelled by user")?(this.info(`
126
- Authentication cancelled`),process.exit(0)):(this.error(`Authentication failed: ${m}`),process.exit(1))}const a=new vh({serverUrl:n,apiUrl:r,authToken:o.api_key,organizationId:o.organization_id,verbose:e.verbose,reconnectInterval:s,stableDeviceId:!e.uniqueInstance,options:{clientId:"agiflow-cli-daemon",baseUrl:r,verbose:e.verbose}}),l=async f=>{console.log(`
127
- 📡 Received ${f}, initiating graceful shutdown...`);try{await a.stop()}catch(m){this.error(`Error during shutdown: ${m}`),process.exit(1)}};process.on("SIGINT",()=>l("SIGINT")),process.on("SIGTERM",()=>l("SIGTERM")),process.on("SIGHUP",()=>l("SIGHUP"));try{await a.start();const f=a.getStats();this.success("Agiflow Daemon connected successfully"),this.info(`🆔 Daemon ID: ${f.daemonId}`),this.info(`💻 Device GUID: ${f.deviceGuid}`),this.info(`Press Ctrl+C to disconnect
128
- `)}catch(f){this.error(`Failed to connect daemon: ${f}`),process.exit(1)}}}class Nr extends it{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 s=0;for(const i of r){const o=require("path").join(D.FileSystemUtils.AGIFLOW_DIR,i);await D.FileSystemUtils.exists(o)&&(await D.FileSystemUtils.remove(o),s++,e.verbose&&this.info(`Removed: ${i}`))}s===0?this.info("No credential files found. You are already logged out."):this.success(`Successfully logged out and removed ${s} 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)}}}Rn.config();async function _h(){const t=new as;t.name("agiflow").description("@agiflowai/agent-cli").option("-v, --verbose","enable verbose logging").option("--debug","enable debug mode");const e=new Or;"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 Rr;"register"in n&&typeof n.register=="function"?n.register(t):t.command("connect").description("Connect agent").action(async()=>{await n.run?.([])});const r=new Nr;"register"in r&&typeof r.register=="function"?r.register(t):t.command("logout").description("Logout and clean up credentials").action(async()=>{await r.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)}}_h();exports.BaseCommand=it;exports.ClaudeCommand=Or;exports.ConfigSchema=Fr;exports.ConnectCommand=Rr;exports.DaemonHttpService=xr;exports.DaemonWsService=Pr;exports.DeviceCodeAuthService=zt;exports.LogoutCommand=Nr;exports.config=ae;exports.createHeartbeat=Ar;exports.generateDeviceId=wr;exports.getServerUrl=Sr;exports.getSystemInfo=Cr;exports.getWebSocketUrl=ih;exports.httpToWebSocket=oh;exports.webSocketToHttp=br;
129
- //# sourceMappingURL=cli-CUdEH93F.js.map