@agiflowai/agent-cli 0.0.8 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/AgentHttpService-Cz0DO3Zx.js +28 -0
- package/dist/AgentHttpService-Cz0DO3Zx.js.map +1 -0
- package/dist/claudeNotification.js +34 -0
- package/dist/claudePostToolUse.js +27 -7
- package/dist/claudePreToolUse.js +30 -0
- package/dist/claudeSessionStart.js +30 -0
- package/dist/cli-Cr-ovvgN.js +104 -0
- package/dist/cli-Cr-ovvgN.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/networkLog.js +46 -24
- package/dist/package.json +5 -5
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/dist/AgentHttpService-MFVF-74l.js +0 -6
- package/dist/AgentHttpService-MFVF-74l.js.map +0 -1
- package/dist/cli-4pvA3zg9.js +0 -129
- package/dist/cli-4pvA3zg9.js.map +0 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";var tn=Object.create;var qe=Object.defineProperty;var nn=Object.getOwnPropertyDescriptor;var sn=Object.getOwnPropertyNames;var rn=Object.getPrototypeOf,on=Object.prototype.hasOwnProperty;var an=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of sn(e))!on.call(n,i)&&i!==t&&qe(n,i,{get:()=>e[i],enumerable:!(s=nn(e,i))||s.enumerable});return n};var ke=(n,e,t)=>(t=n!=null?tn(rn(n)):{},an(e||!n||!n.__esModule?qe(t,"default",{value:n,enumerable:!0}):t,n));const o=require("./AgentHttpService-Cz0DO3Zx.js"),un=require("node:events"),cn=require("node:child_process"),Dt=require("node:path"),ln=require("node:fs"),W=require("node:process"),C=require("fs"),F=require("path"),q=require("os"),pt=require("crypto"),ne=require("fs/promises"),re=require("ws"),hn=require("node-pty"),mt=require("ulidx"),z=require("child_process"),gn=require("events"),ve=require("@inquirer/prompts"),dn=require("node:crypto"),fn=require("node:os"),Dn=require("util");function ge(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const pn=ge(Dt),mn=ge(C),En=ge(hn),Fn=ge(dn),te=ge(fn);var Y={},me={},Ee={},Ye;function be(){if(Ye)return Ee;Ye=1;class n extends Error{constructor(s,i,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=s,this.nestedError=void 0}}class e extends n{constructor(s){super(1,"commander.invalidArgument",s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}return Ee.CommanderError=n,Ee.InvalidArgumentError=e,Ee}var Je;function He(){if(Je)return me;Je=1;const{InvalidArgumentError:n}=be();class e{constructor(i,r){switch(this.description=r||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,i[0]){case"<":this.required=!0,this._name=i.slice(1,-1);break;case"[":this.required=!1,this._name=i.slice(1,-1);break;default:this.required=!0,this._name=i;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(i,r){return r===this.defaultValue||!Array.isArray(r)?[i]:r.concat(i)}default(i,r){return this.defaultValue=i,this.defaultValueDescription=r,this}argParser(i){return this.parseArg=i,this}choices(i){return this.argChoices=i.slice(),this.parseArg=(r,a)=>{if(!this.argChoices.includes(r))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(r,a):r},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function t(s){const i=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+i+">":"["+i+"]"}return me.Argument=e,me.humanReadableArgName=t,me}var Ie={},xe={},Qe;function Et(){if(Qe)return xe;Qe=1;const{humanReadableArgName:n}=He();class e{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(s){const i=s.commands.filter(a=>!a._hidden),r=s._getHelpCommand();return r&&!r._hidden&&i.push(r),this.sortSubcommands&&i.sort((a,c)=>a.name().localeCompare(c.name())),i}compareOptions(s,i){const r=a=>a.short?a.short.replace(/^-/,""):a.long.replace(/^--/,"");return r(s).localeCompare(r(i))}visibleOptions(s){const i=s.options.filter(a=>!a.hidden),r=s._getHelpOption();if(r&&!r.hidden){const a=r.short&&s._findOption(r.short),c=r.long&&s._findOption(r.long);!a&&!c?i.push(r):r.long&&!c?i.push(s.createOption(r.long,r.description)):r.short&&!a&&i.push(s.createOption(r.short,r.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(s){if(!this.showGlobalOptions)return[];const i=[];for(let r=s.parent;r;r=r.parent){const a=r.options.filter(c=>!c.hidden);i.push(...a)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(s){return s._argsDescription&&s.registeredArguments.forEach(i=>{i.description=i.description||s._argsDescription[i.name()]||""}),s.registeredArguments.find(i=>i.description)?s.registeredArguments:[]}subcommandTerm(s){const i=s.registeredArguments.map(r=>n(r)).join(" ");return s._name+(s._aliases[0]?"|"+s._aliases[0]:"")+(s.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(s){return s.flags}argumentTerm(s){return s.name()}longestSubcommandTermLength(s,i){return i.visibleCommands(s).reduce((r,a)=>Math.max(r,i.subcommandTerm(a).length),0)}longestOptionTermLength(s,i){return i.visibleOptions(s).reduce((r,a)=>Math.max(r,i.optionTerm(a).length),0)}longestGlobalOptionTermLength(s,i){return i.visibleGlobalOptions(s).reduce((r,a)=>Math.max(r,i.optionTerm(a).length),0)}longestArgumentTermLength(s,i){return i.visibleArguments(s).reduce((r,a)=>Math.max(r,i.argumentTerm(a).length),0)}commandUsage(s){let i=s._name;s._aliases[0]&&(i=i+"|"+s._aliases[0]);let r="";for(let a=s.parent;a;a=a.parent)r=a.name()+" "+r;return r+i+" "+s.usage()}commandDescription(s){return s.description()}subcommandDescription(s){return s.summary()||s.description()}optionDescription(s){const i=[];return s.argChoices&&i.push(`choices: ${s.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),s.defaultValue!==void 0&&(s.required||s.optional||s.isBoolean()&&typeof s.defaultValue=="boolean")&&i.push(`default: ${s.defaultValueDescription||JSON.stringify(s.defaultValue)}`),s.presetArg!==void 0&&s.optional&&i.push(`preset: ${JSON.stringify(s.presetArg)}`),s.envVar!==void 0&&i.push(`env: ${s.envVar}`),i.length>0?`${s.description} (${i.join(", ")})`:s.description}argumentDescription(s){const i=[];if(s.argChoices&&i.push(`choices: ${s.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),s.defaultValue!==void 0&&i.push(`default: ${s.defaultValueDescription||JSON.stringify(s.defaultValue)}`),i.length>0){const r=`(${i.join(", ")})`;return s.description?`${s.description} ${r}`:r}return s.description}formatHelp(s,i){const r=i.padWidth(s,i),a=i.helpWidth||80,c=2,h=2;function f(l,g){if(g){const d=`${l.padEnd(r+h)}${g}`;return i.wrap(d,a-c,r+h)}return l}function p(l){return l.join(`
|
|
2
|
+
`).replace(/^/gm," ".repeat(c))}let E=[`Usage: ${i.commandUsage(s)}`,""];const m=i.commandDescription(s);m.length>0&&(E=E.concat([i.wrap(m,a,0),""]));const v=i.visibleArguments(s).map(l=>f(i.argumentTerm(l),i.argumentDescription(l)));v.length>0&&(E=E.concat(["Arguments:",p(v),""]));const _=i.visibleOptions(s).map(l=>f(i.optionTerm(l),i.optionDescription(l)));if(_.length>0&&(E=E.concat(["Options:",p(_),""])),this.showGlobalOptions){const l=i.visibleGlobalOptions(s).map(g=>f(i.optionTerm(g),i.optionDescription(g)));l.length>0&&(E=E.concat(["Global Options:",p(l),""]))}const u=i.visibleCommands(s).map(l=>f(i.subcommandTerm(l),i.subcommandDescription(l)));return u.length>0&&(E=E.concat(["Commands:",p(u),""])),E.join(`
|
|
3
|
+
`)}padWidth(s,i){return Math.max(i.longestOptionTermLength(s,i),i.longestGlobalOptionTermLength(s,i),i.longestSubcommandTermLength(s,i),i.longestArgumentTermLength(s,i))}wrap(s,i,r,a=40){const c=" \\f\\t\\v - \uFEFF",h=new RegExp(`[\\n][${c}]+`);if(s.match(h))return s;const f=i-r;if(f<a)return s;const p=s.slice(0,r),E=s.slice(r).replace(`\r
|
|
4
|
+
`,`
|
|
5
|
+
`),m=" ".repeat(r),_="\\s",u=new RegExp(`
|
|
6
|
+
|.{1,${f-1}}([${_}]|$)|[^${_}]+?([${_}]|$)`,"g"),l=E.match(u)||[];return p+l.map((g,d)=>g===`
|
|
7
|
+
`?"":(d>0?m:"")+g.trimEnd()).join(`
|
|
8
|
+
`)}}return xe.Help=e,xe}var Fe={},Ze;function Ft(){if(Ze)return Fe;Ze=1;const{InvalidArgumentError:n}=be();class e{constructor(a,c){this.flags=a,this.description=c||"",this.required=a.includes("<"),this.optional=a.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(a),this.mandatory=!1;const h=i(a);this.short=h.shortFlag,this.long=h.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(a,c){return this.defaultValue=a,this.defaultValueDescription=c,this}preset(a){return this.presetArg=a,this}conflicts(a){return this.conflictsWith=this.conflictsWith.concat(a),this}implies(a){let c=a;return typeof a=="string"&&(c={[a]:!0}),this.implied=Object.assign(this.implied||{},c),this}env(a){return this.envVar=a,this}argParser(a){return this.parseArg=a,this}makeOptionMandatory(a=!0){return this.mandatory=!!a,this}hideHelp(a=!0){return this.hidden=!!a,this}_concatValue(a,c){return c===this.defaultValue||!Array.isArray(c)?[a]:c.concat(a)}choices(a){return this.argChoices=a.slice(),this.parseArg=(c,h)=>{if(!this.argChoices.includes(c))throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(c,h):c},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return s(this.name().replace(/^no-/,""))}is(a){return this.short===a||this.long===a}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class t{constructor(a){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,a.forEach(c=>{c.negate?this.negativeOptions.set(c.attributeName(),c):this.positiveOptions.set(c.attributeName(),c)}),this.negativeOptions.forEach((c,h)=>{this.positiveOptions.has(h)&&this.dualOptions.add(h)})}valueFromOption(a,c){const h=c.attributeName();if(!this.dualOptions.has(h))return!0;const f=this.negativeOptions.get(h).presetArg,p=f!==void 0?f:!1;return c.negate===(p===a)}}function s(r){return r.split("-").reduce((a,c)=>a+c[0].toUpperCase()+c.slice(1))}function i(r){let a,c;const h=r.split(/[ |,]+/);return h.length>1&&!/^[[<]/.test(h[1])&&(a=h.shift()),c=h.shift(),!a&&/^-[^-]$/.test(c)&&(a=c,c=void 0),{shortFlag:a,longFlag:c}}return Fe.Option=e,Fe.DualOptions=t,Fe}var Oe={},Xe;function yn(){if(Xe)return Oe;Xe=1;const n=3;function e(s,i){if(Math.abs(s.length-i.length)>n)return Math.max(s.length,i.length);const r=[];for(let a=0;a<=s.length;a++)r[a]=[a];for(let a=0;a<=i.length;a++)r[0][a]=a;for(let a=1;a<=i.length;a++)for(let c=1;c<=s.length;c++){let h=1;s[c-1]===i[a-1]?h=0:h=1,r[c][a]=Math.min(r[c-1][a]+1,r[c][a-1]+1,r[c-1][a-1]+h),c>1&&a>1&&s[c-1]===i[a-2]&&s[c-2]===i[a-1]&&(r[c][a]=Math.min(r[c][a],r[c-2][a-2]+1))}return r[s.length][i.length]}function t(s,i){if(!i||i.length===0)return"";i=Array.from(new Set(i));const r=s.startsWith("--");r&&(s=s.slice(2),i=i.map(f=>f.slice(2)));let a=[],c=n;const h=.4;return i.forEach(f=>{if(f.length<=1)return;const p=e(s,f),E=Math.max(s.length,f.length);(E-p)/E>h&&(p<c?(c=p,a=[f]):p===c&&a.push(f))}),a.sort((f,p)=>f.localeCompare(p)),r&&(a=a.map(f=>`--${f}`)),a.length>1?`
|
|
9
|
+
(Did you mean one of ${a.join(", ")}?)`:a.length===1?`
|
|
10
|
+
(Did you mean ${a[0]}?)`:""}return Oe.suggestSimilar=t,Oe}var et;function Sn(){if(et)return Ie;et=1;const n=un.EventEmitter,e=cn,t=Dt,s=ln,i=W,{Argument:r,humanReadableArgName:a}=He(),{CommanderError:c}=be(),{Help:h}=Et(),{Option:f,DualOptions:p}=Ft(),{suggestSimilar:E}=yn();class m extends n{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:l=>i.stdout.write(l),writeErr:l=>i.stderr.write(l),getOutHelpWidth:()=>i.stdout.isTTY?i.stdout.columns:void 0,getErrHelpWidth:()=>i.stderr.isTTY?i.stderr.columns:void 0,outputError:(l,g)=>g(l)},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 l=this;l;l=l.parent)u.push(l);return u}command(u,l,g){let d=l,D=g;typeof d=="object"&&d!==null&&(D=d,d=null),D=D||{};const[,w,k]=u.match(/([^ ]+) *(.*)/),A=this.createCommand(w);return d&&(A.description(d),A._executableHandler=!0),D.isDefault&&(this._defaultCommandName=A._name),A._hidden=!!(D.noHelp||D.hidden),A._executableFile=D.executableFile||null,k&&A.arguments(k),this._registerCommand(A),A.parent=this,A.copyInheritedSettings(this),d?this:A}createCommand(u){return new m(u)}createHelp(){return Object.assign(new h,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,l){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 l=l||{},l.isDefault&&(this._defaultCommandName=u._name),(l.noHelp||l.hidden)&&(u._hidden=!0),this._registerCommand(u),u.parent=this,u._checkForBrokenPassThrough(),this}createArgument(u,l){return new r(u,l)}argument(u,l,g,d){const D=this.createArgument(u,l);return typeof g=="function"?D.default(d).argParser(g):D.default(g),this.addArgument(D),this}arguments(u){return u.trim().split(/ +/).forEach(l=>{this.argument(l)}),this}addArgument(u){const l=this.registeredArguments.slice(-1)[0];if(l&&l.variadic)throw new Error(`only the last argument can be variadic '${l.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,l){if(typeof u=="boolean")return this._addImplicitHelpCommand=u,this;u=u??"help [command]";const[,g,d]=u.match(/([^ ]+) *(.*)/),D=l??"display help for command",w=this.createCommand(g);return w.helpOption(!1),d&&w.arguments(d),D&&w.description(D),this._addImplicitHelpCommand=!0,this._helpCommand=w,this}addHelpCommand(u,l){return typeof u!="object"?(this.helpCommand(u,l),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,l){const g=["preSubcommand","preAction","postAction"];if(!g.includes(u))throw new Error(`Unexpected value for event passed to hook : '${u}'.
|
|
12
|
+
Expecting one of '${g.join("', '")}'`);return this._lifeCycleHooks[u]?this._lifeCycleHooks[u].push(l):this._lifeCycleHooks[u]=[l],this}exitOverride(u){return u?this._exitCallback=u:this._exitCallback=l=>{if(l.code!=="commander.executeSubCommandAsync")throw l},this}_exit(u,l,g){this._exitCallback&&this._exitCallback(new c(u,l,g)),i.exit(u)}action(u){const l=g=>{const d=this.registeredArguments.length,D=g.slice(0,d);return this._storeOptionsAsProperties?D[d]=this:D[d]=this.opts(),D.push(this),u.apply(this,D)};return this._actionHandler=l,this}createOption(u,l){return new f(u,l)}_callParseArg(u,l,g,d){try{return u.parseArg(l,g)}catch(D){if(D.code==="commander.invalidArgument"){const w=`${d} ${D.message}`;this.error(w,{exitCode:D.exitCode,code:D.code})}throw D}}_registerOption(u){const l=u.short&&this._findOption(u.short)||u.long&&this._findOption(u.long);if(l){const g=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 '${g}'
|
|
13
|
+
- already used by option '${l.flags}'`)}this.options.push(u)}_registerCommand(u){const l=d=>[d.name()].concat(d.aliases()),g=l(u).find(d=>this._findCommand(d));if(g){const d=l(this._findCommand(g)).join("|"),D=l(u).join("|");throw new Error(`cannot add command '${D}' as already have command '${d}'`)}this.commands.push(u)}addOption(u){this._registerOption(u);const l=u.name(),g=u.attributeName();if(u.negate){const D=u.long.replace(/^--no-/,"--");this._findOption(D)||this.setOptionValueWithSource(g,u.defaultValue===void 0?!0:u.defaultValue,"default")}else u.defaultValue!==void 0&&this.setOptionValueWithSource(g,u.defaultValue,"default");const d=(D,w,k)=>{D==null&&u.presetArg!==void 0&&(D=u.presetArg);const A=this.getOptionValue(g);D!==null&&u.parseArg?D=this._callParseArg(u,D,A,w):D!==null&&u.variadic&&(D=u._concatValue(D,A)),D==null&&(u.negate?D=!1:u.isBoolean()||u.optional?D=!0:D=""),this.setOptionValueWithSource(g,D,k)};return this.on("option:"+l,D=>{const w=`error: option '${u.flags}' argument '${D}' is invalid.`;d(D,w,"cli")}),u.envVar&&this.on("optionEnv:"+l,D=>{const w=`error: option '${u.flags}' value '${D}' from env '${u.envVar}' is invalid.`;d(D,w,"env")}),this}_optionEx(u,l,g,d,D){if(typeof l=="object"&&l instanceof f)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");const w=this.createOption(l,g);if(w.makeOptionMandatory(!!u.mandatory),typeof d=="function")w.default(D).argParser(d);else if(d instanceof RegExp){const k=d;d=(A,$)=>{const T=k.exec(A);return T?T[0]:$},w.default(D).argParser(d)}else w.default(d);return this.addOption(w)}option(u,l,g,d){return this._optionEx({},u,l,g,d)}requiredOption(u,l,g,d){return this._optionEx({mandatory:!0},u,l,g,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,l){return this.setOptionValueWithSource(u,l,void 0)}setOptionValueWithSource(u,l,g){return this._storeOptionsAsProperties?this[u]=l:this._optionValues[u]=l,this._optionValueSources[u]=g,this}getOptionValueSource(u){return this._optionValueSources[u]}getOptionValueSourceWithGlobals(u){let l;return this._getCommandAndAncestors().forEach(g=>{g.getOptionValueSource(u)!==void 0&&(l=g.getOptionValueSource(u))}),l}_prepareUserArgs(u,l){if(u!==void 0&&!Array.isArray(u))throw new Error("first parameter to parse must be array or undefined");if(l=l||{},u===void 0&&l.from===void 0){i.versions?.electron&&(l.from="electron");const d=i.execArgv??[];(d.includes("-e")||d.includes("--eval")||d.includes("-p")||d.includes("--print"))&&(l.from="eval")}u===void 0&&(u=i.argv),this.rawArgs=u.slice();let g;switch(l.from){case void 0:case"node":this._scriptPath=u[1],g=u.slice(2);break;case"electron":i.defaultApp?(this._scriptPath=u[1],g=u.slice(2)):g=u.slice(1);break;case"user":g=u.slice(0);break;case"eval":g=u.slice(1);break;default:throw new Error(`unexpected parse option { from: '${l.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",g}parse(u,l){const g=this._prepareUserArgs(u,l);return this._parseCommand([],g),this}async parseAsync(u,l){const g=this._prepareUserArgs(u,l);return await this._parseCommand([],g),this}_executeSubCommand(u,l){l=l.slice();let g=!1;const d=[".js",".ts",".tsx",".mjs",".cjs"];function D(T,B){const P=t.resolve(T,B);if(s.existsSync(P))return P;if(d.includes(t.extname(B)))return;const S=d.find(N=>s.existsSync(`${P}${N}`));if(S)return`${P}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let w=u._executableFile||`${this._name}-${u._name}`,k=this._executableDir||"";if(this._scriptPath){let T;try{T=s.realpathSync(this._scriptPath)}catch{T=this._scriptPath}k=t.resolve(t.dirname(T),k)}if(k){let T=D(k,w);if(!T&&!u._executableFile&&this._scriptPath){const B=t.basename(this._scriptPath,t.extname(this._scriptPath));B!==this._name&&(T=D(k,`${B}-${u._name}`))}w=T||w}g=d.includes(t.extname(w));let A;i.platform!=="win32"?g?(l.unshift(w),l=v(i.execArgv).concat(l),A=e.spawn(i.argv[0],l,{stdio:"inherit"})):A=e.spawn(w,l,{stdio:"inherit"}):(l.unshift(w),l=v(i.execArgv).concat(l),A=e.spawn(i.execPath,l,{stdio:"inherit"})),A.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(B=>{i.on(B,()=>{A.killed===!1&&A.exitCode===null&&A.kill(B)})});const $=this._exitCallback;A.on("close",T=>{T=T??1,$?$(new c(T,"commander.executeSubCommandAsync","(close)")):i.exit(T)}),A.on("error",T=>{if(T.code==="ENOENT"){const B=k?`searched for local subcommand relative to directory '${k}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",P=`'${w}' 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
|
+
- ${B}`;throw new Error(P)}else if(T.code==="EACCES")throw new Error(`'${w}' not executable`);if(!$)i.exit(1);else{const B=new c(1,"commander.executeSubCommandAsync","(error)");B.nestedError=T,$(B)}}),this.runningCommand=A}_dispatchSubcommand(u,l,g){const d=this._findCommand(u);d||this.help({error:!0});let D;return D=this._chainOrCallSubCommandHook(D,d,"preSubcommand"),D=this._chainOrCall(D,()=>{if(d._executableHandler)this._executeSubCommand(d,l.concat(g));else return d._parseCommand(l,g)}),D}_dispatchHelpCommand(u){u||this.help();const l=this._findCommand(u);return l&&!l._executableHandler&&l.help(),this._dispatchSubcommand(u,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((u,l)=>{u.required&&this.args[l]==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=(g,d,D)=>{let w=d;if(d!==null&&g.parseArg){const k=`error: command-argument value '${d}' is invalid for argument '${g.name()}'.`;w=this._callParseArg(g,d,D,k)}return w};this._checkNumberOfArguments();const l=[];this.registeredArguments.forEach((g,d)=>{let D=g.defaultValue;g.variadic?d<this.args.length?(D=this.args.slice(d),g.parseArg&&(D=D.reduce((w,k)=>u(g,k,w),g.defaultValue))):D===void 0&&(D=[]):d<this.args.length&&(D=this.args[d],g.parseArg&&(D=u(g,D,g.defaultValue))),l[d]=D}),this.processedArgs=l}_chainOrCall(u,l){return u&&u.then&&typeof u.then=="function"?u.then(()=>l()):l()}_chainOrCallHooks(u,l){let g=u;const d=[];return this._getCommandAndAncestors().reverse().filter(D=>D._lifeCycleHooks[l]!==void 0).forEach(D=>{D._lifeCycleHooks[l].forEach(w=>{d.push({hookedCommand:D,callback:w})})}),l==="postAction"&&d.reverse(),d.forEach(D=>{g=this._chainOrCall(g,()=>D.callback(D.hookedCommand,this))}),g}_chainOrCallSubCommandHook(u,l,g){let d=u;return this._lifeCycleHooks[g]!==void 0&&this._lifeCycleHooks[g].forEach(D=>{d=this._chainOrCall(d,()=>D(this,l))}),d}_parseCommand(u,l){const g=this.parseOptions(l);if(this._parseOptionsEnv(),this._parseOptionsImplied(),u=u.concat(g.operands),l=g.unknown,this.args=u.concat(l),u&&this._findCommand(u[0]))return this._dispatchSubcommand(u[0],u.slice(1),l);if(this._getHelpCommand()&&u[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(u[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(l),this._dispatchSubcommand(this._defaultCommandName,u,l);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(g.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();const d=()=>{g.unknown.length>0&&this.unknownOption(g.unknown[0])},D=`command:${this.name()}`;if(this._actionHandler){d(),this._processArguments();let w;return w=this._chainOrCallHooks(w,"preAction"),w=this._chainOrCall(w,()=>this._actionHandler(this.processedArgs)),this.parent&&(w=this._chainOrCall(w,()=>{this.parent.emit(D,u,l)})),w=this._chainOrCallHooks(w,"postAction"),w}if(this.parent&&this.parent.listenerCount(D))d(),this._processArguments(),this.parent.emit(D,u,l);else if(u.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",u,l);this.listenerCount("command:*")?this.emit("command:*",u,l):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(l=>l._name===u||l._aliases.includes(u))}_findOption(u){return this.options.find(l=>l.is(u))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(u=>{u.options.forEach(l=>{l.mandatory&&u.getOptionValue(l.attributeName())===void 0&&u.missingMandatoryOptionValue(l)})})}_checkForConflictingLocalOptions(){const u=this.options.filter(g=>{const d=g.attributeName();return this.getOptionValue(d)===void 0?!1:this.getOptionValueSource(d)!=="default"});u.filter(g=>g.conflictsWith.length>0).forEach(g=>{const d=u.find(D=>g.conflictsWith.includes(D.attributeName()));d&&this._conflictingOption(g,d)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(u=>{u._checkForConflictingLocalOptions()})}parseOptions(u){const l=[],g=[];let d=l;const D=u.slice();function w(A){return A.length>1&&A[0]==="-"}let k=null;for(;D.length;){const A=D.shift();if(A==="--"){d===g&&d.push(A),d.push(...D);break}if(k&&!w(A)){this.emit(`option:${k.name()}`,A);continue}if(k=null,w(A)){const $=this._findOption(A);if($){if($.required){const T=D.shift();T===void 0&&this.optionMissingArgument($),this.emit(`option:${$.name()}`,T)}else if($.optional){let T=null;D.length>0&&!w(D[0])&&(T=D.shift()),this.emit(`option:${$.name()}`,T)}else this.emit(`option:${$.name()}`);k=$.variadic?$:null;continue}}if(A.length>2&&A[0]==="-"&&A[1]!=="-"){const $=this._findOption(`-${A[1]}`);if($){$.required||$.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${$.name()}`,A.slice(2)):(this.emit(`option:${$.name()}`),D.unshift(`-${A.slice(2)}`));continue}}if(/^--[^=]+=/.test(A)){const $=A.indexOf("="),T=this._findOption(A.slice(0,$));if(T&&(T.required||T.optional)){this.emit(`option:${T.name()}`,A.slice($+1));continue}}if(w(A)&&(d=g),(this._enablePositionalOptions||this._passThroughOptions)&&l.length===0&&g.length===0){if(this._findCommand(A)){l.push(A),D.length>0&&g.push(...D);break}else if(this._getHelpCommand()&&A===this._getHelpCommand().name()){l.push(A),D.length>0&&l.push(...D);break}else if(this._defaultCommandName){g.push(A),D.length>0&&g.push(...D);break}}if(this._passThroughOptions){d.push(A),D.length>0&&d.push(...D);break}d.push(A)}return{operands:l,unknown:g}}opts(){if(this._storeOptionsAsProperties){const u={},l=this.options.length;for(let g=0;g<l;g++){const d=this.options[g].attributeName();u[d]=d===this._versionOptionName?this._version:this[d]}return u}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((u,l)=>Object.assign(u,l.opts()),{})}error(u,l){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 g=l||{},d=g.exitCode||1,D=g.code||"commander.error";this._exit(d,D,u)}_parseOptionsEnv(){this.options.forEach(u=>{if(u.envVar&&u.envVar in i.env){const l=u.attributeName();(this.getOptionValue(l)===void 0||["default","config","env"].includes(this.getOptionValueSource(l)))&&(u.required||u.optional?this.emit(`optionEnv:${u.name()}`,i.env[u.envVar]):this.emit(`optionEnv:${u.name()}`))}})}_parseOptionsImplied(){const u=new p(this.options),l=g=>this.getOptionValue(g)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(g));this.options.filter(g=>g.implied!==void 0&&l(g.attributeName())&&u.valueFromOption(this.getOptionValue(g.attributeName()),g)).forEach(g=>{Object.keys(g.implied).filter(d=>!l(d)).forEach(d=>{this.setOptionValueWithSource(d,g.implied[d],"implied")})})}missingArgument(u){const l=`error: missing required argument '${u}'`;this.error(l,{code:"commander.missingArgument"})}optionMissingArgument(u){const l=`error: option '${u.flags}' argument missing`;this.error(l,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(u){const l=`error: required option '${u.flags}' not specified`;this.error(l,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(u,l){const g=w=>{const k=w.attributeName(),A=this.getOptionValue(k),$=this.options.find(B=>B.negate&&k===B.attributeName()),T=this.options.find(B=>!B.negate&&k===B.attributeName());return $&&($.presetArg===void 0&&A===!1||$.presetArg!==void 0&&A===$.presetArg)?$:T||w},d=w=>{const k=g(w),A=k.attributeName();return this.getOptionValueSource(A)==="env"?`environment variable '${k.envVar}'`:`option '${k.flags}'`},D=`error: ${d(u)} cannot be used with ${d(l)}`;this.error(D,{code:"commander.conflictingOption"})}unknownOption(u){if(this._allowUnknownOption)return;let l="";if(u.startsWith("--")&&this._showSuggestionAfterError){let d=[],D=this;do{const w=D.createHelp().visibleOptions(D).filter(k=>k.long).map(k=>k.long);d=d.concat(w),D=D.parent}while(D&&!D._enablePositionalOptions);l=E(u,d)}const g=`error: unknown option '${u}'${l}`;this.error(g,{code:"commander.unknownOption"})}_excessArguments(u){if(this._allowExcessArguments)return;const l=this.registeredArguments.length,g=l===1?"":"s",D=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${l} argument${g} but got ${u.length}.`;this.error(D,{code:"commander.excessArguments"})}unknownCommand(){const u=this.args[0];let l="";if(this._showSuggestionAfterError){const d=[];this.createHelp().visibleCommands(this).forEach(D=>{d.push(D.name()),D.alias()&&d.push(D.alias())}),l=E(u,d)}const g=`error: unknown command '${u}'${l}`;this.error(g,{code:"commander.unknownCommand"})}version(u,l,g){if(u===void 0)return this._version;this._version=u,l=l||"-V, --version",g=g||"output the version number";const d=this.createOption(l,g);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,l){return u===void 0&&l===void 0?this._description:(this._description=u,l&&(this._argsDescription=l),this)}summary(u){return u===void 0?this._summary:(this._summary=u,this)}alias(u){if(u===void 0)return this._aliases[0];let l=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(l=this.commands[this.commands.length-1]),u===l._name)throw new Error("Command alias can't be the same as its name");const g=this.parent?._findCommand(u);if(g){const d=[g.name()].concat(g.aliases()).join("|");throw new Error(`cannot add alias '${u}' to command '${this.name()}' as already have command '${d}'`)}return l._aliases.push(u),this}aliases(u){return u===void 0?this._aliases:(u.forEach(l=>this.alias(l)),this)}usage(u){if(u===void 0){if(this._usage)return this._usage;const l=this.registeredArguments.map(g=>a(g));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?l:[]).join(" ")}return this._usage=u,this}name(u){return u===void 0?this._name:(this._name=u,this)}nameFromFilename(u){return this._name=t.basename(u,t.extname(u)),this}executableDir(u){return u===void 0?this._executableDir:(this._executableDir=u,this)}helpInformation(u){const l=this.createHelp();return l.helpWidth===void 0&&(l.helpWidth=u&&u.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),l.formatHelp(this,l)}_getHelpContext(u){u=u||{};const l={error:!!u.error};let g;return l.error?g=d=>this._outputConfiguration.writeErr(d):g=d=>this._outputConfiguration.writeOut(d),l.write=u.write||g,l.command=this,l}outputHelp(u){let l;typeof u=="function"&&(l=u,u=void 0);const g=this._getHelpContext(u);this._getCommandAndAncestors().reverse().forEach(D=>D.emit("beforeAllHelp",g)),this.emit("beforeHelp",g);let d=this.helpInformation(g);if(l&&(d=l(d),typeof d!="string"&&!Buffer.isBuffer(d)))throw new Error("outputHelp callback must return a string or a Buffer");g.write(d),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",g),this._getCommandAndAncestors().forEach(D=>D.emit("afterAllHelp",g))}helpOption(u,l){return typeof u=="boolean"?(u?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(u=u??"-h, --help",l=l??"display help for command",this._helpOption=this.createOption(u,l),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 l=i.exitCode||0;l===0&&u&&typeof u!="function"&&u.error&&(l=1),this._exit(l,"commander.help","(outputHelp)")}addHelpText(u,l){const g=["beforeAll","before","after","afterAll"];if(!g.includes(u))throw new Error(`Unexpected value for position to addHelpText.
|
|
21
|
+
Expecting one of '${g.join("', '")}'`);const d=`${u}Help`;return this.on(d,D=>{let w;typeof l=="function"?w=l({error:D.error,command:D.command}):w=l,w&&D.write(`${w}
|
|
22
|
+
`)}),this}_outputHelpIfRequested(u){const l=this._getHelpOption();l&&u.find(d=>l.is(d))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function v(_){return _.map(u=>{if(!u.startsWith("--inspect"))return u;let l,g="127.0.0.1",d="9229",D;return(D=u.match(/^(--inspect(-brk)?)$/))!==null?l=D[1]:(D=u.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(l=D[1],/^\d+$/.test(D[3])?d=D[3]:g=D[3]):(D=u.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(l=D[1],g=D[3],d=D[4]),l&&d!=="0"?`${l}=${g}:${parseInt(d)+1}`:u})}return Ie.Command=m,Ie}var tt;function Cn(){if(tt)return Y;tt=1;const{Argument:n}=He(),{Command:e}=Sn(),{CommanderError:t,InvalidArgumentError:s}=be(),{Help:i}=Et(),{Option:r}=Ft();return Y.program=new e,Y.createCommand=a=>new e(a),Y.createOption=(a,c)=>new r(a,c),Y.createArgument=(a,c)=>new n(a,c),Y.Command=e,Y.Option=r,Y.Argument=n,Y.Help=i,Y.CommanderError=t,Y.InvalidArgumentError=s,Y.InvalidOptionArgumentError=s,Y}var vn=Cn();const wn=o.getDefaultExportFromCjs(vn),{program:jr,createCommand:Lr,createArgument:Wr,createOption:Hr,CommanderError:Vr,InvalidArgumentError:Kr,InvalidOptionArgumentError:zr,Command:An,Argument:qr,Option:Yr,Help:Jr}=wn;var X={exports:{}};const _n="17.2.3",bn={version:_n};var nt;function Tn(){if(nt)return X.exports;nt=1;const n=C,e=F,t=q,s=pt,r=bn.version,a=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","📡 add observability to secrets: https://dotenvx.com/ops","👥 sync secrets across teammates & machines: https://dotenvx.com/ops","🗂️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","🔄 add secrets lifecycle management: https://dotenvx.com/ops","🔑 add access controls to secrets: https://dotenvx.com/ops","🛠️ 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 c(){return a[Math.floor(Math.random()*a.length)]}function h(S){return typeof S=="string"?!["false","0","no","off",""].includes(S.toLowerCase()):!!S}function f(){return process.stdout.isTTY}function p(S){return f()?`\x1B[2m${S}\x1B[0m`:S}const E=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function m(S){const N={};let U=S.toString();U=U.replace(/\r\n?/mg,`
|
|
23
|
+
`);let M;for(;(M=E.exec(U))!=null;){const V=M[1];let G=M[2]||"";G=G.trim();const I=G[0];G=G.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),I==='"'&&(G=G.replace(/\\n/g,`
|
|
24
|
+
`),G=G.replace(/\\r/g,"\r")),N[V]=G}return N}function v(S){S=S||{};const N=D(S);S.path=N;const U=P.configDotenv(S);if(!U.parsed){const I=new Error(`MISSING_DATA: Cannot parse ${N} for an unknown reason`);throw I.code="MISSING_DATA",I}const M=g(S).split(","),V=M.length;let G;for(let I=0;I<V;I++)try{const K=M[I].trim(),Q=d(U,K);G=P.decrypt(Q.ciphertext,Q.key);break}catch(K){if(I+1>=V)throw K}return P.parse(G)}function _(S){console.error(`[dotenv@${r}][WARN] ${S}`)}function u(S){console.log(`[dotenv@${r}][DEBUG] ${S}`)}function l(S){console.log(`[dotenv@${r}] ${S}`)}function g(S){return S&&S.DOTENV_KEY&&S.DOTENV_KEY.length>0?S.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function d(S,N){let U;try{U=new URL(N)}catch(K){if(K.code==="ERR_INVALID_URL"){const Q=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 Q.code="INVALID_DOTENV_KEY",Q}throw K}const M=U.password;if(!M){const K=new Error("INVALID_DOTENV_KEY: Missing key part");throw K.code="INVALID_DOTENV_KEY",K}const V=U.searchParams.get("environment");if(!V){const K=new Error("INVALID_DOTENV_KEY: Missing environment part");throw K.code="INVALID_DOTENV_KEY",K}const G=`DOTENV_VAULT_${V.toUpperCase()}`,I=S.parsed[G];if(!I){const K=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${G} in your .env.vault file.`);throw K.code="NOT_FOUND_DOTENV_ENVIRONMENT",K}return{ciphertext:I,key:M}}function D(S){let N=null;if(S&&S.path&&S.path.length>0)if(Array.isArray(S.path))for(const U of S.path)n.existsSync(U)&&(N=U.endsWith(".vault")?U:`${U}.vault`);else N=S.path.endsWith(".vault")?S.path:`${S.path}.vault`;else N=e.resolve(process.cwd(),".env.vault");return n.existsSync(N)?N:null}function w(S){return S[0]==="~"?e.join(t.homedir(),S.slice(1)):S}function k(S){const N=h(process.env.DOTENV_CONFIG_DEBUG||S&&S.debug),U=h(process.env.DOTENV_CONFIG_QUIET||S&&S.quiet);(N||!U)&&l("Loading env from encrypted .env.vault");const M=P._parseVault(S);let V=process.env;return S&&S.processEnv!=null&&(V=S.processEnv),P.populate(V,M,S),{parsed:M}}function A(S){const N=e.resolve(process.cwd(),".env");let U="utf8",M=process.env;S&&S.processEnv!=null&&(M=S.processEnv);let V=h(M.DOTENV_CONFIG_DEBUG||S&&S.debug),G=h(M.DOTENV_CONFIG_QUIET||S&&S.quiet);S&&S.encoding?U=S.encoding:V&&u("No encoding is specified. UTF-8 is used by default");let I=[N];if(S&&S.path)if(!Array.isArray(S.path))I=[w(S.path)];else{I=[];for(const Z of S.path)I.push(w(Z))}let K;const Q={};for(const Z of I)try{const ie=P.parse(n.readFileSync(Z,{encoding:U}));P.populate(Q,ie,S)}catch(ie){V&&u(`Failed to load ${Z} ${ie.message}`),K=ie}const Te=P.populate(M,Q,S);if(V=h(M.DOTENV_CONFIG_DEBUG||V),G=h(M.DOTENV_CONFIG_QUIET||G),V||!G){const Z=Object.keys(Te).length,ie=[];for(const ze of I)try{const pe=e.relative(process.cwd(),ze);ie.push(pe)}catch(pe){V&&u(`Failed to load ${ze} ${pe.message}`),K=pe}l(`injecting env (${Z}) from ${ie.join(",")} ${p(`-- tip: ${c()}`)}`)}return K?{parsed:Q,error:K}:{parsed:Q}}function $(S){if(g(S).length===0)return P.configDotenv(S);const N=D(S);return N?P._configVault(S):(_(`You set DOTENV_KEY but you are missing a .env.vault file at ${N}. Did you forget to build it?`),P.configDotenv(S))}function T(S,N){const U=Buffer.from(N.slice(-64),"hex");let M=Buffer.from(S,"base64");const V=M.subarray(0,12),G=M.subarray(-16);M=M.subarray(12,-16);try{const I=s.createDecipheriv("aes-256-gcm",U,V);return I.setAuthTag(G),`${I.update(M)}${I.final()}`}catch(I){const K=I instanceof RangeError,Q=I.message==="Invalid key length",Te=I.message==="Unsupported state or unable to authenticate data";if(K||Q){const Z=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Z.code="INVALID_DOTENV_KEY",Z}else if(Te){const Z=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Z.code="DECRYPTION_FAILED",Z}else throw I}}function B(S,N,U={}){const M=!!(U&&U.debug),V=!!(U&&U.override),G={};if(typeof N!="object"){const I=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw I.code="OBJECT_REQUIRED",I}for(const I of Object.keys(N))Object.prototype.hasOwnProperty.call(S,I)?(V===!0&&(S[I]=N[I],G[I]=N[I]),M&&u(V===!0?`"${I}" is already defined and WAS overwritten`:`"${I}" is already defined and was NOT overwritten`)):(S[I]=N[I],G[I]=N[I]);return G}const P={configDotenv:A,_configVault:k,_parseVault:v,config:$,decrypt:T,parse:m,populate:B};return X.exports.configDotenv=P.configDotenv,X.exports._configVault=P._configVault,X.exports._parseVault=P._parseVault,X.exports.config=P.config,X.exports.decrypt=P.decrypt,X.exports.parse=P.parse,X.exports.populate=P.populate,X.exports=P,X.exports}var kn=Tn();const yt=o.getDefaultExportFromCjs(kn),$e=10,st=(n=0)=>e=>`\x1B[${e+n}m`,it=(n=0)=>e=>`\x1B[${38+n};5;${e}m`,rt=(n=0)=>(e,t,s)=>`\x1B[${38+n};2;${e};${t};${s}m`,j={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(j.modifier);const In=Object.keys(j.color),xn=Object.keys(j.bgColor);[...In,...xn];function On(){const n=new Map;for(const[e,t]of Object.entries(j)){for(const[s,i]of Object.entries(t))j[s]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},t[s]=j[s],n.set(i[0],i[1]);Object.defineProperty(j,e,{value:t,enumerable:!1})}return Object.defineProperty(j,"codes",{value:n,enumerable:!1}),j.color.close="\x1B[39m",j.bgColor.close="\x1B[49m",j.color.ansi=st(),j.color.ansi256=it(),j.color.ansi16m=rt(),j.bgColor.ansi=st($e),j.bgColor.ansi256=it($e),j.bgColor.ansi16m=rt($e),Object.defineProperties(j,{rgbToAnsi256:{value(e,t,s){return e===t&&t===s?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[s]=t;s.length===3&&(s=[...s].map(r=>r+r).join(""));const i=Number.parseInt(s,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>j.rgbToAnsi256(...j.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,s,i;if(e>=232)t=((e-232)*10+8)/255,s=t,i=t;else{e-=16;const c=e%36;t=Math.floor(e/36)/5,s=Math.floor(c/6)/5,i=c%6/5}const r=Math.max(t,s,i)*2;if(r===0)return 30;let a=30+(Math.round(i)<<2|Math.round(s)<<1|Math.round(t));return r===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,s)=>j.ansi256ToAnsi(j.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>j.ansi256ToAnsi(j.hexToAnsi256(e)),enumerable:!1}}),j}const ee=On(),ot=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const n=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(n&&n.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),at=ot!==0&&{level:ot},$n={stdout:at,stderr:at};function Pn(n,e,t){let s=n.indexOf(e);if(s===-1)return n;const i=e.length;let r=0,a="";do a+=n.slice(r,s)+e+t,r=s+i,s=n.indexOf(e,r);while(s!==-1);return a+=n.slice(r),a}function Rn(n,e,t,s){let i=0,r="";do{const a=n[s-1]==="\r";r+=n.slice(i,a?s-1:s)+e+(a?`\r
|
|
25
|
+
`:`
|
|
26
|
+
`)+t,i=s+1,s=n.indexOf(`
|
|
27
|
+
`,i)}while(s!==-1);return r+=n.slice(i),r}const{stdout:ut,stderr:ct}=$n,Be=Symbol("GENERATOR"),ue=Symbol("STYLER"),he=Symbol("IS_EMPTY"),lt=["ansi","ansi","ansi256","ansi16m"],ce=Object.create(null),Nn=(n,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 t=ut?ut.level:0;n.level=e.level===void 0?t:e.level},Bn=n=>{const e=(...t)=>t.join(" ");return Nn(e,n),Object.setPrototypeOf(e,de.prototype),e};function de(n){return Bn(n)}Object.setPrototypeOf(de.prototype,Function.prototype);for(const[n,e]of Object.entries(ee))ce[n]={get(){const t=we(this,Me(e.open,e.close,this[ue]),this[he]);return Object.defineProperty(this,n,{value:t}),t}};ce.visible={get(){const n=we(this,this[ue],!0);return Object.defineProperty(this,"visible",{value:n}),n}};const Ue=(n,e,t,...s)=>n==="rgb"?e==="ansi16m"?ee[t].ansi16m(...s):e==="ansi256"?ee[t].ansi256(ee.rgbToAnsi256(...s)):ee[t].ansi(ee.rgbToAnsi(...s)):n==="hex"?Ue("rgb",e,t,...ee.hexToRgb(...s)):ee[t][n](...s),Un=["rgb","hex","ansi256"];for(const n of Un){ce[n]={get(){const{level:t}=this;return function(...s){const i=Me(Ue(n,lt[t],"color",...s),ee.color.close,this[ue]);return we(this,i,this[he])}}};const e="bg"+n[0].toUpperCase()+n.slice(1);ce[e]={get(){const{level:t}=this;return function(...s){const i=Me(Ue(n,lt[t],"bgColor",...s),ee.bgColor.close,this[ue]);return we(this,i,this[he])}}}}const Mn=Object.defineProperties(()=>{},{...ce,level:{enumerable:!0,get(){return this[Be].level},set(n){this[Be].level=n}}}),Me=(n,e,t)=>{let s,i;return t===void 0?(s=n,i=e):(s=t.openAll+n,i=e+t.closeAll),{open:n,close:e,openAll:s,closeAll:i,parent:t}},we=(n,e,t)=>{const s=(...i)=>Gn(s,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(s,Mn),s[Be]=n,s[ue]=e,s[he]=t,s},Gn=(n,e)=>{if(n.level<=0||!e)return n[he]?"":e;let t=n[ue];if(t===void 0)return e;const{openAll:s,closeAll:i}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Pn(e,t.close,t.open),t=t.parent;const r=e.indexOf(`
|
|
28
|
+
`);return r!==-1&&(e=Rn(e,i,s,r)),s+e+i};Object.defineProperties(de.prototype,ce);const jn=de();de({level:ct?ct.level:0});const Ln=(n,e,t,s)=>{if(t==="length"||t==="prototype"||t==="arguments"||t==="caller")return;const i=Object.getOwnPropertyDescriptor(n,t),r=Object.getOwnPropertyDescriptor(e,t);!Wn(i,r)&&s||Object.defineProperty(n,t,r)},Wn=function(n,e){return n===void 0||n.configurable||n.writable===e.writable&&n.enumerable===e.enumerable&&n.configurable===e.configurable&&(n.writable||n.value===e.value)},Hn=(n,e)=>{const t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(n)&&Object.setPrototypeOf(n,t)},Vn=(n,e)=>`/* Wrapped ${n}*/
|
|
29
|
+
${e}`,Kn=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),zn=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),qn=(n,e,t)=>{const s=t===""?"":`with ${t.trim()}() `,i=Vn.bind(null,s,e.toString());Object.defineProperty(i,"name",zn);const{writable:r,enumerable:a,configurable:c}=Kn;Object.defineProperty(n,"toString",{value:i,writable:r,enumerable:a,configurable:c})};function Yn(n,e,{ignoreNonConfigurable:t=!1}={}){const{name:s}=n;for(const i of Reflect.ownKeys(e))Ln(n,e,i,t);return Hn(n,e),qn(n,e,s),n}const Ae=new WeakMap,St=(n,e={})=>{if(typeof n!="function")throw new TypeError("Expected a function");let t,s=0;const i=n.displayName||n.name||"<anonymous>",r=function(...a){if(Ae.set(r,++s),s===1)t=n.apply(this,a),n=void 0;else if(e.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return t};return Yn(r,n),Ae.set(r,s),r};St.callCount=n=>{if(!Ae.has(n))throw new Error(`The given function \`${n.name}\` is not wrapped by the \`onetime\` package`);return Ae.get(n)};const ae=[];ae.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&ae.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&ae.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");const Ce=n=>!!n&&typeof n=="object"&&typeof n.removeListener=="function"&&typeof n.emit=="function"&&typeof n.reallyExit=="function"&&typeof n.listeners=="function"&&typeof n.kill=="function"&&typeof n.pid=="number"&&typeof n.on=="function",Pe=Symbol.for("signal-exit emitter"),Re=globalThis,Jn=Object.defineProperty.bind(Object);class Qn{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Re[Pe])return Re[Pe];Jn(Re,Pe,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const s=this.listeners[e],i=s.indexOf(t);i!==-1&&(i===0&&s.length===1?s.length=0:s.splice(i,1))}emit(e,t,s){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(const r of this.listeners[e])i=r(t,s)===!0||i;return e==="exit"&&(i=this.emit("afterExit",t,s)||i),i}}class Ct{}const Zn=n=>({onExit(e,t){return n.onExit(e,t)},load(){return n.load()},unload(){return n.unload()}});class Xn extends Ct{onExit(){return()=>{}}load(){}unload(){}}class es extends Ct{#o=Ge.platform==="win32"?"SIGINT":"SIGHUP";#n=new Qn;#e;#i;#g;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(const t of ae)this.#t[t]=()=>{const s=this.#e.listeners(t);let{count:i}=this.#n;const r=e;if(typeof r.__signal_exit_emitter__=="object"&&typeof r.__signal_exit_emitter__.count=="number"&&(i+=r.__signal_exit_emitter__.count),s.length===i){this.unload();const a=this.#n.emit("exit",null,t),c=t==="SIGHUP"?this.#o:t;a||e.kill(e.pid,c)}};this.#g=e.reallyExit,this.#i=e.emit}onExit(e,t){if(!Ce(this.#e))return()=>{};this.#r===!1&&this.load();const s=t?.alwaysLast?"afterExit":"exit";return this.#n.on(s,e),()=>{this.#n.removeListener(s,e),this.#n.listeners.exit.length===0&&this.#n.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#n.count+=1;for(const e of ae)try{const t=this.#t[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#d(e,...t),this.#e.reallyExit=e=>this.#s(e)}}unload(){this.#r&&(this.#r=!1,ae.forEach(e=>{const t=this.#t[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#i,this.#e.reallyExit=this.#g,this.#n.count-=1)}#s(e){return Ce(this.#e)?(this.#e.exitCode=e||0,this.#n.emit("exit",this.#e.exitCode,null),this.#g.call(this.#e,this.#e.exitCode)):0}#d(e,...t){const s=this.#i;if(e==="exit"&&Ce(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);const i=s.call(this.#e,e,...t);return this.#n.emit("exit",this.#e.exitCode,null),i}else return s.call(this.#e,e,...t)}}const Ge=globalThis.process,{onExit:ts}=Zn(Ce(Ge)?new es(Ge):new Xn),ht=W.stderr.isTTY?W.stderr:W.stdout.isTTY?W.stdout:void 0,ns=ht?St(()=>{ts(()=>{ht.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{};let _e=!1;const oe={};oe.show=(n=W.stderr)=>{n.isTTY&&(_e=!1,n.write("\x1B[?25h"))};oe.hide=(n=W.stderr)=>{n.isTTY&&(ns(),_e=!0,n.write("\x1B[?25l"))};oe.toggle=(n,e)=>{n!==void 0&&(_e=n),_e?oe.show(e):oe.hide(e)};const ss={interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},is={interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},rs={interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},os={interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},as={interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},us={interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},cs={interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},ls={interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},hs={interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},gs={interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},ds={interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},fs={interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},Ds={interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},ps={interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},ms={interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},Es={interval:130,frames:["-","\\","|","/"]},Fs={interval:100,frames:["⠂","-","–","—","–","-"]},ys={interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},Ss={interval:400,frames:[". ",".. ","..."," "]},Cs={interval:200,frames:[". ",".. ","..."," .."," ."," "]},vs={interval:70,frames:["✶","✸","✹","✺","✹","✷"]},ws={interval:80,frames:["+","x","*"]},As={interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},_s={interval:100,frames:["☱","☲","☴"]},bs={interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},Ts={interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},ks={interval:140,frames:[" ",".","o","O","@","*"," "]},Is={interval:120,frames:[".","o","O","°","O","o","."]},xs={interval:100,frames:["▓","▒","░"]},Os={interval:120,frames:["⠁","⠂","⠄","⠂"]},$s={interval:120,frames:["▖","▘","▝","▗"]},Ps={interval:100,frames:["▌","▀","▐","▄"]},Rs={interval:50,frames:["◢","◣","◤","◥"]},Ns={interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},Bs={interval:100,frames:["◜","◠","◝","◞","◡","◟"]},Us={interval:120,frames:["◡","⊙","◠"]},Ms={interval:180,frames:["◰","◳","◲","◱"]},Gs={interval:120,frames:["◴","◷","◶","◵"]},js={interval:50,frames:["◐","◓","◑","◒"]},Ls={interval:100,frames:["╫","╪"]},Ws={interval:250,frames:["⊶","⊷"]},Hs={interval:80,frames:["▫","▪"]},Vs={interval:120,frames:["□","■"]},Ks={interval:100,frames:["■","□","▪","▫"]},zs={interval:100,frames:["▮","▯"]},qs={interval:300,frames:["ဝ","၀"]},Ys={interval:80,frames:["⦾","⦿"]},Js={interval:100,frames:["◍","◌"]},Qs={interval:100,frames:["◉","◎"]},Zs={interval:100,frames:["㊂","㊀","㊁"]},Xs={interval:50,frames:["⧇","⧆"]},ei={interval:120,frames:["☗","☖"]},ti={interval:80,frames:["=","*","-"]},ni={interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},si={interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},ii={interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},ri={interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},oi={interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},ai={interval:200,frames:["😄 ","😝 "]},ui={interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},ci={interval:100,frames:["💛 ","💙 ","💜 ","💚 ","❤️ "]},li={interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},hi={interval:180,frames:["🌍 ","🌎 ","🌏 "]},gi={interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},di={interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},fi={interval:140,frames:["🚶 ","🏃 "]},Di={interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},pi={interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},mi={interval:100,frames:["d","q","p","b"]},Ei={interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},Fi={interval:400,frames:["🌲","🎄"]},yi={interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},Si={interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},Ci={interval:150,frames:["-","=","≡"]},vi={interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},wi={interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},Ai={interval:80,frames:["🤜 🤛 ","🤜 🤛 ","🤜 🤛 "," 🤜 🤛 "," 🤜🤛 "," 🤜✨🤛 ","🤜 ✨ 🤛 "]},_i={interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},bi={interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ "," "," "," "]},Ti={interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},ki={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},Ii={interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},xi={interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},Oi={interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},$i={interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},Pi={interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]},Ri={dots:ss,dots2:is,dots3:rs,dots4:os,dots5:as,dots6:us,dots7:cs,dots8:ls,dots9:hs,dots10:gs,dots11:ds,dots12:fs,dots13:Ds,dots8Bit:ps,sand:ms,line:Es,line2:Fs,pipe:ys,simpleDots:Ss,simpleDotsScrolling:Cs,star:vs,star2:ws,flip:As,hamburger:_s,growVertical:bs,growHorizontal:Ts,balloon:ks,balloon2:Is,noise:xs,bounce:Os,boxBounce:$s,boxBounce2:Ps,triangle:Rs,binary:Ns,arc:Bs,circle:Us,squareCorners:Ms,circleQuarters:Gs,circleHalves:js,squish:Ls,toggle:Ws,toggle2:Hs,toggle3:Vs,toggle4:Ks,toggle5:zs,toggle6:qs,toggle7:Ys,toggle8:Js,toggle9:Qs,toggle10:Zs,toggle11:Xs,toggle12:ei,toggle13:ti,arrow:ni,arrow2:si,arrow3:ii,bouncingBar:ri,bouncingBall:oi,smiley:ai,monkey:ui,hearts:ci,clock:li,earth:hi,material:gi,moon:di,runner:fi,pong:Di,shark:pi,dqpb:mi,weather:Ei,christmas:Fi,grenade:yi,point:Si,layer:Ci,betaWave:vi,fingerDance:wi,fistBump:Ai,soccerHeader:_i,mindblown:bi,speaker:Ti,orangePulse:ki,bluePulse:Ii,orangeBluePulse:xi,timeTravel:Oi,aesthetic:$i,dwarfFortress:Pi};var Ne,gt;function Ni(){if(gt)return Ne;gt=1;const n=Object.assign({},Ri),e=Object.keys(n);return Object.defineProperty(n,"random",{get(){const t=Math.floor(Math.random()*e.length),s=e[t];return n[s]}}),Ne=n,Ne}var Bi=Ni();const ye=o.getDefaultExportFromCjs(Bi),Se={info:"ℹ️",success:"✅",warning:"⚠️",error:"❌️"};function Ui({onlyFirst:n=!1}={}){const i="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(i,n?void 0:"g")}const Mi=Ui();function le(n){if(typeof n!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof n}\``);return n.replace(Mi,"")}function Gi(n){return n===161||n===164||n===167||n===168||n===170||n===173||n===174||n>=176&&n<=180||n>=182&&n<=186||n>=188&&n<=191||n===198||n===208||n===215||n===216||n>=222&&n<=225||n===230||n>=232&&n<=234||n===236||n===237||n===240||n===242||n===243||n>=247&&n<=250||n===252||n===254||n===257||n===273||n===275||n===283||n===294||n===295||n===299||n>=305&&n<=307||n===312||n>=319&&n<=322||n===324||n>=328&&n<=331||n===333||n===338||n===339||n===358||n===359||n===363||n===462||n===464||n===466||n===468||n===470||n===472||n===474||n===476||n===593||n===609||n===708||n===711||n>=713&&n<=715||n===717||n===720||n>=728&&n<=731||n===733||n===735||n>=768&&n<=879||n>=913&&n<=929||n>=931&&n<=937||n>=945&&n<=961||n>=963&&n<=969||n===1025||n>=1040&&n<=1103||n===1105||n===8208||n>=8211&&n<=8214||n===8216||n===8217||n===8220||n===8221||n>=8224&&n<=8226||n>=8228&&n<=8231||n===8240||n===8242||n===8243||n===8245||n===8251||n===8254||n===8308||n===8319||n>=8321&&n<=8324||n===8364||n===8451||n===8453||n===8457||n===8467||n===8470||n===8481||n===8482||n===8486||n===8491||n===8531||n===8532||n>=8539&&n<=8542||n>=8544&&n<=8555||n>=8560&&n<=8569||n===8585||n>=8592&&n<=8601||n===8632||n===8633||n===8658||n===8660||n===8679||n===8704||n===8706||n===8707||n===8711||n===8712||n===8715||n===8719||n===8721||n===8725||n===8730||n>=8733&&n<=8736||n===8739||n===8741||n>=8743&&n<=8748||n===8750||n>=8756&&n<=8759||n===8764||n===8765||n===8776||n===8780||n===8786||n===8800||n===8801||n>=8804&&n<=8807||n===8810||n===8811||n===8814||n===8815||n===8834||n===8835||n===8838||n===8839||n===8853||n===8857||n===8869||n===8895||n===8978||n>=9312&&n<=9449||n>=9451&&n<=9547||n>=9552&&n<=9587||n>=9600&&n<=9615||n>=9618&&n<=9621||n===9632||n===9633||n>=9635&&n<=9641||n===9650||n===9651||n===9654||n===9655||n===9660||n===9661||n===9664||n===9665||n>=9670&&n<=9672||n===9675||n>=9678&&n<=9681||n>=9698&&n<=9701||n===9711||n===9733||n===9734||n===9737||n===9742||n===9743||n===9756||n===9758||n===9792||n===9794||n===9824||n===9825||n>=9827&&n<=9829||n>=9831&&n<=9834||n===9836||n===9837||n===9839||n===9886||n===9887||n===9919||n>=9926&&n<=9933||n>=9935&&n<=9939||n>=9941&&n<=9953||n===9955||n===9960||n===9961||n>=9963&&n<=9969||n===9972||n>=9974&&n<=9977||n===9979||n===9980||n===9982||n===9983||n===10045||n>=10102&&n<=10111||n>=11094&&n<=11097||n>=12872&&n<=12879||n>=57344&&n<=63743||n>=65024&&n<=65039||n===65533||n>=127232&&n<=127242||n>=127248&&n<=127277||n>=127280&&n<=127337||n>=127344&&n<=127373||n===127375||n===127376||n>=127387&&n<=127404||n>=917760&&n<=917999||n>=983040&&n<=1048573||n>=1048576&&n<=1114109}function ji(n){return n===12288||n>=65281&&n<=65376||n>=65504&&n<=65510}function Li(n){return n>=4352&&n<=4447||n===8986||n===8987||n===9001||n===9002||n>=9193&&n<=9196||n===9200||n===9203||n===9725||n===9726||n===9748||n===9749||n>=9776&&n<=9783||n>=9800&&n<=9811||n===9855||n>=9866&&n<=9871||n===9875||n===9889||n===9898||n===9899||n===9917||n===9918||n===9924||n===9925||n===9934||n===9940||n===9962||n===9970||n===9971||n===9973||n===9978||n===9981||n===9989||n===9994||n===9995||n===10024||n===10060||n===10062||n>=10067&&n<=10069||n===10071||n>=10133&&n<=10135||n===10160||n===10175||n===11035||n===11036||n===11088||n===11093||n>=11904&&n<=11929||n>=11931&&n<=12019||n>=12032&&n<=12245||n>=12272&&n<=12287||n>=12289&&n<=12350||n>=12353&&n<=12438||n>=12441&&n<=12543||n>=12549&&n<=12591||n>=12593&&n<=12686||n>=12688&&n<=12773||n>=12783&&n<=12830||n>=12832&&n<=12871||n>=12880&&n<=42124||n>=42128&&n<=42182||n>=43360&&n<=43388||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65040&&n<=65049||n>=65072&&n<=65106||n>=65108&&n<=65126||n>=65128&&n<=65131||n>=94176&&n<=94180||n>=94192&&n<=94198||n>=94208&&n<=101589||n>=101631&&n<=101662||n>=101760&&n<=101874||n>=110576&&n<=110579||n>=110581&&n<=110587||n===110589||n===110590||n>=110592&&n<=110882||n===110898||n>=110928&&n<=110930||n===110933||n>=110948&&n<=110951||n>=110960&&n<=111355||n>=119552&&n<=119638||n>=119648&&n<=119670||n===126980||n===127183||n===127374||n>=127377&&n<=127386||n>=127488&&n<=127490||n>=127504&&n<=127547||n>=127552&&n<=127560||n===127568||n===127569||n>=127584&&n<=127589||n>=127744&&n<=127776||n>=127789&&n<=127797||n>=127799&&n<=127868||n>=127870&&n<=127891||n>=127904&&n<=127946||n>=127951&&n<=127955||n>=127968&&n<=127984||n===127988||n>=127992&&n<=128062||n===128064||n>=128066&&n<=128252||n>=128255&&n<=128317||n>=128331&&n<=128334||n>=128336&&n<=128359||n===128378||n===128405||n===128406||n===128420||n>=128507&&n<=128591||n>=128640&&n<=128709||n===128716||n>=128720&&n<=128722||n>=128725&&n<=128728||n>=128732&&n<=128735||n===128747||n===128748||n>=128756&&n<=128764||n>=128992&&n<=129003||n===129008||n>=129292&&n<=129338||n>=129340&&n<=129349||n>=129351&&n<=129535||n>=129648&&n<=129660||n>=129664&&n<=129674||n>=129678&&n<=129734||n===129736||n>=129741&&n<=129756||n>=129759&&n<=129770||n>=129775&&n<=129784||n>=131072&&n<=196605||n>=196608&&n<=262141}function Wi(n){if(!Number.isSafeInteger(n))throw new TypeError(`Expected a code point, got \`${typeof n}\`.`)}function Hi(n,{ambiguousAsWide:e=!1}={}){return Wi(n),ji(n)||Li(n)||e&&Gi(n)?2:1}const Vi=()=>/[#*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-\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-\uDED8\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]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\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]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\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]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\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]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\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]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\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]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\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]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\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]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\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]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\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]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\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\uDD3C-\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-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\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\uDE70]|\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]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\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]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\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]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\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]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\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]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\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,Ki=new Intl.Segmenter,zi=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function qi(n,e={}){if(typeof n!="string"||n.length===0)return 0;const{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:s=!1}=e;if(s||(n=le(n)),n.length===0)return 0;let i=0;const r={ambiguousAsWide:!t};for(const{segment:a}of Ki.segment(n)){const c=a.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!zi.test(a)){if(Vi().test(a)){i+=2;continue}i+=Hi(c,r)}}return i}function Yi({stream:n=process.stdout}={}){return!!(n&&n.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}function Ji(){const{env:n}=W,{TERM:e,TERM_PROGRAM:t}=n;return W.platform!=="win32"?e!=="linux":!!n.WT_SESSION||!!n.TERMINUS_SUBLIME||n.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||n.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const Qi=3;class Zi{#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(){W.platform==="win32"||!W.stdin.isTTY||(W.stdin.setRawMode(!0),W.stdin.on("data",this.#i),W.stdin.resume())}#e(){W.stdin.isTTY&&(W.stdin.off("data",this.#i),W.stdin.pause(),W.stdin.setRawMode(!1))}#i(e){e[0]===Qi&&W.emit("SIGINT")}}const dt=new Zi;class Xi{#o=0;#n=!1;#e=0;#i=-1;#g=0;#t;#r;#s;#d;#D;#c;#l;#h;#p;#a;#u;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:W.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#D=this.#t.interval,this.#s=this.#t.stream,this.#c=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Yi({stream:this.#s}),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,W.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#c,Object.defineProperty(this,"_linesToClear",{get(){return this.#o},set(t){this.#o=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#i}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#h}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#h=e,this.#f()}get interval(){return this.#D??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#i=-1,this.#D=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Ji())this.#r=ye.line;else if(e===void 0)this.#r=ye.dots;else if(e!=="default"&&ye[e])this.#r=ye[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.#p}set text(e=""){this.#p=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.#d!==void 0}#m(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#E(e=this.#u,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){const e=this.#s.columns??80,t=this.#m(this.#a,"-"),s=this.#E(this.#u,"-"),i=" ".repeat(this.#h)+t+"--"+this.#p+"--"+s;this.#e=0;for(const r of le(i).split(`
|
|
30
|
+
`))this.#e+=Math.max(1,Math.ceil(qi(r,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#c&&!this.#l}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#c=e}get isSilent(){return this.#l}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#l=e}frame(){const e=Date.now();(this.#i===-1||e-this.#g>=this.interval)&&(this.#i=++this.#i%this.#r.frames.length,this.#g=e);const{frames:t}=this.#r;let s=t[this.#i];this.color&&(s=jn[this.color](s));const i=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",r=typeof this.text=="string"?" "+this.text:"",a=typeof this.#u=="string"&&this.#u!==""?" "+this.#u:"";return i+s+r+a}clear(){if(!this.#c||!this.#s.isTTY)return this;this.#s.cursorTo(0);for(let e=0;e<this.#o;e++)e>0&&this.#s.moveCursor(0,-1),this.#s.clearLine(1);return(this.#h||this.lastIndent!==this.#h)&&this.#s.cursorTo(this.#h),this.lastIndent=this.#h,this.#o=0,this}render(){return this.#l?this:(this.clear(),this.#s.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&&oe.hide(this.#s),this.#t.discardStdin&&W.stdin.isTTY&&(this.#n=!0,dt.start()),this.render(),this.#d=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
|
|
31
|
+
`),this)}stop(){return this.#c?(clearInterval(this.#d),this.#d=void 0,this.#i=0,this.clear(),this.#t.hideCursor&&oe.show(this.#s),this.#t.discardStdin&&W.stdin.isTTY&&this.#n&&(dt.stop(),this.#n=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Se.success,text:e})}fail(e){return this.stopAndPersist({symbol:Se.error,text:e})}warn(e){return this.stopAndPersist({symbol:Se.warning,text:e})}info(e){return this.stopAndPersist({symbol:Se.info,text:e})}stopAndPersist(e={}){if(this.#l)return this;const t=e.prefixText??this.#a,s=this.#m(t," "),i=e.symbol??" ",r=e.text??this.text,c=typeof r=="string"?(i?" ":"")+r:"",h=e.suffixText??this.#u,f=this.#E(h," "),p=s+i+c+f+`
|
|
32
|
+
`;return this.stop(),this.#s.write(p),this}}function er(n){return new Xi(n)}class fe{spinner;createSpinner(e){return this.spinner=er(e),this.spinner}success(e){try{this.spinner?this.spinner.succeed(o.chalk.green(e)):console.log(o.chalk.green("✓"),e)}catch{try{process.stdout?.write?.(`✓ ${e}
|
|
33
|
+
`)}catch{}}}error(e){try{this.spinner?this.spinner.fail(o.chalk.red(e)):console.error(o.chalk.red("✗"),e)}catch{try{process.stderr?.write?.(`✗ ${e}
|
|
34
|
+
`)}catch{}}}info(e){try{this.spinner?this.spinner.info(o.chalk.blue(e)):console.log(o.chalk.blue("ℹ"),e)}catch{try{process.stdout?.write?.(`ℹ ${e}
|
|
35
|
+
`)}catch{}}}warn(e){try{this.spinner?this.spinner.warn(o.chalk.yellow(e)):console.warn(o.chalk.yellow("⚠"),e)}catch{try{process.stderr?.write?.(`⚠ ${e}
|
|
36
|
+
`)}catch{}}}handleError(e){const t=e instanceof Error?e.message:String(e);this.error(t),process.env.DEBUG&&e instanceof Error&&(console.error(o.chalk.gray("Stack trace:")),console.error(o.chalk.gray(e.stack))),process.exit(1)}}const b={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"},H={CLAUDE_CODE:"claude-code",GEMINI_CLI:"gemini-cli"},L={STARTING:"starting",IDLE:"idle",PAUSED:"paused",STOPPED:"stopped",ERROR:"error"},ft={STDOUT:"stdout",STDERR:"stderr"},O={STATUS:"daemon-status",ERROR:"daemon-error",TERMINATE:"daemon-terminate",LIST:"daemon-list-agent-sessions",START_AGENT:"daemon-start-agent",STOP_AGENT:"daemon-stop-agent"},se={STARTING:"starting",IDLE:"idle",BUSY:"busy",OFFLINE:"offline"},y={REQUEST:"request",RESPONSE:"response",ACK:"ack"},x=o.object({eventType:o.string(),command:o.string(),payload:o.object({sessionId:o.string(),timestamp:o.number().default(()=>Date.now())})}),tr=o._enum([L.STARTING,L.IDLE,L.PAUSED,L.STOPPED,L.ERROR]),nr=o._enum([H.CLAUDE_CODE,H.GEMINI_CLI]),sr=o._enum([ft.STDOUT,ft.STDERR]),vt=x.extend({eventType:o.literal(b.STATUS).default(b.STATUS),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default(""),fullscreen:o.boolean().default(!1).optional()})}),wt=x.extend({eventType:o.literal(b.RESIZE).default(b.RESIZE),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default(""),cols:o.number$1(),rows:o.number$1()})}),At=x.extend({eventType:o.literal(b.DIRECT_CONTROL).default(b.DIRECT_CONTROL),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string(),controlType:o._enum(["interrupt","cancel","eof","signal"]).default("interrupt"),metadata:o.record(o.string(),o.any()).optional()})}),je=x.extend({eventType:o.literal(b.STATUS).default(b.STATUS),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),status:tr.default(L.IDLE),agentType:nr.optional(),pid:o.number().optional(),version:o.string().optional(),capabilities:o.string().array().optional(),message:o.string().optional()})}),_t=x.extend({eventType:o.literal(b.MESSAGE_INPUT).default(b.MESSAGE_INPUT),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string$1(),messageId:o.string(),content:o.string$1(),preCommands:o.array(o.string()).optional(),metadata:o.record(o.string(),o.any()).optional()})}),ir=x.extend({eventType:o.literal(b.MESSAGE_INPUT).default(b.MESSAGE_INPUT),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string(),sessionId:o.string(),memberId:o.string().nullable().optional(),messageType:o._enum(["input","output","error","system"]),content:o.string(),contentSize:o.number().nullable(),messageTimestamp:o.string(),metadata:o.any().nullable(),createdAt:o.string(),updatedAt:o.string()})}),rr=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT).default(b.MESSAGE_OUTPUT),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default("")})}),bt=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT).default(b.MESSAGE_OUTPUT),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string(),messageId:o.string(),memberId:o.string().nullable().optional(),messageType:o._enum(["input","output","error","system"]),parts:o.array(o.unknown()).default([]),contentSize:o.number().nullable(),messageTimestamp:o.string(),stream:sr.optional(),isComplete:o.boolean().optional().default(!1),metadata:o.any().nullable(),createdAt:o.string(),updatedAt:o.string()})}),or=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT_PERMISSION_REQUESTED).default(b.MESSAGE_OUTPUT_PERMISSION_REQUESTED),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default(""),messageId:o.string(),toolName:o.string(),description:o.string(),metadata:o.record(o.string(),o.any()).optional()})}),Tt=x.extend({eventType:o.literal(b.MESSAGE_STDIN).default(b.MESSAGE_STDIN),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default("")})}),kt=x.extend({eventType:o.literal(b.MESSAGE_STDOUT).default(b.MESSAGE_STDOUT),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default("")})}),ar=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT_STARTED).default(b.MESSAGE_OUTPUT_STARTED),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string(),messageId:o.string(),memberId:o.string().nullable().optional(),messageType:o._enum(["input","output","error","system"]),parts:o.array(o.unknown()).default([]),contentSize:o.number().nullable(),messageTimestamp:o.string(),metadata:o.any().nullable(),createdAt:o.string(),updatedAt:o.string()})}),ur=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT_ENDED).default(b.MESSAGE_OUTPUT_ENDED),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string(),messageId:o.string(),memberId:o.string().nullable().optional(),messageType:o._enum(["input","output","error","system"]),parts:o.array(o.unknown()),contentSize:o.number().nullable(),messageTimestamp:o.string(),totalTokens:o.number().optional(),completionTime:o.number().optional(),metadata:o.any().nullable(),createdAt:o.string(),updatedAt:o.string()})}),cr=x.extend({eventType:o.literal(b.MESSAGE_DELETED).default(b.MESSAGE_DELETED),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string()})}),lr=x.extend({eventType:o.literal(b.ERROR).default(b.ERROR),command:o.literal(y.REQUEST).default(y.REQUEST),payload:x.shape.payload.extend({data:o.string().default("")})}),It=x.extend({eventType:o.literal(b.ERROR).default(b.ERROR),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:x.shape.payload.extend({data:o.string().default(""),error:o.object({code:o.string().default("UNKNOWN_ERROR"),message:o.string().default("An unknown error occurred"),details:o.any().optional(),stack:o.string().optional()})})}),hr=x.extend({eventType:o.literal(b.STATUS).default(b.STATUS),command:o.literal(y.ACK).default(y.ACK),payload:x.shape.payload.extend({data:o.string().default(""),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),agentSessionsSent:o.number().default(0)})}),gr=x.extend({eventType:o.literal(b.MESSAGE_INPUT).default(b.MESSAGE_INPUT),command:o.literal(y.ACK).default(y.ACK),payload:x.shape.payload.extend({data:o.string().default(""),messageId:o.string(),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),agentSessionsSent:o.number().default(0)})}),dr=x.extend({eventType:o.literal(b.MESSAGE_OUTPUT).default(b.MESSAGE_OUTPUT),command:o.literal(y.ACK).default(y.ACK),payload:x.shape.payload.extend({data:o.string().default(""),messageId:o.string(),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),agentSessionsSent:o.number().default(0)})}),fr=x.extend({eventType:o.literal(b.MESSAGE_DELETED).default(b.MESSAGE_DELETED),command:o.literal(y.ACK).default(y.ACK),payload:x.shape.payload.extend({data:o.string().default(""),id:o.string(),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),agentSessionsSent:o.number().default(0)})}),Dr=x.extend({eventType:o.literal(b.ERROR).default(b.ERROR),command:o.literal(y.ACK).default(y.ACK),payload:x.shape.payload.extend({data:o.string().default(""),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),agentSessionsSent:o.number().default(0)})});o.union([vt,wt,At,je,_t,ir,rr,bt,or,Tt,kt,ar,ur,cr,lr,It,hr,gr,dr,fr,Dr]);const R=o.object({eventType:o.string(),command:o.string(),payload:o.object({sessionId:o.string(),timestamp:o.number().default(()=>Date.now())})}),pr=o._enum([se.IDLE,se.BUSY,se.OFFLINE,se.STARTING]),xt=R.extend({eventType:o.literal(O.STATUS).default(O.STATUS),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().default("")})}),Le=R.extend({eventType:o.literal(O.STATUS).default(O.STATUS),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().default(""),status:pr.default(se.IDLE)})}),mr=R.extend({eventType:o.literal(O.ERROR).default(O.ERROR),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().default("")})}),Ot=R.extend({eventType:o.literal(O.ERROR).default(O.ERROR),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().default(""),error:o.object({code:o.string().default("UNKNOWN_ERROR"),message:o.string().default("An unknown error occurred"),details:o.any().optional()})})}),$t=R.extend({eventType:o.literal(O.TERMINATE).default(O.TERMINATE),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().optional().default("")})}),Pt=R.extend({eventType:o.literal(O.TERMINATE).default(O.TERMINATE),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().optional().default("")})}),Rt=R.extend({eventType:o.literal(O.LIST).default(O.LIST),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().optional().default("")})}),Nt=R.extend({eventType:o.literal(O.LIST).default(O.LIST),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().optional().default("")})}),Ve=R.extend({eventType:o.literal(O.START_AGENT).default(O.START_AGENT),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().default(""),agentType:o.string(),agentSessionId:o.string(),agentConfig:o.object({conversationSessionId:o.string().optional(),workingDirectory:o.string().nullable(),environment:o.record(o.string(),o.string()).optional(),args:o.string().array().optional(),commands:o.string().array().optional(),mcps:o.any().optional(),hooks:o.any().optional(),xterm:o.boolean().optional().default(!1),docker:o.boolean().optional().default(!1),dockerImage:o.string().optional(),autonomous:o.boolean().optional().default(!1),worktree:o.union([o.boolean(),o.object({branch:o.string().optional(),name:o.string().optional()})]).optional().default(!1),sessionAlias:o.string().optional(),llmConfig:o.object({provider:o.string(),model:o.string().optional(),apiKey:o.string().optional(),endpoint:o.string().optional()}).optional()}).optional()})}),Er=R.extend({eventType:o.literal(O.START_AGENT).default(O.START_AGENT),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().default(""),agentSessionId:o.string(),agentType:o.string(),status:o._enum(["started","failed"]).default("started"),message:o.string().optional()})}),Fr=R.extend({eventType:o.literal(O.START_AGENT).default(O.START_AGENT),command:o.literal(y.ACK).default(y.ACK),payload:R.shape.payload.extend({data:o.string().default(""),agentType:o.string(),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),daemonsSent:o.number().default(0)})}),Bt=R.extend({eventType:o.literal(O.STOP_AGENT).default(O.STOP_AGENT),command:o.literal(y.REQUEST).default(y.REQUEST),payload:R.shape.payload.extend({data:o.string().default(""),agentSessionId:o.string()})}),Ut=R.extend({eventType:o.literal(O.STOP_AGENT).default(O.STOP_AGENT),command:o.literal(y.RESPONSE).default(y.RESPONSE),payload:R.shape.payload.extend({data:o.string().default(""),agentSessionId:o.string(),status:o._enum(["stopped","not_found","failed"]).default("stopped"),message:o.string().optional()})}),yr=R.extend({eventType:o.literal(O.STOP_AGENT).default(O.STOP_AGENT),command:o.literal(y.ACK).default(y.ACK),payload:R.shape.payload.extend({data:o.string().default(""),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),daemonsSent:o.number().default(0)})}),Sr=R.extend({eventType:o.literal(O.TERMINATE).default(O.TERMINATE),command:o.literal(y.ACK).default(y.ACK),payload:R.shape.payload.extend({data:o.string().default(""),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),daemonsSent:o.number().default(0)})}),Cr=R.extend({eventType:o.literal(O.LIST).default(O.LIST),command:o.literal(y.ACK).default(y.ACK),payload:R.shape.payload.extend({data:o.string().default(""),status:o._enum(["forwarded","failed"]).default("forwarded"),message:o.string(),daemonsSent:o.number().default(0)})});o.union([xt,Le,mr,Ot,$t,Pt,Rt,Nt,Ve,Er,Fr,Bt,Ut,yr,Sr,Cr]);const Mt=o.z.object({VITE_INJECT_AGIFLOW_APP_ENDPOINT:o.z.string().default("").transform(n=>n.trim()||void 0).pipe(o.z.string().url().optional()).describe("Server base URL for both HTTP API and WebSocket connections (optional - leave empty for standalone mode)"),VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:o.z.string().default("").transform(n=>n.trim()||void 0).pipe(o.z.string().url().optional()).describe("Server base URL when running inside Docker containers (optional)"),VITE_AGENT_CLI_DOCKER_IMAGE:o.z.string().default("").describe("Docker image name for containerized Claude Code agents"),VITE_AGENT_CLI_DOCKER_NETWORK:o.z.string().default("").describe("Docker network mode for containerized agents"),VITE_SAVE_RAW:o.z.preprocess(n=>n==="false"||n===""||n===null||n===void 0?!1:n==="true"?!0:n,o.z.boolean().optional()).default(!1)});yt.config({override:!1,debug:!1});const J=Mt.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.6",VITE_AGENT_CLI_DOCKER_NETWORK:""});function Gt(n=!1){return process.env.AGENT_CONTAINER_MODE==="true"||n?J.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT:J.VITE_INJECT_AGIFLOW_APP_ENDPOINT}function vr(n){const e=new URL(n);return e.protocol=e.protocol==="https:"?"wss:":"ws:",e.toString()}function jt(n=!0,e){const s=te.hostname().replace(/[^a-zA-Z0-9-]/g,"-");if(n){const i=e||process.cwd(),r=Fn.createHash("sha256").update(i).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"").slice(0,8);return`claude-daemon-${s}-${r}`}return`claude-daemon-${s}-${Date.now()}`}function Lt(){return{hostname:te.hostname(),platform:te.platform(),arch:te.arch(),release:te.release(),cpus:te.cpus().length,totalMemory:te.totalmem(),type:te.type()}}function wr(n){return n.replace(/^http/,"ws")}function Wt(n,e=3e3){return n.replace(/^ws/,"http").replace(/:\d+$/,`:${e}`)}function Ht(n,e=3e5,t){let s=null;const i=t||console,r=()=>{a(),n().catch(c=>{i.warn?.("Heartbeat failed:",c)||console.warn("Heartbeat failed:",c)}),s=setInterval(async()=>{try{await n()}catch(c){i.warn?.("Heartbeat failed:",c)||console.warn("Heartbeat failed:",c)}},e)},a=()=>{s&&(clearInterval(s),s=null)};return{start:r,stop:a}}class Ar{ws=null;options;callbacks;isConnected=!1;reconnectTimer=null;shouldReconnect=!0;currentSessionId=null;credentialsService;logger;pingInterval=null;connectionAttempts=0;maxReconnectAttempts=10;heartbeatInterval=null;constructor(e,t={}){const s=o.SubEnvManager.isContainerMode?2e3:5e3;this.options={reconnectInterval:s,...e},this.callbacks=t,this.credentialsService=e.credentialsService??new o.CredentialsService,this.logger=e.logger??new o.Logger({verbose:e.verbose??!1}),o.SubEnvManager.isContainerMode&&this.logger.debug("🐳 Docker WebSocket service initialized with enhanced connectivity handling")}async connect(e){if(this.ws&&this.ws.readyState===re.OPEN)return;this.currentSessionId=e;const t=await this.buildWebSocketUrl(e);return o.SubEnvManager.isContainerMode&&(this.logger.info(`🐳 Docker WebSocket connecting to: ${t}`),this.logger.debug("Docker network environment:",{hostname:o.SubEnvManager.hostname,containerMode:o.SubEnvManager.isContainerMode,serverUrl:this.options.serverUrl})),new Promise((s,i)=>{const r={};this.options.apiKey&&(r["x-api-key"]=this.options.apiKey),this.ws=new re(t,{headers:r}),this.ws.on("open",()=>{this.isConnected=!0,this.connectionAttempts=0;const a=this.logger;a&&(o.SubEnvManager.isContainerMode?a.info(`🐳 Docker WebSocket connected successfully to ${t}`):a.info(`🔌 WebSocket connected to ${t}`)),o.SubEnvManager.isContainerMode&&this.startHealthMonitoring(),this.startAgentHeartbeat(),this.callbacks.onConnect&&this.callbacks.onConnect(),s()}),this.ws.on("message",a=>{try{const c=JSON.parse(a.toString());this.handleMessage(c)}catch(c){this.log(`Error parsing message: ${c}`)}}),this.ws.on("close",(a,c)=>{this.isConnected=!1,this.currentSessionId=null,this.callbacks.onDisconnect&&this.callbacks.onDisconnect(a,c.toString()),this.shouldReconnect&&this.scheduleReconnect(e)}),this.ws.on("error",a=>{o.SubEnvManager.isContainerMode&&this.logger.error("🐳 Docker WebSocket connection error:",new Error(`Docker WebSocket error: ${a.message}. URL: ${t}, Hostname: ${o.SubEnvManager.hostname}, Server: ${this.options.serverUrl}`)),a.message.includes("401")&&this.options.apiKey&&this.log(`API key first 8 chars: ${this.options.apiKey.substring(0,8)}...`),(a.message.includes("ECONNREFUSED")||a.message.includes("ENOTFOUND"))&&this.logger.error("🐳 Docker networking issue - check if server is accessible from container"),this.callbacks.onError&&this.callbacks.onError(a),this.isConnected||i(a)}),setTimeout(()=>{this.isConnected||i(new Error("WebSocket connection timeout"))},1e4)})}disconnect(){this.shouldReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHealthMonitoring(),this.stopAgentHeartbeat(),this.ws&&(this.ws.close(),this.ws=null),this.isConnected=!1}isWebSocketConnected(){return this.isConnected}getCurrentSessionId(){if(!this.currentSessionId)throw new Error("No active session ID");return this.currentSessionId}setCurrentSessionId(e){this.currentSessionId=e}sendAgentStatus(e){const t={eventType:b.STATUS,command:y.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:"",status:e.status||L.IDLE,agentType:e.agentType,pid:e.pid,version:e.version,capabilities:e.capabilities,message:e.message}};this.sendMessage(je.parse(t))}sendAgentOutput(e){const t=new Date().toISOString(),s={eventType:b.MESSAGE_OUTPUT,command:y.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:t,stream:e.stream,isComplete:e.isComplete||!1,metadata:e.metadata,createdAt:t,updatedAt:t}};this.sendMessage(bt.parse(s))}sendAgentError(e){const t={eventType:b.ERROR,command:y.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:"",error:{code:e.code,message:e.message,details:e.details,stack:e.stack}}};this.sendMessage(It.parse(t))}sendStdoutMessage(e){const t={eventType:b.MESSAGE_STDOUT,command:y.RESPONSE,payload:{sessionId:this.getCurrentSessionId(),timestamp:Date.now(),data:e}};this.sendMessage(kt.parse(t))}sendMessage(e){if(this.ws&&this.ws.readyState===re.OPEN)try{this.ws.send(JSON.stringify(e))}catch(t){o.SubEnvManager.isContainerMode?(this.logger.error("🐳 Docker WebSocket send error:",t),this.logger.debug("🐳 Message that failed to send:",e)):this.logger.error("WebSocket send error:",t),this.currentSessionId&&this.scheduleReconnect(this.currentSessionId)}else{const t=this.ws?this.ws.readyState:"no socket";o.SubEnvManager.isContainerMode?this.logger.warn(`🐳 Docker WebSocket not ready to send message. State: ${t}`):this.logger.warn(`WebSocket not ready to send message. State: ${t}`)}}handleMessage(e){try{switch(e.eventType){case b.STATUS:if(e.command===y.REQUEST){const t=vt.parse(e);this.callbacks.onStatusRequest&&this.callbacks.onStatusRequest(t)}break;case b.MESSAGE_INPUT:if(e.command===y.REQUEST){const t=_t.parse(e);this.callbacks.onMessageInput&&this.callbacks.onMessageInput(t)}break;case b.MESSAGE_STDIN:if(e.command===y.REQUEST){const t=Tt.parse(e);this.callbacks.onStdinInput&&this.callbacks.onStdinInput(t)}break;case b.RESIZE:if(e.command===y.REQUEST){const t=wt.parse(e),s=this.logger;s&&s.info(`📐 Received resize event: ${t.payload.cols}x${t.payload.rows}`),this.callbacks.onResizeRequest?this.callbacks.onResizeRequest(t):s&&s.warn("📐 No onResizeRequest callback registered, ignoring resize event")}break;case b.DIRECT_CONTROL:if(e.command===y.REQUEST){const t=At.parse(e),s=this.logger;s&&s.info(`🎮 Received direct control event: ${t.payload.controlType} - data: ${JSON.stringify(t.payload.data)}`),this.callbacks.onDirectControl?this.callbacks.onDirectControl(t):s&&s.warn("🎮 No onDirectControl callback registered, ignoring direct control event")}break;default:this.callbacks.onMessage&&this.callbacks.onMessage(e)}}catch(t){this.log(`Error validating message: ${t}`)}}scheduleReconnect(e){if(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.connectionAttempts++,this.connectionAttempts>this.maxReconnectAttempts){o.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 t=this.options.reconnectInterval||2e3,s=o.SubEnvManager.isContainerMode?Math.min(this.connectionAttempts,5):1,i=t*s;o.SubEnvManager.isContainerMode&&this.logger.info(`🐳 Docker WebSocket reconnection attempt ${this.connectionAttempts}/${this.maxReconnectAttempts} in ${i}ms`),this.reconnectTimer=setTimeout(async()=>{try{await this.connect(e)}catch(r){const a=r instanceof Error?r.message:String(r);o.SubEnvManager.isContainerMode?this.logger.error(`🐳 Docker WebSocket reconnection failed: ${a}`):this.log(`Reconnection failed: ${a}`),this.scheduleReconnect(e)}},i)}async buildWebSocketUrl(e){const t=new URL(this.options.serverUrl);t.protocol==="http:"?t.protocol="ws:":t.protocol==="https:"&&(t.protocol="wss:"),t.pathname=`/api/v1/organizations/${this.options.organizationId}/agent-sessions/${e}/ws`,t.searchParams.set("clientType","agent");const s=await this.credentialsService.getDeviceId();return t.searchParams.set("deviceId",s||"unknown"),t.toString()}startHealthMonitoring(){this.pingInterval&&clearInterval(this.pingInterval),this.pingInterval=setInterval(()=>{this.ws&&this.ws.readyState===re.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:b.STATUS,command:y.RESPONSE,payload:{sessionId:this.currentSessionId,timestamp:Date.now(),data:"",status:L.IDLE,message:"Heartbeat"}},t=je.parse(e);this.sendMessage(t),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 _r{session;logger;constructor(e){this.logger=e??new o.Logger({verbose:!1})}spawn(e,t){const s=e.agentSessionId||mt.ulid(),i=e.workingDir||process.cwd(),r={};e.agentApiKey&&(r[o.ENV_KEYS.AGENT_API_KEY]=e.agentApiKey),e.agentOrganizationId&&(r[o.ENV_KEYS.AGENT_ORGANIZATION_ID]=e.agentOrganizationId),e.agentDeviceGuid&&(r[o.ENV_KEYS.AGENT_DEVICE_GUID]=e.agentDeviceGuid),e.agentServerUrl&&(r[o.ENV_KEYS.AGENT_SERVER_URL]=e.agentServerUrl),e.agentType&&(r[o.ENV_KEYS.AGENT_TYPE]=e.agentType),r[o.ENV_KEYS.AGENT_SESSION_ID]=s,this.logger.debug("PTY Environment Variables:",{...process.env,...r,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"});const a=En.spawn(e.command,e.args||[],{name:"xterm-256color",cwd:i,env:{...process.env,...r,...e.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),c={id:s,ptyProcess:a,command:e.command,workingDir:i,status:"running",createdAt:new Date,lastActivity:new Date,logStream:e.logStream};return a.onData(h=>{c.lastActivity=new Date,c.logStream&&c.logStream.write(h),process.stdout.isTTY&&process.stdout.write(h),t?.onData&&t.onData(h,h)}),a.onExit(h=>{const f=h.exitCode,p=h.signal;c.status=f===0?"stopped":"error",c.lastActivity=new Date,this.logger.info(`PTY process ${s} exited with code ${f}${p?` (signal: ${p})`:""}`),c.logStream&&c.logStream.end(),t?.onExit&&t.onExit(f,p)}),this.session=c,c}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,t){return this.session?.ptyProcess?(this.session.ptyProcess.resize(e,t),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(t){return this.logger.error(`Failed to kill PTY session : ${t}`),!1}}getSession(){return this.session}isSessionRunning(){return this.session?.status==="running"}}class We{logger;targetDirectory;originalDirectory;envFilePatterns=[".env",".env.development",".dev.vars",".env.test"];constructor(e){if(this.targetDirectory=F.resolve(e.targetDirectory),this.originalDirectory=e.originalDirectory?F.resolve(e.originalDirectory):void 0,this.logger=e.logger??new o.Logger({verbose:!1}),!C.existsSync(this.targetDirectory))throw new Error(`Target directory does not exist: ${this.targetDirectory}`);if(this.originalDirectory&&!C.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(t=>t.copied).length} environment files`))}catch(t){const s=`Setup failed: ${t.message}`;e.errors.push(s),this.logger.error(s)}return e}async copyEnvironmentFiles(){if(!this.originalDirectory)return[];const e=[],t=await this.findEnvironmentFiles(this.originalDirectory);for(const s of t)try{const i=F.relative(this.originalDirectory,s),r=F.join(this.targetDirectory,i),a=F.dirname(r);C.existsSync(a)||await ne.mkdir(a,{recursive:!0}),await ne.copyFile(s,r),e.push({originalPath:s,targetPath:r,relativePath:i,copied:!0}),this.logger.debug(`Copied: ${i}`)}catch(i){e.push({originalPath:s,targetPath:"",relativePath:F.relative(this.originalDirectory,s),copied:!1}),this.logger.warn(`Failed to copy ${s}: ${i.message}`)}return e}async findEnvironmentFiles(e,t=0){const s=[];if(t>=5)return s;try{const r=await ne.readdir(e,{withFileTypes:!0});for(const a of r){const c=F.join(e,a.name);if(a.isDirectory()){if(this.shouldSkipDirectory(a.name))continue;const h=await this.findEnvironmentFiles(c,t+1);s.push(...h)}else a.isFile()&&this.isEnvironmentFile(a.name)&&s.push(c)}}catch(r){this.logger.debug(`Cannot read directory ${e}: ${r.message}`)}return s}isEnvironmentFile(e){return this.envFilePatterns.some(t=>t.includes("*")?!1:e===t||e.startsWith(t+"."))}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 t=F.join(this.targetDirectory,"package.json");if(!C.existsSync(t))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 s=this.getInstallCommand(e);this.logger.info(`Running: ${s}`);try{return z.execSync(s,{cwd:this.targetDirectory,stdio:"pipe",encoding:"utf8"}),!0}catch(i){if(i.message?.includes("EUNSUPPORTEDPROTOCOL")||i.message?.includes("workspace:"))return this.logger.warn("Workspace protocol detected in dependencies, skipping installation"),this.logger.debug("This is expected in Docker containers where dependencies are pre-installed"),!1;throw i}}catch(t){return this.logger.error(`Failed to install dependencies: ${t.message}`),!1}}isPackageManagerAvailable(e){try{return z.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 C.existsSync(F.join(this.targetDirectory,"package.json"))}isNodeProject(){return["package.json","node_modules","yarn.lock","package-lock.json","pnpm-lock.yaml"].some(t=>C.existsSync(F.join(this.targetDirectory,t)))}isPythonProject(){return["requirements.txt","pyproject.toml","setup.py","Pipfile","poetry.lock","uv.lock"].some(t=>C.existsSync(F.join(this.targetDirectory,t)))}isNxMonorepo(){return["nx.json","workspace.json","angular.json"].some(t=>C.existsSync(F.join(this.targetDirectory,t)))}getDefaultPreAgentHooks(e){if(e&&e.length>0)return this.logger.debug("User provided pre-agent hooks, skipping defaults"),e;const t=[];return this.isNodeProject()&&!C.existsSync(F.join(this.targetDirectory,"node_modules"))&&this.hasPackageJson()&&(this.logger.info("No node_modules found, adding default pnpm install hook"),t.push("pnpm install"),this.isNxMonorepo()&&(this.logger.info("Nx monorepo detected, adding default build hook"),t.push("nx run-many -t build"))),this.isPythonProject()&&(C.existsSync(F.join(this.targetDirectory,".venv"))||C.existsSync(F.join(this.targetDirectory,"venv"))||(this.logger.info("No virtual environment found, adding default Python setup hooks"),C.existsSync(F.join(this.targetDirectory,"uv.lock"))?t.push("uv sync"):C.existsSync(F.join(this.targetDirectory,"requirements.txt"))&&(t.push("python -m venv .venv"),t.push(".venv/bin/pip install -r requirements.txt")))),t}async preAgentSetup(e){const t={hooks:[]};if(this.originalDirectory){const s=await this.setup();t.envFilesCopied=s.envFilesCopied,t.errors=s.errors}return t.hooks=this.getDefaultPreAgentHooks(e),t}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 z.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 z.execSync("nx --version",{stdio:"pipe",timeout:5e3}),!0}catch{try{return z.execSync("npx nx --version",{stdio:"pipe",timeout:1e4}),!0}catch{return!1}}}}class Vt{logger;onData;onExit;ctrlCCount=0;ctrlCTimeout=null;CTRL_C_RESET_MS=3e3;constructor({logger:e,onData:t,onExit:s}){this.logger=e??new o.Logger({verbose:!1}),this.onData=t,this.onExit=s,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(a=>a.charCodeAt(0)).join(",")})`),e.length===1&&e.charCodeAt(0)>=32&&e.charCodeAt(0)<=126?this.logger.debug("Normal typing character detected"):e==="\r"||e===`
|
|
37
|
+
`||e===`\r
|
|
38
|
+
`?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(t){this.logger.error("Error handling stdin data:",t)}}),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 De extends gn.EventEmitter{logger;isShuttingDown=!1;activeTerminations=new Map;callbacks={};constructor(e){super(),this.logger=e??new o.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 t={agentSessionId:e,reason:"agent_sigint",signal:"SIGINT"},s=this.activeTerminations.get(e);if(s)return this.logger.debug(`Termination already in progress for agent ${e}`),s;const i=this.performAgentSigintTermination(t);this.activeTerminations.set(e,i);try{await i}finally{this.activeTerminations.delete(e)}}async performAgentSigintTermination(e){try{this.emit("agent:sigint",e),this.callbacks.onAgentSigint&&await this.callbacks.onAgentSigint(e),this.emit("agent:cleanup",e),this.callbacks.onAgentTerminated&&await this.callbacks.onAgentTerminated(e)}catch(t){throw this.logger.error(`Error handling agent SIGINT: ${t}`),t}}async handlePtyTermination(e){const{agentSessionId:t,exitCode:s,signal:i}=e;this.logger.info(`PTY terminated naturally for session agent ${t}. Exit code: ${s}, Signal: ${i}`);const r=this.activeTerminations.get(t);if(r)return this.logger.debug(`Termination already in progress for agent ${t}`),r;const a=this.performPtyTermination(e);this.activeTerminations.set(t,a);try{await a}finally{this.activeTerminations.delete(t)}}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(t){throw this.logger.error(`Error handling PTY termination: ${t}`),t}}async terminateAgent(e,t={}){const{force:s=!1,timeout:i=5e3}=t;this.logger.info(`Terminating agent ${e} for session force: ${s}`);const r={agentSessionId:e,reason:"user_requested"},a=this.activeTerminations.get(e);if(a)return this.logger.debug(`Termination already in progress for agent ${e}`),a;const c=this.performAgentTermination(r,{force:s,timeout:i});this.activeTerminations.set(e,c);try{await c}finally{this.activeTerminations.delete(e)}}async performAgentTermination(e,t){const{force:s,timeout:i}=t;try{this.emit("agent:terminating",e);const r=new Promise((c,h)=>{setTimeout(()=>h(new Error(`Termination timeout for agent ${e.agentSessionId}`)),i)}),a=new Promise(c=>{const h=f=>{f.agentSessionId===e.agentSessionId&&(this.off("agent:terminated",h),c())};this.on("agent:terminated",h)});try{await Promise.race([a,r]),this.logger.info(`Agent ${e.agentSessionId} terminated gracefully`)}catch(c){if(s)this.logger.warn(`Forcefully terminating agent ${e.agentSessionId} after timeout`),this.emit("agent:force-terminate",e);else throw c}this.callbacks.onAgentTerminated&&await this.callbacks.onAgentTerminated(e)}catch(r){throw this.logger.error(`Error terminating agent: ${r}`),r}}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 t=e.map(s=>this.terminateAgent(s,{force:!0,timeout:3e3}).catch(i=>{this.logger.error(`Failed to terminate agent ${s}: ${i}`)}));await Promise.allSettled(t),this.logger.info("All agents terminated, daemon can now exit"),this.emit("daemon:shutdown-complete")}catch(t){throw this.logger.error(`Error during daemon shutdown: ${t}`),t}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 Kt{agentType;serverUrl;apiUrl;apiKey;verbose;organizationId;standalone;logger;credentialsService;terminationService;onFullscreenChange;wsService;httpService;ptyRunner;agentInfo=null;ptySessionId=null;xtermEnabled=!1;stdinForwarding=null;isFullscreen=!1;stdoutBuffer="";stdoutThrottleTimer=null;lastStdoutSent=0;STDOUT_THROTTLE_MS=500;STDOUT_BUFFER_LIMIT=64*1024;backgroundOutputBuffer=[];BACKGROUND_BUFFER_SIZE=10;BACKGROUND_CHUNK_MAX_SIZE=2048;constructor(e){if(this.agentType=e.agentType,this.serverUrl=e.serverUrl,this.apiUrl=e.apiUrl,this.apiKey=e.apiKey,this.verbose=e.verbose??!1,this.organizationId=e.organizationId,this.standalone=e.standalone??!1,this.logger=e.logger??new o.Logger({verbose:this.verbose}),this.credentialsService=e.credentialsService??new o.CredentialsService,this.terminationService=e.terminationService??new De(this.logger),this.onFullscreenChange=e.onFullscreenChange,this.ptyRunner=new _r(this.logger),e.serverUrl){const i={serverUrl:e.serverUrl,apiKey:e.apiKey,verbose:e.verbose,organizationId:e.organizationId,credentialsService:this.credentialsService,logger:this.logger},r={onStatusRequest:a=>this.handleStatusRequest(a),onMessageInput:a=>this.handleMessageInput(a),onStdinInput:a=>this.handleStdinInput(a),onResizeRequest:a=>this.handleResizeRequest(a),onDirectControl:a=>this.handleDirectControl(a),onConnect:()=>this.onWebSocketConnect(),onDisconnect:(a,c)=>this.onWebSocketDisconnect(a,c),onError:a=>this.onWebSocketError(a)};this.wsService=new Ar(i,r),this.logger.debug("WebSocket service initialized")}else this.logger.info("Running in standalone mode without WebSocket connection");const t=Gt(),s=this.apiUrl||t||e.serverUrl;s?(this.httpService=new o.AgentHttpService({apiUrl:s,organizationId:this.organizationId,apiKey:this.apiKey,logger:this.logger}),this.logger.debug("HTTP service initialized")):this.logger.info("HTTP service not initialized - no API URL provided"),this.standalone&&this.initializeStdinForwarding()}initializeStdinForwarding(){this.stdinForwarding=new Vt({logger:this.logger,onData:e=>{this.logger.debug(`StdinForwarding received data: ${JSON.stringify(e)}`),this.sendInputToPty(e)},onExit:e=>{this.logger.info(`StdinForwarding received exit signal: ${e}`),this.disconnect(),process.exit(0)}})}async connectToSession(e){if(this.logger.info(`connectToSession called with sessionId: ${e}`),this.logger.info(`wsService exists: ${!!this.wsService}`),this.logger.info(`serverUrl: ${this.serverUrl||"undefined"}`),!this.wsService){this.logger.info("WebSocket service not available - skipping connection");return}this.logger.info("Attempting to connect to WebSocket..."),await this.wsService.connect(e),this.wsService.sendAgentStatus({agentType:this.agentType,status:L.IDLE,message:`${this.agentType} agent connected`})}disconnect(){if(this.standalone&&this.stdinForwarding)try{this.stdinForwarding.restore(),this.stdinForwarding=null}catch(e){this.logger.error("Error restoring stdin forwarding:",e)}this.flushStdoutBuffer(),this.stdoutThrottleTimer&&(clearTimeout(this.stdoutThrottleTimer),this.stdoutThrottleTimer=null),this.ptySessionId&&(this.logger.info(`Terminating PTY session: ${this.ptySessionId}`),this.ptyRunner.kill(),this.ptySessionId=null),this.wsService&&this.wsService.disconnect(),this.agentInfo=null}onWebSocketConnect(){this.logger.debug(`WebSocket connected for ${this.agentType} agent`)}onWebSocketDisconnect(e,t){this.logger.debug(`WebSocket disconnected for ${this.agentType} agent (${e}): ${t}`)}onWebSocketError(e){this.logger.error(`WebSocket error for ${this.agentType} agent: ${e?.message||"Unknown error"}`),this.logger.error(`Error stack: ${e?.stack||"No stack trace"}`)}async handleStatusRequest(e){if(this.logger.debug(`Handling status request for session: ${e.payload.sessionId}`),!this.wsService){this.logger.debug("WebSocket service not available - cannot handle status request");return}try{try{this.wsService.getCurrentSessionId()!==e.payload.sessionId&&(this.wsService.setCurrentSessionId(e.payload.sessionId),this.logger.debug(`Set current session ID to: ${e.payload.sessionId}`))}catch{this.wsService.setCurrentSessionId(e.payload.sessionId),this.logger.debug(`Set current session ID to: ${e.payload.sessionId}`)}let t=L.IDLE,s=`${this.agentType} agent is idle`;this.agentInfo&&this.agentInfo.agentSessionId===e.payload.sessionId?(t=this.agentInfo.status,t===L.IDLE?s=`${this.agentType} agent is running`:t===L.STARTING?s=`${this.agentType} agent is starting`:t===L.ERROR?s=`${this.agentType} agent encountered an error`:t===L.STOPPED&&(s=`${this.agentType} agent is stopped`)):(this.logger.debug(`No active agent process for session ${e.payload.sessionId}, but daemon is ready`),s=`${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:t,message:s,pid:this.agentInfo?.process?.pid||process.pid,version:await this.getVersion()||void 0,capabilities:["chat","code-editing","file-operations"]})}catch(t){this.wsService.sendAgentError({code:"STATUS_FAILED",message:`Status request failed: ${t.message}`,details:{error:t.toString()}})}}async handleMessageInput(e){this.logger.debug(`Handling message input: ${e.payload.content}`);const t=e.payload.content;if(e.payload.preCommands&&Array.isArray(e.payload.preCommands)){this.logger.info(`[PreCommands] Executing ${e.payload.preCommands.length} pre-commands`);for(const s of e.payload.preCommands)this.sendInputToPty(s),await new Promise(i=>setTimeout(i,350));await new Promise(s=>setTimeout(s,100))}if(!t||t.length===0){this.logger.info("[Content] Content is empty, skipping input");return}if(this.sendInputToPty("\x1B[I"),this.agentType.toLowerCase().includes(H.GEMINI_CLI)){this.logger.debug("Gemini agent detected - pasting content with newline");for(const i of[" "," "])await new Promise(r=>{setTimeout(()=>{this.sendInputToPty(i),r(null)},150)});await new Promise(i=>{setTimeout(()=>{this.sendInputToPty(`${t}
|
|
39
|
+
`),i(null)},150)}),await new Promise(i=>{setTimeout(()=>{this.sendInputToPty("\r"),i(null)},150)})}else this.sendInputToPty(t),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(t){this.logger.error(`Failed to send direct control signal to PTY: ${t}`)}}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 s=Date.now()-this.lastStdoutSent;if(s>=this.STDOUT_THROTTLE_MS)this.flushStdoutBuffer();else if(!this.stdoutThrottleTimer){const i=this.STDOUT_THROTTLE_MS-s;this.stdoutThrottleTimer=setTimeout(()=>{this.flushStdoutBuffer()},i)}}flushStdoutBuffer(){if(!(!this.stdoutBuffer||!this.wsService))try{this.wsService.sendStdoutMessage(this.stdoutBuffer),this.lastStdoutSent=Date.now(),this.logger.debug(`📤 Stdout buffer flushed: ${this.stdoutBuffer.length} chars`),this.stdoutBuffer="",this.stdoutThrottleTimer&&(clearTimeout(this.stdoutThrottleTimer),this.stdoutThrottleTimer=null)}catch(e){this.logger.error("Failed to send stdout event:",e)}}addToBackgroundBuffer(e){const t=e.length>this.BACKGROUND_CHUNK_MAX_SIZE?e.substring(e.length-this.BACKGROUND_CHUNK_MAX_SIZE):e;this.backgroundOutputBuffer.push(t),this.backgroundOutputBuffer.length>this.BACKGROUND_BUFFER_SIZE&&this.backgroundOutputBuffer.shift(),this.logger.debug(`📦 Added ${t.length} chars to background buffer (${this.backgroundOutputBuffer.length}/${this.BACKGROUND_BUFFER_SIZE} chunks)`)}sendBackgroundBuffer(){if(this.backgroundOutputBuffer.length===0||!this.wsService)return;this.logger.debug(`📤 Sending background buffer: ${this.backgroundOutputBuffer.length} chunks`);const e=this.backgroundOutputBuffer.join("");if(e)try{this.wsService.sendStdoutMessage(e),this.logger.debug(`📤 Background buffer sent: ${e.length} chars`)}catch(t){this.logger.error("Failed to send background buffer:",t)}}setXtermEnabled(e){this.xtermEnabled=e,this.logger.debug(`Xterm functionality ${e?"enabled":"disabled"}`)}setFullscreen(e,t=!1){const s=this.isFullscreen;this.isFullscreen=e,this.logger.debug(`Agent fullscreen mode ${e?"enabled":"disabled"}`),e&&!s&&this.xtermEnabled&&this.agentInfo&&this.sendBackgroundBuffer(),!t&&s!==e&&this.agentInfo&&this.onFullscreenChange&&this.onFullscreenChange(this.agentInfo.agentSessionId,e)}getFullscreen(){return this.isFullscreen}sendAgentStatus(e){this.wsService&&this.wsService.sendAgentStatus(e)}sendAgentOutput(e){this.wsService&&this.wsService.sendAgentOutput(e)}sendAgentError(e){this.wsService&&this.wsService.sendAgentError(e)}getAgentInfo(){return this.agentInfo}sendInputToPty(e){this.ptyRunner.sendInput(e)}setAgentInfo(e){if(this.agentInfo=e,e.agentSessionId&&this.wsService)try{this.wsService.setCurrentSessionId(e.agentSessionId)}catch{}}getAgentEnvironmentVariables(){const e={};for(const[t,s]of Object.entries(process.env))s!==void 0&&(e[t]=s);return this.apiKey&&(e[o.ENV_KEYS.AGENT_API_KEY]=this.apiKey),this.organizationId&&(e[o.ENV_KEYS.AGENT_ORGANIZATION_ID]=this.organizationId),this.serverUrl&&(e[o.ENV_KEYS.AGENT_SERVER_URL]=this.serverUrl),e[o.ENV_KEYS.AGENT_TYPE]=this.agentType,e[o.ENV_KEYS.VERBOSE]=this.verbose?"true":"false",e}configureNodeOptions(e){let t=null;const s=F.join(__dirname,"networkLog.js"),i=F.join(__dirname,"networkLog.ts"),r=F.join(__dirname,"..","networkLog.js"),a=F.join(__dirname,"..","networkLog.ts");C.existsSync(s)?t=s:C.existsSync(i)?t=i:C.existsSync(r)?t=r:C.existsSync(a)&&(t=a);let h=e["NODE_OPTIONS"]||"";return this.logger.debug("Network logging hook configuration:",{sameDirJs:s,sameDirTs:i,parentDirJs:r,parentDirTs:a,foundPath:t,existingNodeOptions:h,alreadyIncludes:h.includes("networkLog")}),t&&!h.includes("networkLog")?(h=`${h} --require ${t}`.trim(),this.logger.debug(`Network logging hook added to NODE_OPTIONS: ${t}`)):t?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: ${h}`),h}async sendInputToAgent(e){this.ptyRunner.sendInput(e)||this.logger.warn("Failed to send input to PTY session")}resizePty(e,t){this.ptyRunner.resize(e,t)}async executePreAgentStartHooks(e,t,s){const r=new We({targetDirectory:t,logger:this.logger}).getDefaultPreAgentHooks(e);if(!r||r.length===0){this.logger.debug("No pre-agent start hooks to execute");return}this.logger.info(`Executing ${r.length} pre-agent start hook(s) in ${t}`);const a=[];for(let c=0;c<r.length;c++){const h=r[c];this.logger.info(`[${c+1}/${r.length}] Executing hook: ${h}`);let f;if(s&&this.httpService)try{f=(await this.httpService.startMessage(s,{messageType:"output",metadata:{hookIndex:c+1,totalHooks:r.length,command:h,status:"running"}})).id}catch(p){this.logger.debug("Failed to start hook message:",p)}try{const{spawn:p}=await import("child_process"),E=await new Promise(m=>{const v=p(h,{cwd:t,shell:!0,stdio:["pipe","pipe","pipe"]});let _="",u="";v.stdout?.on("data",l=>{const g=l.toString();_+=g,this.logger.debug(`[Hook stdout] ${g.trim()}`)}),v.stderr?.on("data",l=>{const g=l.toString();u+=g,this.logger.warn(`[Hook stderr] ${g.trim()}`)}),v.on("close",l=>{if(l===0)this.logger.success(`Hook completed successfully: ${h}`),_.trim()&&this.logger.debug(`Hook stdout: ${_.trim()}`),m({success:!0,stdout:_.trim()});else{this.logger.error(`Hook failed with exit code ${l}: ${h}`),_.trim()&&this.logger.error(`Hook stdout (full output): ${_.trim()}`),u.trim()&&this.logger.error(`Hook stderr (full error): ${u.trim()}`);const g=[];u.trim()&&g.push(`stderr: ${u.trim()}`),_.trim()&&g.push(`stdout: ${_.trim()}`);const d=g.length>0?`Hook failed with exit code ${l}. ${g.join(" | ")}`:`Hook failed with exit code ${l}`;m({success:!1,error:d,stderr:u.trim()||_.trim()||void 0})}}),v.on("error",l=>{this.logger.error(`Hook execution error: ${h}`,l),m({success:!1,error:l.message})})});if(s&&f&&this.httpService)try{const m=E.success?"completed":"failed",v=E.success?`✅ Hook completed: ${h}`:`❌ Hook failed: ${h}
|
|
40
|
+
${E.error}`;await this.httpService.updateMessage(s,f,{parts:[{type:"text",text:v}],metadata:{hookIndex:c+1,totalHooks:r.length,command:h,status:m,exitCode:E.success?0:1,stdout:E.stdout,stderr:E.stderr,error:E.error}})}catch(m){this.logger.debug("Failed to update hook message:",m)}E.success||a.push({hook:h,error:E.error||"Unknown error",stderr:E.stderr})}catch(p){const E=p instanceof Error?p.message:String(p);if(this.logger.error(`Failed to execute hook: ${h}`,p instanceof Error?p:new Error(E)),s&&f&&this.httpService)try{await this.httpService.updateMessage(s,f,{parts:[{type:"text",text:`❌ Hook execution failed: ${h}
|
|
41
|
+
Error: ${E}`}],metadata:{hookIndex:c+1,totalHooks:r.length,command:h,status:"failed",error:E}})}catch(m){this.logger.debug("Failed to update hook message with error:",m)}a.push({hook:h,error:E})}}if(a.length>0){s&&await this.reportHookFailuresToTask(s,a);const c=a[0];throw new Error(`Pre-agent hook(s) failed. First failure: ${c.hook} - ${c.error}`)}this.logger.success("All pre-agent start hooks completed successfully")}async reportHookFailuresToTask(e,t){if(!this.httpService){this.logger.debug("HTTP service not available - cannot report hook failures to task");return}try{const i=`⚠️ **Pre-agent start hook(s) failed**
|
|
42
|
+
|
|
43
|
+
${t.map(r=>{let a=`• **Command**: \`${r.hook}\`
|
|
44
|
+
**Error**: ${r.error}`;return r.stderr&&(a+=`
|
|
45
|
+
**Output**: \`\`\`
|
|
46
|
+
${r.stderr}
|
|
47
|
+
\`\`\``),a}).join(`
|
|
48
|
+
|
|
49
|
+
`)}
|
|
50
|
+
|
|
51
|
+
**Suggestion**: Please check the hook commands and ensure all dependencies are installed correctly.`;await this.httpService.createTaskComment(e,i,void 0,{type:"hook_failure",failedHooks:t}),this.logger.info("Hook failure reported to task")}catch(s){this.logger.warn("Failed to report hook errors to task:",s)}}async setupDockerRepository(e){const t=e.payload?.agentConfig;if(!(t?.docker===!0)){this.logger.debug("Not using Docker, skipping repository setup");return}const i=t?.workingDirectory||this.agentInfo?.workingDir;if(!i){this.logger.warn("No working directory specified for Docker repository setup");return}try{this.logger.info("Setting up Docker repository with environment files...");const r=process.cwd(),c=await new We({targetDirectory:i,originalDirectory:r,logger:this.logger}).setup();if(c.envFilesCopied.length>0){const p=c.envFilesCopied.filter(E=>E.copied).length;this.logger.success(`Copied ${p} environment files to Docker container`)}c.errors.length>0&&(this.logger.warn(`Docker repository setup completed with ${c.errors.length} errors`),c.errors.forEach(p=>this.logger.debug(`Setup error: ${p}`)));const h=t?.agentSessionId||this.agentInfo?.agentSessionId,f=t?.hooks?.preAgentStartHooks||t?.hooks?.preAgentStart;await this.executePreAgentStartHooks(f,i,h)}catch(r){this.logger.error(`Failed to setup Docker repository: ${r}`)}}setupInitialPtySize(){try{const e=process.stdout.columns||80,t=process.stdout.rows||24;this.resizePty(e,t),this.logger.info(`🖥️ PTY resized to fit terminal: ${e}x${t}`)}catch(e){this.logger.warn("Failed to detect terminal size, using defaults:",e),this.resizePty(80,24)}}}class zt extends Kt{claudePath;claudeArgs=[];agentInputReady=!1;startupCommands=[];startupCommandsExecuted=!1;tempMcpConfigPath=null;tempProjectMcpConfigPath=null;tempSettingsPath=null;claudeVersion=null;supportsSettingsFlag=!1;ctrlCCount=0;ctrlCTimeout=null;CTRL_C_RESET_MS=2e3;complexInputDetected=!1;KEYBOARD_WHITELIST=new Set(["\r",`
|
|
52
|
+
`,"\x1B[A","\x1B[B","\x1B[C","\x1B[D"," ","","",""]);constructor(e){super({...e,agentType:H.CLAUDE_CODE}),this.claudePath=e.claudePath||"claude"}detectClaudeType(){const{execSync:e}=require("child_process");try{const t=e(`which ${this.claudePath}`,{encoding:"utf-8"}).trim();try{const s=e(`file "${t}"`,{encoding:"utf-8"});if(s.includes("Mach-O")||s.includes("executable"))return this.logger.info(`Detected standalone binary at ${t}`),this.logger.info("Using npx @anthropic-ai/claude-code instead to enable hooks"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}catch{}try{const s=C.readFileSync(t,"utf-8");if(s.startsWith("#!/usr/bin/env node")||s.includes("npx"))return this.logger.info(`Detected npm package script at ${t}`),{command:this.claudePath,args:[]}}catch{}return this.logger.info("Using npx @anthropic-ai/claude-code to enable hooks"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}catch{return this.logger.info("Claude binary not found, using npx @anthropic-ai/claude-code"),{command:"npx",args:["-y","@anthropic-ai/claude-code"]}}}isSimpleKeyboardInput(e){return!!(this.KEYBOARD_WHITELIST.has(e)||/^[0-9]/.test(e)||e.startsWith("\x1B"))}detectComplexInputPattern(e){const t=le(e);return[/select|choose|pick/i,/\[[ x]\]\s+.*\s+\[[ x]\]/i,/>\s*\[\s*\]/i,/\(\s*\)\s*\[\s*\]/i,/press.*to/i,/enter.*select/i,/use.*arrows/i,/space.*to.*select/i].some(i=>i.test(t))}async handleComplexInputEscape(){this.complexInputDetected&&(this.logger.debug("Complex input detected, sending ESC to exit..."),await this.sendInputToAgent("\x1B"),this.complexInputDetected=!1,await new Promise(e=>setTimeout(e,100)))}verifyAgentReady(e){if(this.detectComplexInputPattern(e)&&!this.complexInputDetected&&(this.complexInputDetected=!0,this.logger.debug("Complex input pattern detected in Claude Code output")),this.agentInputReady)return;const s=le(e);[/Type (your )?(message|prompt)/i,/Enter (your )?(message|prompt)/i,/Press Enter to send/i,/╭[\s\S]*?╰/m,/┌[\s\S]*?└/m].some(a=>a.test(s))&&(this.agentInputReady=!0,this.sendAgentStatus({agentType:H.CLAUDE_CODE,status:L.IDLE,message:"Agent input box detected. Ready for commands."}),this.sendSessionReadyStatus(),this.executeStartupCommands())}async sendSessionReadyStatus(){if(!(!this.agentInfo||!this.httpService))try{await this.httpService.sendAgentSessionReady(this.agentInfo.agentSessionId),this.logger.info("Session ready status sent to backend")}catch(e){this.logger.warn("Failed to send session ready status",e)}}async handleMessageInput(e){const t=e.payload.content,s=this.isSimpleKeyboardInput(t);this.complexInputDetected&&!s&&await this.handleComplexInputEscape(),await super.handleMessageInput(e)}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(t=>setTimeout(t,250))}catch(t){this.logger.warn(`Failed executing startup command: ${e}`,t)}}}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}isSameMcpCommand(e,t){if(!e.command||!t.command||e.command!==t.command)return!1;const s=e.args||[],i=t.args||[];return s.length!==i.length?!1:s.every((r,a)=>r===i[a])}mergeProjectMcpConfig(e,t){try{if(!C.existsSync(e))return null;const s=C.readFileSync(e,"utf-8"),i=JSON.parse(s);if(!i.mcpServers||typeof i.mcpServers!="object")return null;const r={};if(Array.isArray(t))for(const h of t){if(!h||typeof h!="object")continue;const f=h.name||h.id||h.key;f&&(r[f]={type:h.type||"stdio",command:h.command,args:h.args||h.arguments||[],url:h.url,env:h.env||{},disabled:h.disabled??!1,headers:h.headers||{}})}else if(typeof t=="object"&&t)for(const[h,f]of Object.entries(t))f&&typeof f=="object"&&(r[h]={...f,headers:f.headers||{}});const a={},c=[];for(const[h,f]of Object.entries(i.mcpServers)){if(!f||typeof f!="object")continue;const p=h in r,E=Object.values(r).some(m=>this.isSameMcpCommand(f,m));if(p||E){c.push(h);const m=p?"duplicate name":"duplicate command/args";this.logger.info(`Removed duplicate MCP server '${h}' from project config (${m})`)}else a[h]=f}return c.length>0&&this.logger.info(`Removed ${c.length} duplicate MCP server(s): ${c.join(", ")}`),Object.keys(a).length>0?a:null}catch(s){return this.logger.warn("Failed to merge project MCP config",s),null}}writeProjectMcpConfigFile(e,t,s){try{const i=this.mergeProjectMcpConfig(e,t);if(!i)return null;const r={mcpServers:i},a=`claude-project-mcps-${s}.json`,c=F.join(q.tmpdir(),a);return C.writeFileSync(c,JSON.stringify(r,null,2),"utf8"),this.logger.info(`Created temporary project MCP config at ${c}`),c}catch(i){return this.logger.warn("Failed to write project MCP config file",i),null}}writeMcpConfigFile(e,t){if(!e)return null;try{const s={};if(Array.isArray(e))for(const c of e){if(!c||typeof c!="object")continue;const h=c.name||c.id||c.key;h&&(s[h]={type:c.type||"stdio",command:c.command,args:c.args||c.arguments||[],url:c.url,env:c.env||{},disabled:c.disabled??!1,headers:c.headers||{}})}else if(typeof e=="object")for(const[c,h]of Object.entries(e))h&&typeof h=="object"&&(s[c]={...h,headers:h.headers||{}});if(Object.keys(s).length===0)return null;const i={mcpServers:s},r=`claude-mcps-${t}.json`,a=F.join(q.tmpdir(),r);return C.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),this.tempMcpConfigPath=a,a}catch(s){return this.logger.warn("Failed to write MCP config file",s),null}}async discoverSubagents(e){const t=[];try{const s=F.join(e,".claude","agents");if(C.existsSync(s)){const a=C.readdirSync(s).filter(c=>c.endsWith(".md"));for(const c of a){const h=F.basename(c,".md");t.push(`${h} (project)`)}}const i=F.join(q.homedir(),".claude","agents");if(C.existsSync(i)){const a=C.readdirSync(i).filter(c=>c.endsWith(".md"));for(const c of a){const h=F.basename(c,".md");t.some(p=>p.startsWith(`${h} (`))||t.push(`${h} (user)`)}}}catch(s){this.logger.warn("Failed to discover subagents:",s)}return t}async detectClaudeVersion(){try{const{execSync:e}=await import("child_process"),s=e(`${this.claudePath} --version`,{encoding:"utf-8"}).match(/(\d+\.\d+\.\d+)/);if(s){this.claudeVersion=s[1];const[i]=this.claudeVersion.split(".").map(Number);this.supportsSettingsFlag=i>=2,this.logger.info(`Detected Claude Code version ${this.claudeVersion} (--settings flag: ${this.supportsSettingsFlag})`)}}catch(e){this.logger.warn("Failed to detect Claude Code version, assuming legacy version",e),this.supportsSettingsFlag=!1}}async createTempSettingsFile(e){try{const t=[F.join(__dirname,"..","..","dist","claudePostToolUse.js"),F.join(__dirname,"..","dist","claudePostToolUse.js"),F.join(__dirname,"dist","claudePostToolUse.js"),F.join(process.cwd(),"dist","claudePostToolUse.js")];let s=null;for(const v of t)if(C.existsSync(v)){s=v;break}if(!s)return this.logger.warn("PostToolUse hook file not found at any expected location"),null;const i=[F.join(__dirname,"..","..","dist","claudePreToolUse.js"),F.join(__dirname,"..","dist","claudePreToolUse.js"),F.join(__dirname,"dist","claudePreToolUse.js"),F.join(process.cwd(),"dist","claudePreToolUse.js")];let r=null;for(const v of i)if(C.existsSync(v)){r=v;break}const a=[F.join(__dirname,"..","..","dist","claudeNotification.js"),F.join(__dirname,"..","dist","claudeNotification.js"),F.join(__dirname,"dist","claudeNotification.js"),F.join(process.cwd(),"dist","claudeNotification.js")];let c=null;for(const v of a)if(C.existsSync(v)){c=v;break}const h=[F.join(__dirname,"..","..","dist","claudeSessionStart.js"),F.join(__dirname,"..","dist","claudeSessionStart.js"),F.join(__dirname,"dist","claudeSessionStart.js"),F.join(process.cwd(),"dist","claudeSessionStart.js")];let f=null;for(const v of h)if(C.existsSync(v)){f=v;break}const p={hooks:{...f?{SessionStart:[{matcher:"startup",hooks:[{type:"command",command:`node ${f}`}]}]}:{},...r?{PreToolUse:[{matcher:"*",hooks:[{type:"command",command:`node ${r}`}]}]}:{},PostToolUse:[{matcher:"*",hooks:[{type:"command",command:`node ${s}`}]}],...c?{Notification:[{matcher:"*",hooks:[{type:"command",command:`node ${c}`}]}]}:{}}},E=`claude-settings-${e}.json`,m=F.join(q.tmpdir(),E);return await ne.writeFile(m,JSON.stringify(p,null,2),"utf8"),this.tempSettingsPath=m,this.logger.info(`Created temporary settings file at ${m}`),f&&this.logger.info("SessionStart hook enabled - session ready status will be sent on startup"),r&&this.logger.info("PreToolUse hook enabled - tool inputs will be logged for inspection"),c&&this.logger.info("Notification hook enabled - notifications will be logged to .claude-logs/notifications.jsonl"),m}catch(t){return this.logger.error(`Failed to create temporary settings file: ${t}`),null}}async addPostToolUseHook(e){const t=F.join(e,".claude","settings.local.json"),s=F.dirname(t);try{await ne.mkdir(s,{recursive:!0});let i={};try{const f=await ne.readFile(t,"utf-8");i=JSON.parse(f)}catch{this.logger.debug("No existing settings.local.json found, creating new one")}i.hooks||(i.hooks={}),i.hooks.PostToolUse||(i.hooks.PostToolUse=[]);let r=null;const a=[F.join(__dirname,"..","..","dist","claudePostToolUse.js"),F.join(__dirname,"..","dist","claudePostToolUse.js"),F.join(__dirname,"dist","claudePostToolUse.js"),F.join(process.cwd(),"dist","claudePostToolUse.js")];for(const f of a)if(C.existsSync(f)){r=f;break}if(!r){this.logger.warn("PostToolUse hook file not found at any expected location");return}const c={matcher:"*",hooks:[{type:"command",command:`node ${r}`}]};i.hooks.PostToolUse.some(f=>f.hooks&&Array.isArray(f.hooks)?f.hooks.some(p=>p.type==="command"&&p.command===`node ${r}`):!1)||(i.hooks.PostToolUse.push(c),await ne.writeFile(t,JSON.stringify(i,null,2)),this.logger.info(`Added PostToolUse hook to ${t}`))}catch(i){this.logger.error(`Failed to add PostToolUse hook: ${i}`)}}async removePostToolUseHook(e){const t=F.join(e,".claude","settings.local.json");try{const s=await ne.readFile(t,"utf-8"),i=JSON.parse(s);if(i.hooks?.PostToolUse){let r=null;const a=[F.join(__dirname,"..","..","dist","claudePostToolUse.js"),F.join(__dirname,"..","dist","claudePostToolUse.js"),F.join(__dirname,"dist","claudePostToolUse.js"),F.join(process.cwd(),"dist","claudePostToolUse.js")];for(const h of a)if(C.existsSync(h)){r=h;break}if(!r)return;const c=`node ${r}`;i.hooks.PostToolUse=i.hooks.PostToolUse.filter(h=>h.hooks&&Array.isArray(h.hooks)?(h.hooks=h.hooks.filter(f=>!(f.type==="command"&&f.command===c)),h.hooks.length>0):!0),i.hooks.PostToolUse.length===0&&delete i.hooks.PostToolUse,Object.keys(i.hooks).length===0&&delete i.hooks,await ne.writeFile(t,JSON.stringify(i,null,2)),this.logger.info(`Removed PostToolUse hook from ${t}`)}}catch(s){this.logger.debug(`Could not remove PostToolUse hook: ${s}`)}}writeSessionSettings(e,t,s,i,r){try{const a=F.join(q.homedir(),".agiflow"),c=F.join(a,"sessions.json");C.existsSync(a)||C.mkdirSync(a,{recursive:!0});let h={};if(C.existsSync(c))try{h=JSON.parse(C.readFileSync(c,"utf-8"))}catch{this.logger.warn("Invalid sessions.json, creating new one")}h[e]={...t&&{provider:t},...s&&{model:s},...i&&{alias:i},...r&&{reasoningEffort:r}},C.writeFileSync(c,JSON.stringify(h,null,2),"utf-8"),this.logger.info(`Session settings written to ${c}`),t&&s?this.logger.info(`Session: ${i||e} (${t}/${s})`):this.logger.info(`Session: ${i||e} (default Claude)`)}catch(a){this.logger.error("Failed to write session settings",a)}}async launchAgent(e){const{payload:t}=e,s=t.agentSessionId,i=t.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(t.agentConfig.workingDirectory):process.cwd();this.startupCommands=t.agentConfig?.commands??[],this.startupCommandsExecuted=!1;const r=t.agentConfig?.xterm??!1;this.setXtermEnabled(r);const a=t.agentConfig?.llmConfig,c=t.agentConfig?.sessionAlias;a?.provider?this.writeSessionSettings(s,a.provider,a.model||"default",c,void 0):this.writeSessionSettings(s,void 0,void 0,c,void 0);const{command:h,args:f}=this.detectClaudeType();this.claudePath=h,this.claudeArgs=f,await this.detectClaudeVersion();const p=t.agentConfig?.hooks?.preAgentStartHooks||t.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(p,i,s),o.SubEnvManager.isContainerMode&&r&&this.setFullscreen(!0),this.serverUrl?this.supportsSettingsFlag?await this.createTempSettingsFile(s):await this.addPostToolUseHook(i):this.logger.info("Running in standalone mode - PostToolUse hook will not be configured");const m=await this.discoverSubagents(i);m.length>0&&this.logger.info(`Discovered ${m.length} Claude subagent(s): ${m.join(", ")}`);const v=this.writeMcpConfigFile(t.agentConfig?.mcps,s),_=F.join(i,".mcp.json"),u=this.writeProjectMcpConfigFile(_,t.agentConfig?.mcps,s);u&&(this.tempProjectMcpConfigPath=u),this.serverUrl?await this.connectToSession(s):this.logger.info("Running in standalone mode - skipping WebSocket connection"),await this.setupDockerRepository(e);const l=this.buildClaudeArgs(e),g=[];u?g.push(u):C.existsSync(_)&&g.push(_),v&&g.push(v),g.length&&l.push("--mcp-config",...g);try{const d=this.getAgentEnvironmentVariables(),D=this.configureNodeOptions(d),w=process.listeners("SIGINT"),k=()=>{this.handleCtrlC()?(this.logger.info("Double Ctrl+C detected, terminating Claude agent..."),process.removeListener("SIGINT",k),w.forEach(B=>{typeof B=="function"&&process.on("SIGINT",B)}),this.ptyRunner.kill("SIGINT")):this.ptyRunner.sendInput("")};process.removeAllListeners("SIGINT"),process.on("SIGINT",k);const A=this.ptyRunner.spawn({command:this.claudePath,args:l,workingDir:i,agentSessionId:s,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{...d,NODE_OPTIONS:D,[o.ENV_KEYS.AGENT_SESSION_ID]:s,[o.ENV_KEYS.AGENT_TYPE]:this.agentType,...v?{CLAUDE_MCP_CONFIG_FILE:v}:{},...t.data?{[o.ENV_KEYS.CONTEXT_DATA]:t.data}:{}}},{onExit:async(T,B)=>{if(process.removeListener("SIGINT",k),w.forEach(P=>{typeof P=="function"&&process.on("SIGINT",P)}),this.ctrlCTimeout&&(clearTimeout(this.ctrlCTimeout),this.ctrlCTimeout=null),this.serverUrl)if(this.supportsSettingsFlag){if(this.tempSettingsPath){try{C.unlinkSync(this.tempSettingsPath),this.logger.info(`Removed temporary settings file: ${this.tempSettingsPath}`)}catch(P){this.logger.warn("Failed to delete temp settings file",P)}this.tempSettingsPath=null}}else await this.removePostToolUseHook(i);if(this.tempMcpConfigPath){try{C.unlinkSync(this.tempMcpConfigPath)}catch(P){this.logger.warn("Failed to delete temp MCP config file",P)}this.tempMcpConfigPath=null}if(this.tempProjectMcpConfigPath){try{C.unlinkSync(this.tempProjectMcpConfigPath),this.logger.info(`Removed temporary project MCP config file: ${this.tempProjectMcpConfigPath}`)}catch(P){this.logger.warn("Failed to delete temp project MCP config file",P)}this.tempProjectMcpConfigPath=null}this.logger.info(`Claude Code PTY exited with code ${T}, signal: ${B}`),this.sendAgentStatus({agentType:H.CLAUDE_CODE,status:T===0?L.STOPPED:L.ERROR,message:`Claude Code session ended (exit code: ${T})`}),this.wsService&&this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:B===2?"agent_sigint":"natural",exitCode:T,signal:B})},onData:async T=>{this.verifyAgentReady(T),this.xtermEnabled&&this.sendStdoutEvent(T)}});this.logger.success(`Claude Code launched successfully for session agentSessionId: ${s}`),this.ptySessionId=A.id,r?this.resizePty(80,24):this.setupInitialPtySize();const $={agentSessionId:s,agentType:H.CLAUDE_CODE,status:L.IDLE,workingDir:i,process:A.ptyProcess,metadata:{agentSessionId:s,agentType:t.agentType,config:t.agentConfig,ptySessionId:A.id}};return this.setAgentInfo($),$}catch(d){throw new Error(`Failed to launch Claude Code: ${d instanceof Error?d.message:String(d)}`)}}async isAvailable(){return!0}async getVersion(){return"claude-pty-agent"}buildClaudeArgs(e){const t=[...this.claudeArgs,...e.payload?.agentConfig?.args||[]],s=e.payload?.agentConfig?.conversationSessionId;return s&&t.push("--session-id",s),this.supportsSettingsFlag&&this.tempSettingsPath&&t.push("--settings",this.tempSettingsPath),t}}class br{session;logger;constructor(e){this.logger=e??new o.Logger({verbose:!1})}async isDockerAvailable(){return new Promise(e=>{const t=z.spawn("docker",["--version"],{stdio:"pipe"});t.on("close",s=>{e(s===0)}),t.on("error",()=>{e(!1)})})}spawn(e,t){const s=e.agentSessionId||mt.ulid(),i=e.workingDir??process.cwd(),r=e.dockerImage||"agiflow/claude-agent:latest",a=this.buildDockerArgs(s,e,r),c=`docker ${a.join(" ")}`;this.logger.info(`🐳 Docker Command: ${c}`),this.logger.debug("Spawning Docker container with args:",a);const h=z.spawn("docker",a,{stdio:["pipe","pipe","pipe"]}),f=`claude-agent-${s}`,p={id:s,dockerProcess:h,containerId:f,command:`docker ${a.join(" ")}`,workingDir:i,status:"running",createdAt:new Date,lastActivity:new Date,logStream:e.logStream};return h.stdout?.on("data",E=>{p.lastActivity=new Date;const m=E.toString();p.logStream&&p.logStream.write(m),process.stdout.write(m),t?.onData&&t.onData(m)}),h.stderr?.on("data",E=>{const m=E.toString();this.logger.error(`🐳 Container ${f} stderr: ${m.trim()}`),process.stderr.write(m)}),h.on("close",E=>{p.status=E===0?"stopped":"error",p.lastActivity=new Date,this.logger.info(`Container ${f} exited with code ${E}`),p.logStream&&p.logStream.end(),t?.onExit&&t.onExit(E||0,void 0)}),h.on("error",E=>{p.status="error",this.logger.error(`Container ${f} error:`,E),t?.onError&&t.onError(E)}),this.session=p,p}buildDockerArgs(e,t,s){const r=["run","--rm","--name",`claude-agent-${e}`,"-i"];if(t.privileged&&r.push("--privileged"),t.user&&r.push("--user",t.user),t.networkMode&&r.push("--network",t.networkMode),t.ports&&t.ports.length>0)for(const m of t.ports)r.push("-p",`${m.host}:${m.container}`);const a=t.agentServerUrl||o.SubEnvManager.serverUrl;r.push("-e",`${o.ENV_KEYS.AGENT_SERVER_URL}=${a}`);const c=t.agentApiKey||o.SubEnvManager.apiKey;c&&r.push("-e",`${o.ENV_KEYS.AGENT_API_KEY}=${c}`);const h=t.agentOrganizationId||o.SubEnvManager.organizationId;h&&r.push("-e",`${o.ENV_KEYS.AGENT_ORGANIZATION_ID}=${h}`);const f=t.agentType||o.SubEnvManager.agentType;f&&r.push("-e",`${o.ENV_KEYS.AGENT_TYPE}=${f}`);const p=e||o.SubEnvManager.sessionId;if(p&&r.push("-e",`${o.ENV_KEYS.AGENT_SESSION_ID}=${p}`),t.additionalEnvVars)for(const[m,v]of Object.entries(t.additionalEnvVars))r.push("-e",`${m}=${v}`);t.workingDir&&(r.push("-v",`${t.workingDir}:/workspace`),r.push("-w","/workspace"));const E=F.join(q.homedir(),".agiflow");if(mn.existsSync(E)?(r.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}`),t.additionalVolumes&&t.additionalVolumes.length>0)for(const m of t.additionalVolumes){let v;m.type==="volume"?(v=m.readonly?`${m.host}:${m.container}:ro`:`${m.host}:${m.container}`,this.logger.debug(`Mounting named volume: ${m.host} -> ${m.container}`)):(v=m.readonly?`${m.host}:${m.container}:ro`:`${m.host}:${m.container}`,this.logger.debug(`Mounting bind volume: ${m.host} -> ${m.container}`)),r.push("-v",v)}if(o.SubEnvManager.isDebugMode&&r.push("-v","/var/run/docker.sock:/var/run/docker.sock"),r.push(s),r.push("claude"),r.push("--server-url",a),t.agentApiUrl&&r.push("--api-url",t.agentApiUrl),c&&r.push("--api-key",c),h&&r.push("--organization-id",h),p&&r.push("--agent-session-id",p),t.workingDir&&r.push("--working-directory","/workspace"),t.agentConfig){const m=encodeURIComponent(t.agentConfig);r.push("--agent-config",m)}return t.verbose&&r.push("--verbose"),t.args&&t.args.length>0&&r.push("--args",...t.args),r}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(t){return this.logger.error("Failed to send input to Docker container:",t),!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(t){return this.logger.error(`Failed to kill Docker container: ${t}`),!1}}getSession(){return this.session}isSessionRunning(){return this.session?.status==="running"}}class Tr{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 o.Logger({verbose:this.verbose}),this.terminationService=e.terminationService??new De(this.logger),this.dockerImage=e.dockerImage||"agiflowai/agent-cli:latest",this.onFullscreenChange=e.onFullscreenChange,this.dockerRunner=new br(this.logger)}async isAvailable(){return await this.dockerRunner.isDockerAvailable()}getAgentInfo(){return this.agentInfo}setAgentInfo(e){this.agentInfo=e}getAgentEnvironmentVariables(){const e={};for(const[t,s]of Object.entries(process.env))s!==void 0&&(e[t]=s);return this.apiKey&&(e[o.ENV_KEYS.AGENT_API_KEY]=this.apiKey),this.organizationId&&(e[o.ENV_KEYS.AGENT_ORGANIZATION_ID]=this.organizationId),this.serverUrl&&(e[o.ENV_KEYS.AGENT_SERVER_URL]=this.serverUrl),e[o.ENV_KEYS.AGENT_TYPE]=this.agentType,e[o.ENV_KEYS.VERBOSE]=this.verbose?"true":"false",e}addToBackgroundBuffer(e){const t=e.length>this.BACKGROUND_CHUNK_MAX_SIZE?e.substring(e.length-this.BACKGROUND_CHUNK_MAX_SIZE):e;this.backgroundOutputBuffer.push(t),this.backgroundOutputBuffer.length>this.BACKGROUND_BUFFER_SIZE&&this.backgroundOutputBuffer.shift(),this.logger.debug(`🐳 Added ${t.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,t=!1){const s=this.isFullscreen;this.isFullscreen=e,this.logger.debug(`Docker agent fullscreen mode ${e?"enabled":"disabled"}`),e&&!s&&this.agentInfo&&this.flushBackgroundBuffer(),!t&&s!==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 qt extends Tr{onBeforeTerminate;constructor(e){super({...e,agentType:H.CLAUDE_CODE,dockerImage:e.dockerImage||J.VITE_AGENT_CLI_DOCKER_IMAGE}),this.onBeforeTerminate=e.onBeforeTerminate}async getVersion(){return"claude-docker-agent"}async launchAgent(e){const{payload:t}=e,s=t.agentSessionId,i=t.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(t.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: ${s}`);const r=this.getDockerOptions(e);try{const a=this.dockerRunner.spawn(r,{onExit:async(h,f)=>{if(this.logger.info(`Docker Claude agent exited with code ${h}, signal: ${f}`),this.onBeforeTerminate)try{this.logger.info("Executing cleanup callback before termination..."),await this.onBeforeTerminate(),this.logger.info("Cleanup callback completed successfully")}catch(p){this.logger.error("Error during cleanup callback:",p)}this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:f===2?"agent_sigint":"natural",exitCode:h,signal:f})},onData:async h=>{this.logger.debug("Docker container output:",h)},onError:h=>{this.logger.error("Docker container error:",h)}});this.logger.success(`Docker Claude agent launched successfully for session: ${s}`);const c={agentSessionId:s,agentType:H.CLAUDE_CODE,status:L.IDLE,workingDir:i,containerId:a.containerId,dockerSessionId:a.id,process:a.dockerProcess,metadata:{agentSessionId:s,agentType:t.agentType,config:t.agentConfig,docker:!0,containerId:a.containerId,dockerSessionId:a.id}};return this.setAgentInfo(c),c}catch(a){throw new Error(`Failed to launch Claude Docker agent: ${a instanceof Error?a.message:String(a)}`)}}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:t}=e,s=t.agentSessionId,i=t.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(t.agentConfig.workingDirectory):process.cwd(),r=J.VITE_INJECT_AGIFLOW_APP_DOCKER_ENDPOINT||this.serverUrl,a=r?r.replace(/^http/,"ws"):void 0;let c=null;t.agentConfig?.mcps&&(c=this.processAgentConfig(t.agentConfig.mcps));const h={...t.agentConfig,workingDirectory:"/workspace"};return c&&(h.mcps=c),{agentSessionId:s,dockerImage:t.agentConfig?.dockerImage||this.dockerImage,workingDir:i,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:a,agentApiUrl:r,agentType:H.CLAUDE_CODE,agentConfig:JSON.stringify(h),verbose:this.verbose,additionalEnvVars:{[o.ENV_KEYS.NODE_ENV]:o.SubEnvManager.nodeEnv,[o.ENV_KEYS.AGENT_SESSION_ID]:s,[o.ENV_KEYS.AGENT_CONTAINER_MODE]:o.SubEnvManager.isContainerMode?"true":"false",IS_SANDBOX:"1"},additionalVolumes:this.getAdditionalVolumes(t),networkMode:J.VITE_AGENT_CLI_DOCKER_NETWORK,user:void 0}}getAdditionalVolumes(e){const t=[],s=o.SubEnvManager.homeDir;if(s)if(t.push({host:`${s}/.ssh`,container:"/root/.ssh",readonly:!0,type:"bind"}),t.push({host:"agiflow-pnpm-cache",container:"/root/.pnpm-store",readonly:!1,type:"volume"}),t.push({host:"agiflow-npm-cache",container:"/root/.npm",readonly:!1,type:"volume"}),t.push({host:"agiflow-node-gyp-cache",container:"/root/.cache/node-gyp",readonly:!1,type:"volume"}),o.SubEnvManager.isMacOS){const r=`${s}/.claude_tmp.json`;C.existsSync(r)||C.writeFileSync(r,"{}","utf8"),t.push({host:r,container:"/root/.claude.json",readonly:!1,type:"bind"});const a=`${s}/.claude_tmp`;C.existsSync(a)||C.mkdirSync(a,{recursive:!0}),t.push({host:a,container:"/root/.claude",readonly:!1,type:"bind"})}else{const r=`${s}/.claude.json`;C.existsSync(r)||C.writeFileSync(r,"{}","utf8"),t.push({host:r,container:"/root/.claude.json",readonly:!1,type:"bind"});const a=`${s}/.claude`;C.existsSync(a)||C.mkdirSync(a,{recursive:!0}),t.push({host:a,container:"/root/.claude",readonly:!1,type:"bind"})}return t}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 t={};if(Array.isArray(e))for(const s of e){if(!s||typeof s!="object")continue;const i=s.name||s.id||s.key;i&&(t[i]={type:s.type||"stdio",command:s.command,args:s.args||s.arguments||[],url:s.url,env:s.env||{},disabled:s.disabled??!1,headers:s.headers||{}})}else if(typeof e=="object")for(const[s,i]of Object.entries(e))i&&typeof i=="object"&&(t[s]={...i,headers:i.headers||{}});return t}}class Yt extends fe{register(e){e.command("claude").description("Launch Claude Code agent with full functionality").option("-s, --server-url <url>","WebSocket server URL").option("-a, --api-url <url>","HTTP API URL").option("-k, --api-key <key>","API key for authentication").option("-o, --organization-id <id>","Organization ID").option("-v, --verbose","Enable verbose logging",!1).option("-p, --claude-path <path>","Path to Claude executable","claude").option("-w, --working-directory <dir>","Working directory",process.cwd()).option("-i, --agent-session-id <id>","Agent session ID").option("-c, --agent-config <json>","Agent configuration as JSON string").option("--args <args...>","Additional arguments to pass to Claude").option("--docker","Run Claude agent in Docker container",!1).option("--docker-image <image>","Docker image to use for containerized agent").option("--llm-provider <provider>","LLM provider to route requests to (e.g., openai)").option("--llm-model <model>","LLM model to use (e.g., gpt-4-turbo, gpt-5)").option("--alias <alias>","Custom session alias for easy identification").option("--standalone","Run in standalone mode without backend connection",!1).action(async t=>{try{await this.execute(t)}catch(s){this.handleError(s)}})}async execute(e){let t;if(e.llmProvider){const l=["codex","gpt","openai","chatgpt"],g=e.llmProvider.toLowerCase();l.includes(g)||(this.error(`Invalid LLM provider: ${e.llmProvider}`),this.error(`Allowed providers: ${l.join(", ")}`),process.exit(1)),t={provider:g,model:e.llmModel}}const s=e.standalone?void 0:e.serverUrl||J.VITE_INJECT_AGIFLOW_APP_ENDPOINT,i=e.standalone?void 0:e.apiUrl||J.VITE_INJECT_AGIFLOW_APP_ENDPOINT,r=e.standalone?void 0:e.apiKey||o.SubEnvManager.apiKey,a=e.standalone?void 0:e.organizationId||o.SubEnvManager.organizationId;let c=e.agentSessionId||o.SubEnvManager.sessionId;if(c||(c=pt.randomUUID(),e.verbose&&this.info(`Generated session ID: ${c}`)),!s)e.verbose&&(e.standalone?this.info("Running in standalone mode (--standalone flag)"):this.info("Running in standalone mode (no server URL configured)"),this.info("Agent will launch without remote connectivity"));else try{new URL(s)}catch{this.error("Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://)."),process.exit(1)}if(i)try{new URL(i)}catch{this.error("Invalid API URL. Must be a valid HTTP URL."),process.exit(1)}else!s&&e.verbose&&this.info("No API URL provided - HTTP features will be unavailable");const h=()=>{const g=new Date().toISOString().replace(/[-:]/g,"").replace("T","-").split(".")[0],d=e.llmProvider||"claude",D=e.llmModel?.replace(/[^a-z0-9]/gi,"")||"default";return`${d}-${D}-${g}`},f=e.alias||h(),p=new o.Logger({verbose:e.verbose});e.verbose&&(this.info(`Starting Claude agent${e.docker?" in Docker container":""}...`),this.info(`Session: ${f} (ID: ${c})`),p.debug("Options:",e),e.llmProvider&&this.info(`LLM Routing enabled: ${e.llmProvider} → ${e.llmModel||"default model"}`));const E=new o.CredentialsService,m=new De(p),v=e.docker?new qt({agentType:H.CLAUDE_CODE,serverUrl:s,apiKey:r,organizationId:a,verbose:e.verbose,dockerImage:e.dockerImage,logger:p,terminationService:m}):new zt({agentType:H.CLAUDE_CODE,serverUrl:s,apiUrl:i,apiKey:r,organizationId:a,verbose:e.verbose,claudePath:e.claudePath,standalone:!0,logger:p,credentialsService:E,terminationService:m});let _={workingDirectory:e.workingDirectory?o.FileSystemUtils.getAbsolutePath(e.workingDirectory):process.cwd(),args:e.args||[],sessionAlias:f,...t&&{llmConfig:t}};if(e.agentConfig)try{const l=decodeURIComponent(e.agentConfig),g=JSON.parse(l);_={..._,...g}}catch(l){try{const g=JSON.parse(e.agentConfig);_={..._,...g}}catch{this.error(`Failed to parse agent config JSON: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}}const u=Ve.parse({payload:{sessionId:c,agentType:H.CLAUDE_CODE,agentSessionId:c,agentConfig:_}});try{await v.launchAgent(u),this.success(`Claude agent${e.docker?" (Docker)":""} launched successfully for session: ${f}`);const l=async g=>{e.verbose&&this.info(`Received ${g}, shutting down Claude agent${e.docker?" container":""}...`);try{v.disconnect(),this.info(`Claude agent${e.docker?" container":""} shutdown complete`),process.exit(0)}catch(d){this.error(`Error during shutdown: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}};process.on("SIGINT",()=>l("SIGINT")),process.on("SIGTERM",()=>l("SIGTERM")),this.info(`Claude agent${e.docker?" container":""} is running. Press Ctrl+C to stop.`),await new Promise(()=>{})}catch(l){this.error(`Failed to start Claude agent: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}}}const kr=Dn.promisify(z.exec);class Ir{claudeAgentsPath;constructor(e={}){this.claudeAgentsPath=e.claudeAgentsPath||F.join(q.homedir(),".claude","agents")}async findAgentsDirectory(){const e=F.join(process.cwd(),".claude","agents");try{if((await C.promises.stat(e)).isDirectory())return e}catch{}try{if((await C.promises.stat(this.claudeAgentsPath)).isDirectory())return this.claudeAgentsPath}catch{}try{const t=q.homedir(),s=[`"${t}/.config"`,`"${t}/.local"`,`"${t}/workspace"`,`"${t}/projects"`,`"${t}/dev"`,`"${t}/code"`,`"${t}/.claude"`,`"${t}"`];for(const i of s)try{const a=i===`"${t}"`?1:5,c=`find ${i} -maxdepth ${a} -type d -name "agents" -path "*/.claude/agents" 2>/dev/null | head -1`,{stdout:h}=await kr(c),f=h.trim();if(f&&f.length>0&&(await C.promises.stat(f)).isDirectory())return f}catch{}}catch(t){console.error("Error searching for .claude/agents directory:",t)}return null}async listAgentFiles(){const e=await this.findAgentsDirectory();if(!e)return[];try{return(await C.promises.readdir(e)).filter(s=>s.endsWith(".md")).map(s=>F.join(e,s))}catch(t){return console.error("Error reading agents directory:",t),[]}}async parseAgentFile(e){try{const t=await C.promises.readFile(e,"utf-8");return this.parseAgentContent(t,e)}catch(t){return console.error(`Error reading agent file ${e}:`,t),null}}parseAgentContent(e,t){const s=e.split(`
|
|
53
|
+
`),i=s.findIndex(p=>p.trim()==="---"),r=s.findIndex((p,E)=>E>i&&p.trim()==="---");if(i===-1||r===-1)return console.error(`Invalid frontmatter in ${t}`),null;const a=s.slice(i+1,r),c={};for(const p of a){const E=p.indexOf(":");if(E>0){const m=p.substring(0,E).trim(),v=p.substring(E+1).trim();c[m]=v}}const f=s.slice(r+1).join(`
|
|
54
|
+
`).trim();return!c.name||!c.description?(console.error(`Missing required fields in ${t}`),null):{name:c.name,description:c.description,color:c.color||"default",prompt:f,filePath:t}}async getAllAgentProfiles(){const e=await this.listAgentFiles(),t=[];for(const s of e){const i=await this.parseAgentFile(s);i&&t.push(i)}return t}async getAgentProfile(e){return(await this.getAllAgentProfiles()).find(s=>s.name===e)||null}async searchAgentProfiles(e){const t=await this.getAllAgentProfiles(),s=e.toLowerCase();return t.filter(i=>i.name.toLowerCase().includes(s)||i.description.toLowerCase().includes(s))}}class Ke{options;apiKeyPath;logger;constructor(e){this.options=e,this.logger=e.logger||new o.Logger({verbose:e.verbose||!1}),this.apiKeyPath=F.join(o.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 t=await this.performDeviceCodeFlow();return await this.storeApiKey(t),t}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 h=await e.text();throw new Error(`Device authorization failed: ${e.status} ${h}`)}const t=await e.json(),s=`${t.verification_uri}?code=${encodeURIComponent(t.user_code)}`;this.logger.info("To authenticate your CLI:"),this.logger.info(`1. Open (or we opened): ${s}`),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: ${t.user_code}`);const i=await ve.input({message:"Paste verification token (JWT):",validate:h=>!h||h.trim().split(".").length!==3?"Invalid verification token format. Please enter a valid JWT token.":!0}),r=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:t.device_code,verification_token:i.trim(),client_id:this.options.clientId})});if(!r.ok){const h=await r.text();throw new Error(`Token exchange failed: ${r.status} ${h}`)}const a=await r.json();if(!a.api_key)throw new Error("Token exchange response missing api_key");if(!a.organization_id)throw new Error("Token exchange response missing organization_id");this.logger.success(`Authentication successful!
|
|
55
|
+
`);const c={api_key:a.api_key,key_id:"device-flow",expires_at:Date.now()+a.expires_in*1e3,organization_id:a.organization_id,prefix:"agiflow_"};return await this.checkAndOfferAgentProfiles(c),c}async loadApiKey(){try{return await o.FileSystemUtils.exists(this.apiKeyPath)?await o.FileSystemUtils.readJson(this.apiKeyPath):null}catch{return null}}async storeApiKey(e){await this.ensureAgiflowDir(),await o.FileSystemUtils.writeJson(this.apiKeyPath,e),this.logger.debug(`API key stored at ${this.apiKeyPath}`)}async ensureAgiflowDir(){await o.FileSystemUtils.ensureDir(o.FileSystemUtils.AGIFLOW_DIR)}isTokenValid(e){return Date.now()<e-3e5}async clearTokens(){try{await o.FileSystemUtils.exists(this.apiKeyPath)&&await o.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 t=await this.loadApiKey();t&&(t.device_id=e,await this.storeApiKey(t),this.logger.debug(`Updated device ID in stored API key: ${e}`))}async checkAndOfferAgentProfiles(e){try{this.logger.info("Checking for local agent profiles...");const s=await new Ir().getAllAgentProfiles();if(s.length===0){this.logger.info("No local agent profiles found.");return}this.logger.info(`Found ${s.length} local agent profile(s):`),s.forEach((r,a)=>{this.logger.info(` ${a+1}. ${r.name} - ${r.description.substring(0,80)}...`)}),await ve.confirm({message:"Would you like to add these agent profiles to your organization?",default:!1})?await this.uploadAgentProfiles(s,e):this.logger.info("Skipping agent profile upload.")}catch(t){this.logger.warn(`Could not check agent profiles: ${t instanceof Error?t.message:t}`)}}async uploadAgentProfiles(e,t){this.logger.info("Uploading agent profiles to organization...");try{const s=await fetch(`${this.options.baseUrl}/api/v1/organizations/${t.organization_id}/members/agents`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t.api_key},body:JSON.stringify({agents:e.map(i=>({name:i.name,description:i.description,prompt:i.prompt}))})});if(s.ok){const i=await s.json(),r=i.created?.length||0,a=i.errors?.length||0;r>0&&(this.logger.success(`Successfully uploaded ${r} agent profile(s) to your organization!`),i.created.forEach(c=>{this.logger.info(`✅ Created: ${c.user.name}`)})),a>0&&(this.logger.warn(`Failed to upload ${a} agent profile(s):`),i.errors.forEach(c=>{this.logger.warn(`❌ ${c.name}: ${c.error}`)}))}else{const i=await s.text();this.logger.warn(`❌ Failed to upload agent profiles: ${s.status} ${i}`)}}catch(s){this.logger.warn(`❌ Error uploading agent profiles: ${s instanceof Error?s.message:s}`)}}}class xr{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 Or{semaphores=new Map;permits;constructor(e=1){this.permits=e}getSemaphore(e){let t=this.semaphores.get(e);return t||(t=new xr(this.permits),this.semaphores.set(e,t)),t}async acquire(e){return this.getSemaphore(e).acquire()}release(e){const t=this.semaphores.get(e);t&&(t.release(),t.available===this.permits&&t.waiting===0&&this.semaphores.delete(e))}async runExclusive(e,t){return this.getSemaphore(e).runExclusive(t)}isLocked(e){const t=this.semaphores.get(e);return t?t.available===0:!1}clear(){this.semaphores.clear()}}class $r extends Kt{geminiPath;tempExtensionConfigPath=null;agentInputReady=!1;optionBuffer="";optionTimeout=null;isCollectingOptions=!1;OPTION_WAIT_MS=1e3;constructor(e){super({...e,agentType:H.GEMINI_CLI}),this.geminiPath=e.geminiPath||"gemini"}async launchAgent(e){const{payload:t}=e,s=t.agentSessionId,i=t.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(t.agentConfig.workingDirectory):process.cwd(),r=t.agentConfig?.xterm??!1;this.setXtermEnabled(r);const a=t.agentConfig?.hooks?.preAgentStartHooks||t.agentConfig?.hooks?.preAgentStart;await this.executePreAgentStartHooks(a,i,s),this.logger.debug("Agent config MCPs:",t.agentConfig?.mcps);const c=await this.writeGeminiExtensionFile(t.agentConfig?.mcps,i);this.logger.debug("Custom Gemini extension config result:",c);const h=F.join(i,"agiflow-extension.json");this.logger.debug("Project Gemini extension config path:",h),await this.connectToSession(s),await this.setupDockerRepository(e);const f=this.buildGeminiArgs(e);C.existsSync(h)?this.logger.debug(`Found project Gemini extension config: ${h}`):this.logger.debug("No project agiflow-extension.json found in working directory"),c&&this.logger.debug(`Created Gemini extension config: ${c}`);try{const p=this.getAgentEnvironmentVariables(),E=this.configureNodeOptions(p),m=this.ptyRunner.spawn({command:this.geminiPath,args:f,workingDir:i,agentSessionId:s,logger:this.logger,agentApiKey:this.apiKey,agentOrganizationId:this.organizationId,agentServerUrl:this.serverUrl,agentType:this.agentType,env:{...p,NODE_OPTIONS:E,GEMINI_SESSION_ID:s,GEMINI_AGENT_SESSION_ID:s,GEMINI_AGENT_MODE:"true",...c?{GEMINI_EXTENSION_CONFIG_FILE:c}:{}}},{onData:async _=>{this.verifyAgentReady(_),this.processDataForOptions(_),this.xtermEnabled&&this.sendStdoutEvent(_)},onExit:async(_,u)=>{if(this.tempExtensionConfigPath){try{C.unlinkSync(this.tempExtensionConfigPath),this.logger.debug(`Deleted temp Gemini extension config file: ${this.tempExtensionConfigPath}`)}catch(l){this.logger.warn("Failed to delete temp Gemini extension config file",l)}this.tempExtensionConfigPath=null}this.logger.info(`Gemini PTY exited with code ${_}, signal: ${u}`),this.sendAgentStatus({agentType:H.GEMINI_CLI,status:_===0?L.STOPPED:L.ERROR,message:`Gemini session ended (exit code: ${_})`}),this.wsService&&this.wsService.disconnect(),this.ptySessionId=null,this.agentInfo&&await this.terminationService.handlePtyTermination({agentSessionId:this.agentInfo.agentSessionId,reason:"natural",exitCode:_,signal:u})}});this.logger.success(`Gemini launched successfully for session agentSessionId: ${s}`),this.ptySessionId=m.id,r?this.resizePty(80,24):this.setupInitialPtySize();const v={agentSessionId:s,agentType:H.GEMINI_CLI,status:L.IDLE,workingDir:i,process:m.ptyProcess,metadata:{agentSessionId:s,agentType:t.agentType,config:t.agentConfig,ptySessionId:m.id}};return this.setAgentInfo(v),v}catch(p){throw new Error(`Failed to launch Gemini: ${p instanceof Error?p.message:String(p)}`)}}async isAvailable(){return!0}async getVersion(){return"gemini-pty-agent"}verifyAgentReady(e){if(this.agentInputReady)return;const s=(a=>a.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(a=>a.test(s))&&(this.agentInputReady=!0,this.logger.debug("Gemini agent detected as ready for input"),this.sendAgentStatus({agentType:H.GEMINI_CLI,status:L.IDLE,message:"Gemini ready for commands"}))}buildGeminiArgs(e){const t=e.payload?.agentConfig?.args||[],s=e.payload?.agentConfig?.conversationSessionId;return s&&t.push("--session-id",s),t}processDataForOptions(e){this.optionBuffer+=e;const t=le(e);(/Do you want to proceed\?/m.test(t)||/●\s*\d+\.\s+/.test(t)||/\n\s{0,4}\d+\.\s+[^\n]+/.test(t))&&!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=le(this.optionBuffer),t=this.extractOptions(e);t.length&&await this.handleDetectedOptions(t),this.resetOptionState()}resetOptionState(){this.optionBuffer="",this.optionTimeout=null,this.isCollectingOptions=!1}extractOptions(e){const t=[],s=e.split(`
|
|
56
|
+
`);for(const r of s){const a=r.trim();let c=a.match(/^●\s*(\d+)\.\s+(.+)$/);if(c){t.push({number:parseInt(c[1],10),text:c[2].trim(),selected:!0});continue}c=a.match(/^(?:[│|]?\s*)?(\d+)\.\s+(.+)$/),c&&t.push({number:parseInt(c[1],10),text:c[2].trim()})}const i=new Set;return t.filter(r=>i.has(r.number)?!1:(i.add(r.number),!0))}async handleDetectedOptions(e){if(!e.length||!this.agentInfo||!this.httpService)return;const t=new Date().toISOString();try{const s=e.map(a=>({label:a.text,value:a.number,selected:!!a.selected})),i=o.createSelectComponent(s),r=o.createToolInvocationInput(!1,i);await this.httpService.requestApproval(this.agentInfo.agentSessionId,{toolName:"selectOption",toolArgs:{timestamp:t,options:s},input:r}),this.logger.debug("Sent Gemini option selection approval request")}catch(s){this.logger.warn("Failed to send Gemini options approval request",s)}}async writeGeminiExtensionFile(e,t){if(this.logger.debug("writeGeminiExtensionFile called",{rawMcps:e,workingDir:t}),!e)return this.logger.debug("No MCPs provided, returning null"),null;try{const s={};if(Array.isArray(e))for(const p of e){if(!p||typeof p!="object")continue;const E=p.name||p.id||p.key;if(!E)continue;const m={};p.type==="sse"?(m.url=p.url,p.headers&&Object.keys(p.headers).length>0&&(m.headers=p.headers)):(m.command=p.command,p.args&&p.args.length>0&&(m.args=p.args)),p.env&&Object.keys(p.env).length>0&&(m.env=p.env),p.disabled&&(m.disabled=p.disabled),s[E]=m}else if(typeof e=="object"){for(const[p,E]of Object.entries(e))if(E&&typeof E=="object"){const m=E,v={};m.type==="sse"||m.url?(v.url=m.url,m.headers&&Object.keys(m.headers).length>0&&(v.headers=m.headers)):(v.command=m.command,m.args&&m.args.length>0&&(v.args=m.args)),m.env&&Object.keys(m.env).length>0&&(v.env=m.env),m.disabled&&(v.disabled=m.disabled),s[p]=v}}if(Object.keys(s).length===0)return null;const i=await this.findGitRepoRoot(t),r=i||q.homedir();this.logger.debug(`Using base directory for Gemini extension: ${r}`);const a=F.join(r,".gemini","extensions");C.existsSync(a)||(C.mkdirSync(a,{recursive:!0}),this.logger.debug(`Created directory: ${a}`));const c={name:"agiflow-mcps",version:"1.0.0",mcpServers:s,contextFileName:"GEMINI.md",excludeTools:["run_shell_command"]},f=F.join(a,"agiflow-extension.json");return C.writeFileSync(f,JSON.stringify(c,null,2),"utf8"),this.logger.debug(`Gemini extension config written to: ${f}`),this.tempExtensionConfigPath=f,i&&await this.ensureGitignoreEntry(i,".gemini/extensions/agiflow-extension.json"),f}catch(s){return this.logger.warn("Failed to write Gemini extension config file",s),null}}async findGitRepoRoot(e){let t=F.resolve(e);const s=F.parse(t).root;for(;t!==s;){const i=F.join(t,".git");if(C.existsSync(i))return t;t=F.dirname(t)}return null}async ensureGitignoreEntry(e,t){const s=F.join(e,".gitignore");try{let i="";if(C.existsSync(s)&&(i=C.readFileSync(s,"utf8")),i.split(`
|
|
57
|
+
`).some(c=>c.trim()===t))this.logger.debug(`Entry '${t}' already exists in .gitignore`);else{const c=i.endsWith(`
|
|
58
|
+
`)||i===""?i+t+`
|
|
59
|
+
`:i+`
|
|
60
|
+
`+t+`
|
|
61
|
+
`;C.writeFileSync(s,c,"utf8"),this.logger.debug(`Added '${t}' to .gitignore`)}}catch(i){this.logger.warn(`Failed to update .gitignore: ${i instanceof Error?i.message:String(i)}`)}}}class Pr{logger;repositoryPath;originalRepositoryPath;activeWorktrees=new Map;canPush=null;constructor(e,t){if(this.originalRepositoryPath=F.resolve(e),this.repositoryPath=this.originalRepositoryPath,this.logger=t??new o.Logger({verbose:!1}),!this.isGitRepository())throw new Error(`Path ${this.originalRepositoryPath} is not a git repository`)}isGitRepository(){try{let e=F.resolve(this.repositoryPath);const t=F.resolve("/");let s=0;const i=15;for(;e!==t&&s<i;){const r=F.join(e,".git");if(C.existsSync(r))return this.repositoryPath=e,!0;const a=F.resolve(e,"..");if(a===e)break;e=a,s++}return!1}catch{return!1}}execGit(e,t){try{return z.execSync(`git ${e}`,{cwd:t||this.repositoryPath,encoding:"utf8",stdio:"pipe"}).trim()}catch(s){e.includes("diff --cached --exit-code")&&s.status===1||this.logger.error(`Git command failed: git ${e}`,s);const r=new Error(`Git command failed: ${s.message}`);throw r.status=s.status,r.signal=s.signal,r.output=s.output,r}}getCurrentBranch(){return this.execGit("branch --show-current")}getCurrentCommit(){return this.execGit("rev-parse HEAD")}listWorktrees(){try{const e=this.execGit("worktree list --porcelain"),t=[],s=e.split(`
|
|
62
|
+
|
|
63
|
+
`).filter(i=>i.trim());for(const i of s){const r=i.split(`
|
|
64
|
+
`);let a="",c="",h="";for(const f of r)f.startsWith("worktree ")?a=f.substring(9):f.startsWith("branch ")?c=f.substring(7):f.startsWith("HEAD ")&&(h=f.substring(5));a&&t.push({path:a,branch:c||"detached",commit:h,isActive:a===this.repositoryPath,name:F.basename(a)})}return t}catch{return this.logger.debug("No worktrees found or git worktree not supported"),[]}}async createWorktree(e){const{branch:t,worktreeName:s}=e,i=this.repositoryPath,r=F.basename(i),a=t||this.generateUniqueBranchName(),c=this.sanitizeBranchName(a),h=`${r}-worktrees`,f=s||c,p=F.join(this.repositoryPath,".."),E=F.join(p,h),m=F.join(E,f);C.existsSync(E)||await(await import("fs/promises")).mkdir(E,{recursive:!0});try{let v=`worktree add "${m}"`;if(this.isBranchCheckedOutInWorktree(a))throw new Error(`Branch '${a}' is already checked out in another worktree. Use a different branch name or specify a unique branch.`);const _=this.checkBranchExists(`refs/heads/${a}`);let u=!1;_?v+=` ${a}`:(u=this.checkBranchExists(`refs/remotes/origin/${a}`),u?v+=` -b ${a} origin/${a}`:v+=` -b ${a}`),this.logger.info(`Creating worktree at ${m}`),this.execGit(v);const l=this.execGit("rev-parse HEAD",m),g=a||this.execGit("branch --show-current",m),d={path:m,branch:g,commit:l,isActive:!1,name:f};if(this.activeWorktrees.set(f,d),this.logger.success(`Worktree created successfully at ${m}`),!_&&!u)try{this.logger.info(`Pushing new branch ${g} to remote`),this.execGit(`push --set-upstream origin ${g}`,m),this.logger.success(`Branch ${g} pushed to remote`)}catch(D){this.logger.warn(`Could not push branch to remote: ${D.message}`)}return d}catch(v){throw this.logger.error(`Failed to create worktree: ${v.message}`),v}}async commitChanges(e,t,s=!0,i=!1){try{try{this.execGit("clean -fd -e node_modules",e)}catch(a){this.logger.debug("Git clean warning (non-fatal):",a)}s&&(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(a){if(a.status!==1&&a.status!==void 0)throw this.logger.error(`Git diff failed with unexpected status: ${a.status}`),a;this.logger.debug("Changes detected in staging area, proceeding with commit")}const r=i?"--no-verify":"";this.execGit(`commit ${r} -m "${t}"`.trim(),e),this.logger.success(`Changes committed in worktree: ${e}`)}catch(r){throw this.logger.error(`Failed to commit changes: ${r.message}`),r}}async pushChanges(e,t="origin",s){if(!await this.canPushToRemote(t))throw new Error(`Cannot push to remote '${t}' - no valid authentication method found. Please set up SSH keys or store HTTPS credentials.`);try{const r=s||this.execGit("branch --show-current",e);if(!r)throw new Error("No branch to push (detached HEAD)");try{this.logger.debug(`Pushing branch ${r} to ${t}`),this.execGit(`push --set-upstream ${t} ${r}`,e)}catch{try{this.logger.debug(`Retrying push without --set-upstream for ${r}`),this.execGit(`push ${t} ${r}`,e)}catch(c){const h=c.message||"";throw h.includes("permission")||h.includes("denied")?this.logger.error(`Push failed: No permission to push to ${t}/${r}`):h.includes("Could not read from remote repository")?this.logger.error("Push failed: Cannot access remote repository. Check your SSH keys or credentials."):h.includes("does not appear to be a git repository")?this.logger.error(`Push failed: Remote '${t}' is not configured properly`):this.logger.error(`Failed to push branch ${r}: ${h}`),c}}this.logger.success(`Changes pushed to ${t}/${r}`),await this.createPullRequestIfPossible(e,r)}catch(r){throw this.logger.error(`Failed to push changes: ${r.message}`),r}}async commitAndPush(e,t,s="origin",i,r=!1){await this.commitChanges(e,t,!0,r),await this.pushChanges(e,s,i)}async removeWorktree(e,t=!1){try{const s=t?"--force":"";this.execGit(`worktree remove ${s} "${e}"`);for(const[i,r]of this.activeWorktrees.entries())if(r.path===e){this.activeWorktrees.delete(i);break}this.logger.success(`Worktree removed: ${e}`)}catch(s){throw this.logger.error(`Failed to remove worktree: ${s.message}`),s}}switchToWorktree(e){if(!C.existsSync(e))throw new Error(`Worktree path does not exist: ${e}`);try{const t=this.execGit("rev-parse HEAD",e),s=this.execGit("branch --show-current",e),i={path:e,branch:s||"detached",commit:t,isActive:!0,name:F.basename(e)};return this.logger.info(`Switched to worktree: ${e} (${s})`),i}catch(t){throw this.logger.error(`Failed to switch to worktree: ${t.message}`),t}}getWorktreeInfo(e){try{const t=this.execGit("rev-parse HEAD",e),s=this.execGit("branch --show-current",e);return{path:e,branch:s||"detached",commit:t,isActive:!1,name:F.basename(e)}}catch{return null}}async cleanup(e=!0,t="Agent work completed"){this.logger.info("Cleaning up worktrees...");let s=!1;e&&(s=await this.canPushToRemote(),s||this.logger.warn("Cannot push to remote - will only commit changes locally"));for(const[,i]of this.activeWorktrees.entries())try{if(e)try{s?(await this.commitAndPush(i.path,t,"origin",void 0,!0),this.logger.info(`Committed and pushed changes for worktree: ${i.path}`)):(await this.commitChanges(i.path,t,!0,!0),this.logger.info(`Committed changes locally for worktree: ${i.path}`))}catch(r){this.logger.warn(`Failed to commit/push worktree ${i.path}: ${r}`)}await this.removeWorktree(i.path,!0)}catch(r){this.logger.warn(`Failed to remove worktree ${i.path}: ${r}`)}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 t=this.execGit(`remote get-url ${e}`);return t.startsWith("git@")||t.includes("ssh://")?this.canPush=await this.testSshConnection(t):t.startsWith("https://")?this.canPush=await this.testHttpsCredentials(e):(this.logger.warn(`Unknown git remote protocol: ${t}`),this.canPush=!1)}catch(t){return this.logger.debug(`Cannot determine push capability: ${t}`),this.canPush=!1}}async testSshConnection(e){try{const t=e.split("@")[1]?.split(":")[0]||e.split("/")[2];return t?(z.execSync(`ssh -T -o ConnectTimeout=5 -o BatchMode=yes git@${t}`,{stdio:"pipe",timeout:1e4}),!0):!1}catch(t){return t.status===1&&t.stderr?.includes("successfully authenticated")?!0:(this.logger.debug(`SSH test failed: ${t.message}`),!1)}}async testHttpsCredentials(e){try{return z.execSync(`git ls-remote --exit-code ${e} HEAD`,{cwd:this.repositoryPath,stdio:"pipe",timeout:1e4}),!0}catch(t){return this.logger.debug(`HTTPS credentials test failed: ${t}`),!1}}checkBranchExists(e){try{return z.execSync(`git show-ref --verify --quiet ${e}`,{cwd:this.repositoryPath,stdio:"pipe"}),!0}catch{return!1}}isBranchCheckedOutInWorktree(e){try{return this.listWorktrees().some(s=>s.branch===e&&s.path!==this.repositoryPath)}catch{return!1}}generateUniqueBranchName(){const e=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),t=Math.random().toString(36).substring(2,8);return`agent-work-${e}-${t}`}sanitizeBranchName(e){return e.replace(/[^a-zA-Z0-9-_]/g,"-").replace(/--+/g,"-").replace(/^-|-$/g,"").toLowerCase()}isGhCliAvailable(){try{return z.execSync("gh --version",{stdio:"pipe"}),!0}catch{return!1}}getMainBranch(){try{const t=this.execGit("config --get init.defaultBranch").trim();if(t)return t}catch{}try{const t=this.execGit("symbolic-ref refs/remotes/origin/HEAD").trim();if(t)return t.replace("refs/remotes/origin/","")}catch{}const e=["main","master"];for(const t of e)if(this.checkBranchExists(`refs/heads/${t}`)||this.checkBranchExists(`refs/remotes/origin/${t}`))return t;return"main"}async createPullRequestIfPossible(e,t){if(!this.isGhCliAvailable()){this.logger.debug("GitHub CLI not available, skipping PR creation");return}const s=this.getMainBranch();if(t===s){this.logger.debug(`Already on main branch (${s}), skipping PR creation`);return}try{const i=z.execSync(`gh pr list --head "${t}" --json number`,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim(),r=JSON.parse(i||"[]");if(r.length>0){this.logger.info(`Pull request already exists for branch ${t}: #${r[0].number}`);return}let a=`Agent work: ${t}`;t.includes("agent-work")&&(a=`🤖 ${t.replace(/-/g," ").replace("agent work","Agent Work:")}`);const c=`## 🤖 Automated Changes by AI Agent
|
|
65
|
+
|
|
66
|
+
This pull request contains automated changes made by the Agiflow AI Agent.
|
|
67
|
+
|
|
68
|
+
### Branch Information
|
|
69
|
+
- **Source Branch:** \`${t}\`
|
|
70
|
+
- **Target Branch:** \`${s}\`
|
|
71
|
+
- **Created:** ${new Date().toISOString()}
|
|
72
|
+
|
|
73
|
+
### Review Checklist
|
|
74
|
+
- [ ] Code follows project conventions
|
|
75
|
+
- [ ] Tests pass (if applicable)
|
|
76
|
+
- [ ] No security vulnerabilities introduced
|
|
77
|
+
- [ ] Documentation updated (if needed)
|
|
78
|
+
|
|
79
|
+
### Notes
|
|
80
|
+
Please review the changes carefully before merging. The AI agent has attempted to follow best practices, but human review is essential.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
*Generated by [Agiflow Agent](https://agiflow.io)*`,h=`gh pr create --base "${s}" --head "${t}" --title "${a}" --body "${c}"`,f=z.execSync(h,{cwd:e,encoding:"utf8",stdio:"pipe"}).trim();this.logger.success(`Pull request created: ${f}`)}catch(i){i.message?.includes("authentication")||i.message?.includes("gh auth login")?this.logger.warn('GitHub CLI not authenticated. Run "gh auth login" to enable PR creation.'):this.logger.debug(`Could not create PR: ${i.message}`)}}}class Rr{logger;credentialsService;terminationService;gitWorktreeService;currentWorktree;agentHttpService;instance;isTerminating=!1;onFullscreenChange;constructor(e,t,s){this.logger=e??new o.Logger({verbose:!1}),this.credentialsService=new o.CredentialsService,this.terminationService=t??new De(this.logger),this.onFullscreenChange=s;const i=J.VITE_INJECT_AGIFLOW_APP_ENDPOINT;if(!i)throw new Error("VITE_INJECT_AGIFLOW_APP_ENDPOINT is required but not configured");this.agentHttpService=new o.AgentHttpService({apiUrl:i,logger:this.logger,credentials:this.credentialsService}),this.setupTerminationHandlers()}handleInput(e){this.instance.sendInputToAgent(e)}get isFullscreen(){return this.instance?.isFullscreen??!1}setupTerminationHandlers(){this.isTerminating||(this.terminationService.on("daemon:terminating",async()=>{this.logger.info(`Daemon shutting down, terminating agent ${this.instance.getAgentInfo()?.agentSessionId}`);try{this.instance.disconnect()}catch(e){this.logger.error(`Error terminating agent during daemon shutdown: ${e}`)}}),this.terminationService.on("pty:terminated",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&(this.logger.info(`PTY terminated for agent ${e.agentSessionId}, clearing reference`),this.isTerminating=!0)}),this.terminationService.on("agent:cleanup",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&(this.logger.info(`Agent cleanup for ${e.agentSessionId}, clearing reference`),this.isTerminating=!0)}),this.terminationService.on("agent:sigint",e=>{this.instance.getAgentInfo()?.agentSessionId===e.agentSessionId&&this.logger.info(`Agent ${e.agentSessionId} received SIGINT, will be terminated via daemon`)}))}async terminateAgent(){if(this.isTerminating)return this.logger.debug("Agent is already terminating, skipping duplicate termination"),!0;this.logger.info("Starting agent termination process"),this.instance.setFullscreen(!1),this.logger.debug("Agent removed from fullscreen mode");try{this.instance.disconnect(),this.logger.debug("Agent disconnected successfully")}catch(e){this.logger.warn("Error disconnecting agent:",e)}return this.logger.info("Checking for worktree cleanup..."),await this.cleanupWorktrees(),this.logger.info("Agent termination completed"),!0}async launchAgent(e){const{payload:t}=e,{sessionId:s,agentType:i,agentSessionId:r}=t,a=await this.credentialsService.getAgentCreds();this.logger.info(`Launching agent - Type: ${i}, Session: ${s}, AgentSession: ${r}`),!this.gitWorktreeService&&t.agentConfig?.worktree&&await this.initializeGitWorktreeService(e);const c=t.agentConfig?.worktree;let h=t.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(t.agentConfig.workingDirectory):void 0;if(c&&this.gitWorktreeService){let l,g;typeof c=="boolean"&&c||typeof c=="object"&&(l=c.branch,g=c.name);const d=await this.gitWorktreeService.createWorktree({repositoryPath:this.gitWorktreeService.getRepositoryPath(),branch:l,worktreeName:g,logger:this.logger});this.currentWorktree=d,h=d.path,this.logger.success(`Created worktree for agent: ${d.path} (${d.branch})`);try{if(r){const w={worktrees:[{name:d.name,branch:d.branch,path:d.path,createdAt:new Date().toISOString()}],currentSession:r};await this.agentHttpService.updateTaskDevInfo(r,w),this.logger.debug("Updated task devInfo with worktree information");const k=`🌳 Git worktree created for agent session
|
|
84
|
+
- Location: \`${d.path}\`
|
|
85
|
+
- Branch: \`${d.branch}\`
|
|
86
|
+
- Name: ${d.name}`;await this.agentHttpService.createTaskComment(r,k),this.logger.debug("Added task comment about worktree creation");const A={sessionId:r,messageType:"output",content:`Creating git worktree for isolated development:
|
|
87
|
+
• Branch: ${d.branch}
|
|
88
|
+
• Location: ${d.path}
|
|
89
|
+
• 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(D){this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${D}`)}await this.setupWorktree(d.path,this.gitWorktreeService.getRepositoryPath(),r)}const f=i===H.GEMINI_CLI,p=i===H.CLAUDE_CODE;if(!f&&!p)throw this.logger.error(`Unsupported agent type: ${i}`),new Error(`Unsupported agent type: ${i}`);const E={agentType:i,serverUrl:J.VITE_INJECT_AGIFLOW_APP_ENDPOINT,apiUrl:J.VITE_INJECT_AGIFLOW_APP_ENDPOINT,...a,logger:this.logger,credentialsService:this.credentialsService,terminationService:this.terminationService,onFullscreenChange:this.onFullscreenChange,standalone:!1},m=t.agentConfig?.docker===!0,v=t.agentConfig?.autonomous===!0;let _;f?_=new $r(E):p&&(m||v?(this.logger.info("Docker execution requested for Claude agent"),_=new qt({...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")}})):_=new zt(E));const u=f?"Gemini":m?"Claude Docker":"Claude";if(this.logger.debug(`Created ${u} agent instance`),!_)throw new Error(`Sorry, the agent ${u} is not supported!`);return h&&h!==t.agentConfig?.workingDirectory&&e.payload.agentConfig&&(e.payload.agentConfig.workingDirectory=h),await _.launchAgent(e),this.instance=_,this.instance.setFullscreen(!0),this.logger.debug("Agent set to fullscreen mode for stdin handling"),this.logger.success(`Agent launched successfully - AgentSession: ${r}`),_}async initializeGitWorktreeService(e){try{const t=e.payload.agentConfig?.workingDirectory?o.FileSystemUtils.getAbsolutePath(e.payload.agentConfig.workingDirectory):process.cwd();this.gitWorktreeService=new Pr(t,this.logger),this.logger.debug(`Git worktree service initialized for: ${t}`)}catch(t){this.logger.debug(`Git worktree service not available - not in a git repository: ${t}`)}}async createWorktree(e,t){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),null;try{const s=await this.gitWorktreeService.createWorktree({repositoryPath:this.gitWorktreeService.getRepositoryPath(),branch:e,worktreeName:t,logger:this.logger});if(this.currentWorktree=s,this.instance&&this.instance.getAgentInfo()){const r=this.instance.getAgentInfo();r.workingDir=s.path,this.logger.info(`Agent working directory updated to worktree: ${s.path}`);try{const a=r.agentSessionId;if(a){const h={worktrees:[{name:s.name,branch:s.branch,path:s.path,createdAt:new Date().toISOString()}],currentSession:a};await this.agentHttpService.updateTaskDevInfo(a,h),this.logger.debug("Updated task devInfo with worktree information");const f=`🌳 Git worktree created
|
|
90
|
+
- Location: \`${s.path}\`
|
|
91
|
+
- Branch: \`${s.branch}\`
|
|
92
|
+
- Name: ${s.name}`;await this.agentHttpService.createTaskComment(a,f),this.logger.debug("Added task comment about worktree creation");const p={sessionId:a,messageType:"output",content:`Git worktree created:
|
|
93
|
+
• Branch: ${s.branch}
|
|
94
|
+
• Location: ${s.path}
|
|
95
|
+
• The agent is now working in an isolated workspace.`,metadata:{eventType:"worktree_created",worktreePath:s.path,worktreeBranch:s.branch,worktreeName:s.name}};await this.agentHttpService.sendMessage(p),this.logger.debug("Sent message about worktree creation")}}catch(a){this.logger.debug(`Failed to update task devInfo, add comment, or send message: ${a}`)}}this.logger.success(`Created worktree: ${s.path} (${s.branch})`);const i=this.instance?.getAgentInfo()?.agentSessionId;return await this.setupWorktree(s.path,this.gitWorktreeService.getRepositoryPath(),i),s}catch(s){return this.logger.error(`Failed to create worktree: ${s}`),null}}async setupWorktree(e,t,s){try{if(this.logger.info("Setting up worktree with environment files and dependencies..."),s)try{const h={sessionId:s,messageType:"output",content:`🔧 Setting up development environment in the worktree...
|
|
96
|
+
Copying environment files...`,metadata:{eventType:"worktree_setup_start",worktreePath:e}};await this.agentHttpService.sendMessage(h)}catch(h){this.logger.debug(`Failed to send setup start message: ${h}`)}const r=await new We({targetDirectory:e,originalDirectory:t,logger:this.logger}).setup();let a=`✅ Environment setup completed:
|
|
97
|
+
`,c=!1;if(r.envFilesCopied.length>0){const h=r.envFilesCopied.filter(f=>f.copied).length;this.logger.success(`Copied ${h} environment files to worktree`),a+=`• Copied ${h} environment files
|
|
98
|
+
`,c=!0}if(r.errors.length>0&&(this.logger.warn(`Worktree setup completed with ${r.errors.length} errors`),r.errors.forEach(h=>this.logger.debug(`Setup error: ${h}`)),a+=`• ⚠️ ${r.errors.length} setup warnings occurred
|
|
99
|
+
`),s&&c)try{const h={sessionId:s,messageType:"output",content:a+"The workspace is ready for development.",metadata:{eventType:"worktree_setup_complete",worktreePath:e,envFilesCopied:r.envFilesCopied.filter(f=>f.copied).length,errorsCount:r.errors.length}};await this.agentHttpService.sendMessage(h)}catch(h){this.logger.debug(`Failed to send setup complete message: ${h}`)}}catch(i){if(this.logger.error(`Failed to setup worktree: ${i}`),s)try{const r={sessionId:s,messageType:"output",content:`⚠️ Worktree setup encountered issues: ${i}
|
|
100
|
+
The workspace is created but may require manual setup.`,metadata:{eventType:"worktree_setup_error",worktreePath:e,error:String(i)}};await this.agentHttpService.sendMessage(r)}catch(r){this.logger.debug(`Failed to send setup error message: ${r}`)}}}switchToWorktree(e){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),null;try{const t=this.gitWorktreeService.switchToWorktree(e);if(this.currentWorktree=t,this.instance&&this.instance.getAgentInfo()){const s=this.instance.getAgentInfo();s.workingDir=t.path,this.logger.info(`Agent working directory updated to worktree: ${t.path}`)}return this.logger.success(`Switched to worktree: ${t.path} (${t.branch})`),t}catch(t){return this.logger.error(`Failed to switch to worktree: ${t}`),null}}getCurrentWorktree(){return this.currentWorktree}listWorktrees(){return this.gitWorktreeService?this.gitWorktreeService.listWorktrees():[]}async removeWorktree(e,t=!1){if(!this.gitWorktreeService)return this.logger.warn("Git worktree service not available"),!1;try{return await this.gitWorktreeService.removeWorktree(e,t),this.currentWorktree?.path===e&&(this.currentWorktree=void 0),!0}catch(s){return this.logger.error(`Failed to remove worktree: ${s}`),!1}}async commitWorktreeChanges(e,t=!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,t),!0}catch(s){return this.logger.error(`Failed to commit worktree changes: ${s}`),!1}}async pushWorktreeChanges(e="origin",t){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,t),!0}catch(s){return this.logger.error(`Failed to push worktree changes: ${s}`),!1}}async commitAndPushWorktreeChanges(e,t="origin",s){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,t,s),!0}catch(i){return this.logger.error(`Failed to commit and push worktree changes: ${i}`),!1}}async cleanupWorktrees(e=!0,t="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,t),this.currentWorktree=void 0,this.logger.success("Worktrees cleaned up successfully")}catch(s){this.logger.warn(`Error cleaning up worktrees: ${s}`)}}isWorktreeSupported(){return this.gitWorktreeService?.isWorktreeSupported()??!1}getGitWorktreeService(){return this.gitWorktreeService}getAgentHttpService(){return this.agentHttpService}}class Nr{agents=new Map;agentLaunchSemaphore;logger;credentials;constructor(e){this.logger=e.logger,this.agentLaunchSemaphore=new Or(1),this.credentials=e.credentials??new o.CredentialsService}listAgentIds(){return Array.from(this.agents.keys())}getAgent(e){return this.agents.get(e)}getActiveAgent(){return Array.from(this.agents.values()).find(t=>t.isFullscreen)}handleFullscreenChange=(e,t)=>{if(t){for(const[s,i]of this.agents.entries())s!==e&&i.isFullscreen&&(i.instance.setFullscreen(!1,!0),this.logger.debug(`Agent ${s} removed from fullscreen mode`));this.logger.debug(`Agent ${e} is now in fullscreen mode`)}};async stopAgent(e){const t=this.getAgent(e);return t?(t?.terminateAgent(),this.agents.delete(e),!0):!1}async startAgent(e,t){const s=e.payload.agentSessionId;if(this.agentLaunchSemaphore.isLocked(s)){this.logger.warn(`Agent launch already in progress for session: ${s}`),t(e.payload.sessionId,"AGENT_ALREADY_LAUNCHING",`Agent with session ${s} is already being launched`);return}await this.agentLaunchSemaphore.runExclusive(s,async()=>{if(this.getAgent(s)){this.logger.info(`Agent already exists for session: ${s}`);return}this.logger.info("Launching agent:",e.payload.agentType);const r=await this.credentials.getApiKey(),a=await this.credentials.getOrganizationId();if(!r||!a)throw new Error("Missing credentials to launch agent");const c=new Rr(this.logger,void 0,this.handleFullscreenChange);await c.launchAgent(e),this.agents.set(e.payload.agentSessionId,c),this.logger.debug("Waiting for agent PTY to initialize..."),await new Promise(h=>setTimeout(h,1e3)),this.logger.debug("Agent PTY should now be ready for stdin forwarding"),this.logger.success(`Agent launched successfully: ${e.payload.agentSessionId}`)})}}class Br{logger;constructor(e){this.logger=e??new o.Logger({verbose:!1})}async detectAgents(){const e=[{name:H.CLAUDE_CODE,executable:"claude"},{name:H.GEMINI_CLI,executable:"gemini"}],t=[];for(const i of e){const r=await this.detectAgent(i.name,i.executable);t.push(r)}const s=t.filter(i=>i.isInstalled).length;return this.logger.info(`🔍 Agent detection complete: ${s}/${t.length} agents installed`),{availableAgents:t,installedCount:s}}async detectAgent(e,t){let s={name:e,executable:t,isInstalled:!1};try{const i=this.executeCommand(`${t} --version`);if(i){const r=this.executeCommand(`which ${t}`);this.logger.info(`✅ Found ${e}: ${i.trim()}`),s={name:e,executable:t,isInstalled:!0,version:i.trim(),path:r?.trim()}}}catch{try{this.executeCommand(`${t} --help`),this.logger.info(`✅ Found ${e} (version unknown)`),s={name:e,executable:t,isInstalled:!0,version:"unknown"}}catch{this.logger.info(`❌ ${e} not found`)}}return s.isInstalled&&(s.hostAuthed=this.checkHostAuth(e),s.dockerAuthed=this.checkDockerAuth(e),this.logger.info(`🔐 ${e} auth status: host=${s.hostAuthed}, docker=${s.dockerAuthed}`)),s}async isAgentInstalled(e,t){return(await this.detectAgent(e,t)).isInstalled}async getInstalledAgents(){return(await this.detectAgents()).availableAgents.filter(t=>t.isInstalled)}async getAgentTypesForRegistration(){return(await this.getInstalledAgents()).map(t=>({agentType:t.name,hostEnabled:t.hostAuthed??!1,dockerEnabled:t.dockerAuthed??!1,hostAuthed:t.hostAuthed??!1,dockerAuthed:t.dockerAuthed??!1}))}executeCommand(e){try{return z.execSync(e,{encoding:"utf8",stdio:"pipe",timeout:5e3})}catch{return null}}checkHostAuth(e){if(e!==H.CLAUDE_CODE)return!1;const t=q.homedir(),s=q.platform()==="darwin";try{if(s){const i=F.join(t,".claude_tmp.json"),r=F.join(t,".claude_tmp");return C.existsSync(i)||C.existsSync(r)}else{const i=F.join(t,".claude.json"),r=F.join(t,".claude");return C.existsSync(i)||C.existsSync(r)}}catch(i){return this.logger.debug(`Error checking host auth for ${e}:`,i),!1}}checkDockerAuth(e){if(e!==H.CLAUDE_CODE||!this.isDockerAvailableSync())return!1;const t=q.homedir(),s=q.platform()==="darwin";try{if(s){const i=F.join(t,".claude_tmp.json"),r=F.join(t,".claude_tmp");return C.existsSync(i)||C.existsSync(r)}else{const i=F.join(t,".claude.json"),r=F.join(t,".claude");return C.existsSync(i)||C.existsSync(r)}}catch(i){return this.logger.debug(`Error checking Docker auth for ${e}:`,i),!1}}isDockerAvailableSync(){try{return!!this.executeCommand("docker --version")}catch{return!1}}async isDockerAvailable(){try{const e=this.executeCommand("docker --version");if(e)return this.logger.info(`🐳 Docker available: ${e.trim()}`),!0}catch{this.logger.info("🐳 Docker not available")}return!1}async getSystemCapabilities(){const[e,t]=await Promise.all([this.getInstalledAgents(),this.isDockerAvailable()]),s=e.map(i=>({agentType:i.name,hostEnabled:!0,dockerEnabled:t}));return{hostExecution:e.length>0,dockerExecution:t,installedAgents:e,agentTypesForRegistration:s}}}class Jt{options;authService;databaseDeviceId=null;credentials;logger;agentDetection;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new o.CredentialsService,this.logger=e.logger??new o.Logger({verbose:!1}),this.agentDetection=e.agentDetection??new Br(this.logger)}setDatabaseDeviceId(e){this.databaseDeviceId=e}getDatabaseDeviceId(){return this.databaseDeviceId}async getAuthHeaders(){let e=await this.credentials.getApiKey(),t=await this.credentials.getOrganizationId();if((!e||!t)&&this.authService){const i=await this.authService.getValidApiKey();e=i.api_key,t=i.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:t,expiresAt:i.expires_at})}if(e&&t)return this.options.organizationId=t,{"Content-Type":"application/json","x-api-key":e};const s=this.options.authToken;if(!s)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 ${s}`}}async makeAuthenticatedRequest(e,t,s=!0){const i=await fetch(e,t);if(i.status===401&&s&&this.authService&&(await i.text()).includes("Invalid API key")){this.logger.info("🔑 API key expired or invalid, clearing tokens and retrying authentication..."),await this.authService.clearTokens();try{await this.credentials.clear()}catch{}this.logger.info("🔄 Retrying authentication...");const a=await this.getAuthHeaders(),c={...t,headers:{...t.headers,...a}};return await fetch(e,c)}return i.status===429&&this.logger.warn("🚫 Rate limit exceeded, keeping credentials but not retrying"),i}async registerDaemon(){const{deviceGuid:e}=this.options;if(this.authService&&!this.databaseDeviceId){const h=await this.authService.getDeviceId();h&&(this.databaseDeviceId=h,this.logger.info(`📋 Loaded existing device ID from storage: ${this.databaseDeviceId}`))}this.authService&&this.logger.info("🔐 Authenticating via OAuth flow...");const t=await this.getAuthHeaders(),s=this.options.organizationId,i=Lt(),r=process.cwd();this.logger.info("🔍 Detecting available agent types...");const a=await this.agentDetection.getAgentTypesForRegistration();a.length>0?this.logger.info(`✅ Found ${a.length} agent type(s): ${a.map(h=>h.agentType).join(", ")}`):this.logger.warn("⚠️ No agent types detected - daemon will register without agent capabilities");const c={deviceGuid:e,hostname:i.hostname,platform:i.platform,workingDirectory:r,agentTypes:a.length>0?a:void 0};this.logger.info("📝 Registering daemon with API...");try{const h=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/daemons`,{method:"POST",headers:t,body:JSON.stringify(c)});if(!h.ok){const p=await h.text();throw new Error(`Registration failed: ${h.status} ${p}`)}const f=await h.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(h){throw new Error(`Failed to register daemon: ${h instanceof Error?h.message:h}`)}}async sendHeartbeat(e){if(!e){this.logger.warn("⚠️ No daemon registration available for heartbeat");return}try{const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s){this.logger.warn("⚠️ Organization ID not available for heartbeat");return}const i={lastHeartbeat:new Date().toISOString(),status:se.IDLE},r=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/daemons/${e.id}`,{method:"PATCH",headers:t,body:JSON.stringify(i)},!0);if(!r.ok){const a=await r.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to send heartbeat: ${r.status} ${a}`)}}catch(t){this.logger.warn("⚠️ Failed to send heartbeat:",t)}}async unregisterDaemon(e){if(e)try{const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s){this.logger.warn("⚠️ Organization ID not available for unregistration");return}this.logger.info("📝 Unregistering daemon from API...");const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/daemons/${e.id}`,{method:"DELETE",headers:t},!1);if(i.ok)this.logger.success("Daemon unregistered successfully");else{const r=await i.text().catch(()=>"Unknown error");this.logger.warn(`⚠️ Failed to unregister daemon: ${i.status} ${r}`)}}catch(t){this.logger.warn("⚠️ Failed to unregister daemon:",t)}}}class Qt{ws=null;options;callbacks;reconnectTimer=null;isConnected=!1;shouldReconnect=!0;sessionManager;credentials;logger;agentsManager;constructor(e,t={}){this.options={reconnectInterval:5e3,...e},this.callbacks=t,this.sessionManager=e.sessionManager,this.logger=e.logger??new o.Logger({verbose:e.verbose||!1}),this.credentials=e.credentials??new o.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===re.OPEN?this.ws.send(JSON.stringify(e)):this.logger.warn("Cannot send message - WebSocket not connected")}sendError(e,t,s,i){const r=Ot.parse({payload:{sessionId:e,data:s,error:{code:t,message:s,details:i instanceof Error?i.message:i}}});this.sendMessage(r)}async connectToDaemonChannel(e){return new Promise(async(t,s)=>{const{authToken:i,deviceGuid:r}=this.options;if(!e){s(new Error("Daemon must be registered before connecting to daemon channel"));return}let a=await this.credentials.getApiKey(),c=await this.credentials.getOrganizationId();if((!a||!c)&&this.options.authService)try{const m=await this.options.authService.getValidApiKey();a=m.api_key,c=m.organization_id,await this.credentials.setApiKey({apiKey:a,organizationId:c,deviceId:m.device_id})}catch(m){this.logger.warn("Unable to refresh credentials:",m.message)}c||(c=this.options.organizationId),!a&&i&&(a=i);const h=c||this.options.organizationId;if(!h){s(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 p=e.id;f.pathname=`/api/v1/organizations/${h}/daemons/${p}/ws`,f.searchParams.set("clientType","daemon");const E=await this.credentials.buildDeviceAuthHeaders(r);if(!E["x-api-key"]){s(new Error("No API key available for WebSocket connection"));return}this.logger.info(`Connecting to daemon WebSocket: ${f.toString()}`),this.ws=new re(f.toString(),{headers:E}),this.ws.on("open",()=>{this.isConnected=!0,this.logger.info("Daemon WebSocket connection established");const m=Le.parse({payload:{sessionId:r,data:"Daemon ready",status:se.IDLE}});this.sendMessage(m),this.callbacks.onConnect&&this.callbacks.onConnect(),t()}),this.ws.on("message",m=>{try{const v=m.toString(),_=JSON.parse(v);this.handleServerMessage(_)}catch(v){this.logger.error("Failed to parse server message:",v),this.logger.error(`Raw data: ${m.toString()}`)}}),this.ws.on("close",(m,v)=>{this.isConnected=!1,this.logger.info(`Daemon WebSocket disconnected (${m}): ${v}`),this.callbacks.onDisconnect&&this.callbacks.onDisconnect(m,v.toString()),this.shouldReconnect&&this.scheduleReconnect(e)}),this.ws.on("error",m=>{this.logger.error("WebSocket error:",m),this.callbacks.onError&&this.callbacks.onError(m),this.isConnected||s(m)}),setTimeout(()=>{this.isConnected||s(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===O.STATUS&&e.command===y.REQUEST?await this.handleStatusRequest(e):e.eventType===O.START_AGENT&&e.command===y.REQUEST?await this.handleLaunchAgent(e):e.eventType===O.STOP_AGENT&&e.command===y.REQUEST?await this.handleStopAgent(e):e.eventType===O.TERMINATE&&e.command===y.REQUEST?await this.handleTerminateDaemon(e):e.eventType===O.LIST&&e.command===y.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(t){this.logger.error("Failed to process server message:",t),this.sendError(e.payload?.sessionId||"","COMMAND_ERROR","Failed to process server command",t)}}async handleStatusRequest(e){try{const t=xt.parse(e),s=Le.parse({eventType:O.STATUS,command:y.RESPONSE,payload:{sessionId:t.payload.sessionId,timestamp:Date.now(),data:"Daemon is running",status:se.IDLE}});this.sendMessage(s)}catch(t){this.logger.error("Failed to handle daemon status request:",t),this.sendError(e.payload?.sessionId||"","STATUS_REQUEST_FAILED","Failed to handle status request",t)}}async handleLaunchAgent(e){try{const t=Ve.parse(e),s=t.payload.agentSessionId;if(this.agentsManager.getAgent(s))return;this.agentsManager.startAgent(t,r=>{this.logger.warn(`Agent launch already in progress for session: ${s}`),this.sendError(r)})}catch(t){this.logger.error("Failed to launch agent:",t),this.sendError(e.payload?.sessionId||"","LAUNCH_AGENT_FAILED","Failed to launch agent",t)}}async handleStopAgent(e){try{const t=Bt.parse(e),s=t.payload.agentSessionId,i=await this.agentsManager.stopAgent(s),r=Ut.parse({eventType:O.STOP_AGENT,command:y.RESPONSE,payload:{sessionId:t.payload.sessionId,timestamp:Date.now(),data:i?"Agent stopped successfully":"Agent not found",agentSessionId:s,status:i?"stopped":"not_found",message:i?`Agent ${s} has been stopped`:`Agent ${s} was not found`}});this.sendMessage(r),i?this.logger.success(`Agent stopped successfully: ${s}`):this.logger.warn(`Agent not found: ${s}`)}catch(t){this.logger.error("Failed to stop agent:",t),this.sendError(e.payload?.sessionId||"","STOP_AGENT_FAILED","Failed to stop agent",t)}}async handleTerminateDaemon(e){try{const t=$t.parse(e);if(this.logger.info("Received daemon terminate request"),this.ws&&this.ws.readyState===re.OPEN){const s=Pt.parse({payload:{sessionId:t.payload.sessionId,data:"Daemon terminating gracefully"}});this.sendMessage(s),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(s){this.logger.error("Error during graceful shutdown:",s),process.exit(1)}},500);else{this.logger.warn("No onTerminate callback provided, using fallback shutdown");const s=this.sessionManager.getAllSessions();for(const i of s)i.status===L.IDLE&&await this.sessionManager.terminateSession(i.id);setTimeout(()=>{this.disconnect(),this.logger.info("Daemon shutting down..."),process.exit(0)},1e3)}}catch(t){this.logger.error("Failed to handle daemon terminate request:",t),this.sendError(e.payload?.sessionId||"","TERMINATE_DAEMON_FAILED","Failed to terminate daemon",t)}}async handleListAgentSessions(e){try{const t=Rt.parse(e),s=this.sessionManager.getAllSessions(),i=Nt.parse({payload:{sessionId:t.payload.sessionId,data:"Agent sessions list",sessions:s}});this.sendMessage(i)}catch(t){this.logger.error("Failed to handle list agent sessions request:",t),this.sendError(e.payload?.sessionId||"","LIST_SESSIONS_FAILED","Failed to list agent sessions",t)}}getSessionManager(){return this.sessionManager}}class Ur{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||Wt(e.serverUrl)},this.options.deviceGuid=e.deviceGuid||jt(this.options.stableDeviceId!==!1),this.logger=new o.Logger({verbose:this.options.verbose||!1,logFile:this.options.logFile,logDir:this.options.logDir||pn.join(te.tmpdir(),"agiflow-agents","daemon",`session-${process.pid}`),maxFiles:7,maxFileSize:"10m"});const t=this.logger.getLogFilePath();t&&this.logger.info(`Logging to file: ${t}`),this.agentsManager=new Nr({logger:this.logger}),this.logger.debug("Setting up StdinForwarding service..."),this.stdinForwarding=new Vt({logger:this.logger,onData:this.onData.bind(this),onExit:this.onExit.bind(this)}),this.logger.debug("StdinForwarding service initialized"),this.terminationService=new De(this.logger),this.terminationService.registerCallbacks({onPtyTerminated:async s=>{await this.agentsManager.stopAgent(s.agentSessionId)},onAgentTerminated:async s=>{this.logger.info(`Agent ${s.agentSessionId} terminated, cleaning up`),await this.agentsManager.stopAgent(s.agentSessionId)},onDaemonTerminating:async()=>{this.logger.info("Daemon is terminating, preparing cleanup")},onAgentSigint:async s=>{this.logger.info(`Agent ${s.agentSessionId} received SIGINT, stopping agent via daemon`),await this.agentsManager.stopAgent(s.agentSessionId)}}),this.authService=new Ke({...e.options,logger:this.logger}),this.httpService=new Jt({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 Qt({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:s=>this.stop(s)}),this.heartbeat=Ht(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 t=this.agentsManager.getActiveAgent();t?(this.logger.info(`Stopping agent due to exit signal: ${t.instance.getAgentInfo()?.agentSessionId}`),await this.agentsManager.stopAgent(t.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 t=this.agentsManager.getActiveAgent();if(t){const s=t.instance.getAgentInfo();this.logger.debug(`Found active agent: ${s?.agentSessionId}`),this.logger.debug("About to call agentWorker.handleInput..."),t.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(t){this.logger.error("Error in daemon onData:",t)}}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 t;if(this.authService){const s=await this.authService.getValidApiKey();t=s.api_key,this.options.organizationId=s.organization_id}else t=this.options.authToken;if(!t)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(t){throw this.logger.error("Failed to start daemon:",t),t}}async stop(e=!1){if(this.isShuttingDown){this.logger.debug("Already shutting down, skipping duplicate stop call");return}this.isShuttingDown=!0;const t=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 s=this.agentsManager.listAgentIds();s.length>0?(this.logger.info(`Terminating ${s.length} active agent(s)...`),await this.terminationService.shutdownDaemon(s),await this.terminationService.waitForActiveTerminations(),this.logger.info("All agents terminated successfully")):this.logger.info("No active agents to terminate");try{this.daemonRegistration&&this.httpService&&(this.logger.info("Unregistering daemon from backend..."),await this.httpService.unregisterDaemon(this.daemonRegistration),this.logger.info("Daemon unregistered successfully"))}catch(i){this.logger.warn("Failed to unregister daemon (non-fatal):",i)}e?this.logger.info("WebSocket-initiated shutdown, WebSocket will handle its own disconnect"):(this.logger.info("Disconnecting WebSocket..."),this.wsService.disconnect()),this.logger.info("Cleaning up termination service..."),this.terminationService.cleanup(),this.logger.info("Restoring stdio handler to terminal..."),this.stdinForwarding.restore(),this.logger.success("✅ Daemon stopped gracefully"),clearTimeout(t),process.exit(0)}catch(s){this.logger.error("❌ Error during daemon shutdown:",s),clearTimeout(t),process.exit(1)}}getStats(){return{daemonId:this.daemonRegistration?.id,deviceGuid:this.daemonRegistration?.deviceGuid}}getAllSessions(){return this.agentsManager.listAgentIds().map(t=>({id:t,status:"IDLE"}))}async terminateSession(e){this.logger.info(`Terminating session: ${e}`),await this.agentsManager.stopAgent(e)}}class Zt extends fe{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 t=>{try{await this.execute(t)}catch(s){this.handleError(s)}})}async execute(e){const t=e.serverUrl||J.VITE_INJECT_AGIFLOW_APP_ENDPOINT,s=e.apiUrl||J.VITE_INJECT_AGIFLOW_APP_ENDPOINT;t||(this.error("Server URL is required. Provide via --server-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable."),process.exit(1)),s||(this.error("API URL is required. Provide via --api-url or VITE_INJECT_AGIFLOW_APP_ENDPOINT environment variable."),process.exit(1));try{new URL(t)}catch{this.error("Invalid server URL. Must be a valid WebSocket URL (ws:// or wss://)."),process.exit(1)}try{new URL(s)}catch{this.error("Invalid API URL. Must be a valid HTTP URL."),process.exit(1)}const i=e.reconnectInterval?parseInt(e.reconnectInterval,10):5e3;(isNaN(i)||i<1e3)&&(this.error("Invalid reconnect interval. Must be at least 1000ms."),process.exit(1));const r=new Ke({clientId:"agiflow-cli-daemon",baseUrl:s,verbose:e.verbose});let a;try{e.verbose&&console.log("🔐 Authenticating..."),a=await r.getValidApiKey()}catch(f){const p=f instanceof Error?f.message:String(f);p.includes("cancelled by user")?(this.info(`
|
|
101
|
+
Authentication cancelled`),process.exit(0)):(this.error(`Authentication failed: ${p}`),process.exit(1))}const c=new Ur({serverUrl:t,apiUrl:s,authToken:a.api_key,organizationId:a.organization_id,verbose:e.verbose,reconnectInterval:i,stableDeviceId:!e.uniqueInstance,options:{clientId:"agiflow-cli-daemon",baseUrl:s,verbose:e.verbose}}),h=async f=>{console.log(`
|
|
102
|
+
📡 Received ${f}, initiating graceful shutdown...`);try{await c.stop()}catch(p){this.error(`Error during shutdown: ${p}`),process.exit(1)}};process.on("SIGINT",()=>h("SIGINT")),process.on("SIGTERM",()=>h("SIGTERM")),process.on("SIGHUP",()=>h("SIGHUP"));try{await c.start();const f=c.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
|
|
103
|
+
`)}catch(f){this.error(`Failed to connect daemon: ${f}`),process.exit(1)}}}class Xt extends fe{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 t=>{try{await this.execute(t)}catch(s){this.handleError(s)}})}async execute(e){e.verbose&&console.log("🔐 Logging out and cleaning up credentials...");try{if(!await o.FileSystemUtils.exists(o.FileSystemUtils.AGIFLOW_DIR)){this.info("No stored credentials found. You are already logged out.");return}if(e.removeAll)await o.FileSystemUtils.remove(o.FileSystemUtils.AGIFLOW_DIR),e.verbose&&this.info(`Removed entire directory: ${o.FileSystemUtils.AGIFLOW_DIR}`),this.success("Successfully logged out and removed all Agiflow configuration");else{const s=["api-key.json","credentials.json"];let i=0;for(const r of s){const a=require("path").join(o.FileSystemUtils.AGIFLOW_DIR,r);await o.FileSystemUtils.exists(a)&&(await o.FileSystemUtils.remove(a),i++,e.verbose&&this.info(`Removed: ${r}`))}i===0?this.info("No credential files found. You are already logged out."):this.success(`Successfully logged out and removed ${i} credential file(s)`)}}catch(t){const s=t instanceof Error?t.message:String(t);this.error(`Failed to clean up credentials: ${s}`),process.exit(1)}}}class en extends fe{register(e){e.command("router").description("Manage LLM routing configuration for active sessions").option("-v, --verbose","Enable verbose logging").option("--clear","Clear all session routing configurations").action(async t=>{try{await this.execute(t)}catch(s){this.handleError(s)}})}async execute(e){try{if(e.clear){await o.SessionSettingsManager.clearAllSessions(),this.success("All session routing configurations have been cleared.");return}const t=await o.SessionSettingsManager.getAllSessions(),s=Object.keys(t);if(s.length===0){this.warn("No active sessions found."),this.info("Start a Claude agent first using: agiflow claude");return}const i=s.map(p=>{const E=t[p],m=E?.alias||p,v=E?.provider&&E?.model?`${E.provider}/${E.model}${E.reasoningEffort?` (${E.reasoningEffort})`:""}`:"default";return{name:`${m} [${v}]`,value:p,description:`Current routing: ${v}`}}),r=await ve.select({message:"Select a session to configure routing:",choices:i});e.verbose&&this.info(`Selected session: ${r}`);const a=[{name:"Default (Claude)",value:null,description:"Use default Claude routing (no LLM proxy)"},{name:"GPT-5 (Reasoning: High)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"high"},description:"Route to GPT-5 with high reasoning effort"},{name:"GPT-5 (Reasoning: Medium)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"medium"},description:"Route to GPT-5 with medium reasoning effort"},{name:"GPT-5 (Reasoning: Low)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"low"},description:"Route to GPT-5 with low reasoning effort"},{name:"GPT-5 (Reasoning: Minimal)",value:{provider:"chatgpt",model:"gpt-5",reasoningEffort:"minimal"},description:"Route to GPT-5 with minimal reasoning effort"},{name:"GPT-5 Codex (Reasoning: High)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"high"},description:"Route to GPT-5 Codex with high reasoning effort"},{name:"GPT-5 Codex (Reasoning: Medium)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"medium"},description:"Route to GPT-5 Codex with medium reasoning effort"},{name:"GPT-5 Codex (Reasoning: Low)",value:{provider:"chatgpt",model:"gpt-5-codex",reasoningEffort:"low"},description:"Route to GPT-5 Codex with low reasoning effort"}],c=await ve.select({message:"Select LLM routing configuration:",choices:a.map(p=>({name:p.name,value:p.value,description:p.description}))}),h=t[r],f=h?.alias||r;if(c===null){const p={...h?.alias&&{alias:h.alias}};await o.SessionSettingsManager.setSessionSettings(r,p),this.success(`Routing cleared for session "${f}". Using default Claude.`)}else{const p={...c,alias:h?.alias};await o.SessionSettingsManager.setSessionSettings(r,p),this.success(`Routing configured for session "${f}": ${c.provider}/${c.model}${c.reasoningEffort?` (${c.reasoningEffort})`:""}`)}this.info("Note: Restart the agent for changes to take effect.")}catch(t){if(t instanceof Error&&t.message.includes("User force closed")){this.info("Operation cancelled by user");return}throw t}}}yt.config();async function Mr(){const n=new An;n.name("agiflow").description("@agiflowai/agent-cli").option("-v, --verbose","enable verbose logging").option("--debug","enable debug mode");const e=new Yt;"register"in e&&typeof e.register=="function"?e.register(n):n.command("claude").description("Launch Claude Code agent").action(async()=>{await e.run?.([])});const t=new Zt;"register"in t&&typeof t.register=="function"?t.register(n):n.command("connect").description("Connect agent").action(async()=>{await t.run?.([])});const s=new Xt;"register"in s&&typeof s.register=="function"?s.register(n):n.command("logout").description("Logout and clean up credentials").action(async()=>{await s.run?.([])});const i=new en;"register"in i&&typeof i.register=="function"?i.register(n):n.command("router").description("Manage Agiflow routing configuration").action(async()=>{await i.run?.([])});try{await n.parseAsync(process.argv)}catch(r){console.error("[cli] error",r.message),n.opts().debug&&r instanceof Error&&console.error(r.stack),process.exit(1)}}Mr();exports.BaseCommand=fe;exports.ClaudeCommand=Yt;exports.ConfigSchema=Mt;exports.ConnectCommand=Zt;exports.DaemonHttpService=Jt;exports.DaemonWsService=Qt;exports.DeviceCodeAuthService=Ke;exports.LogoutCommand=Xt;exports.RouterCommand=en;exports.config=J;exports.createHeartbeat=Ht;exports.generateDeviceId=jt;exports.getServerUrl=Gt;exports.getSystemInfo=Lt;exports.getWebSocketUrl=vr;exports.httpToWebSocket=wr;exports.webSocketToHttp=Wt;
|
|
104
|
+
//# sourceMappingURL=cli-Cr-ovvgN.js.map
|