bridge-agent 0.1.0-beta.0
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/LICENSE +21 -0
- package/README.md +67 -0
- package/dist/commands/auth.d.ts +1 -0
- package/dist/commands/auth.js +87 -0
- package/dist/commands/start.d.ts +1 -0
- package/dist/commands/start.js +21 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +76 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +345 -0
- package/dist/metrics.d.ts +10 -0
- package/dist/metrics.js +91 -0
- package/dist/pty/agents.d.ts +25 -0
- package/dist/pty/agents.js +108 -0
- package/dist/pty/claude-quota.d.ts +12 -0
- package/dist/pty/claude-quota.js +114 -0
- package/dist/pty/claude-usage.d.ts +5 -0
- package/dist/pty/claude-usage.js +92 -0
- package/dist/pty/manager.d.ts +18 -0
- package/dist/pty/manager.js +125 -0
- package/dist/shared/types.d.ts +142 -0
- package/dist/shared/types.js +1 -0
- package/dist/ws/client.d.ts +3 -0
- package/dist/ws/client.js +925 -0
- package/package.json +54 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var is=Object.create;var Qe=Object.defineProperty;var os=Object.getOwnPropertyDescriptor;var as=Object.getOwnPropertyNames;var ls=Object.getPrototypeOf,cs=Object.prototype.hasOwnProperty;var ds=(r,e)=>()=>(r&&(e=r(r=0)),e);var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),us=(r,e)=>{for(var t in e)Qe(r,t,{get:e[t],enumerable:!0})},hs=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of as(e))!cs.call(r,s)&&s!==t&&Qe(r,s,{get:()=>e[s],enumerable:!(n=os(e,s))||n.enumerable});return r};var _=(r,e,t)=>(t=r!=null?is(ls(r)):{},hs(e||!r||!r.__esModule?Qe(t,"default",{value:r,enumerable:!0}):t,r));var de=E(et=>{var Oe=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},Ze=class extends Oe{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};et.CommanderError=Oe;et.InvalidArgumentError=Ze});var Ce=E(rt=>{var{InvalidArgumentError:fs}=de(),tt=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new fs(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ps(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}rt.Argument=tt;rt.humanReadableArgName=ps});var st=E(zt=>{var{humanReadableArgName:gs}=Ce(),nt=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(s=>!s._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((s,i)=>s.name().localeCompare(i.name())),t}compareOptions(e,t){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(s=>!s.hidden),n=e._getHelpOption();if(n&&!n.hidden){let s=n.short&&e._findOption(n.short),i=n.long&&e._findOption(n.long);!s&&!i?t.push(n):n.long&&!i?t.push(e.createOption(n.long,n.description)):n.short&&!s&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let s=n.options.filter(i=>!i.hidden);t.push(...s)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>gs(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,s)=>Math.max(n,t.subcommandTerm(s).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,s)=>Math.max(n,t.optionTerm(s).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,s)=>Math.max(n,t.argumentTerm(s).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let s=e.parent;s;s=s.parent)n=s.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),s=t.helpWidth||80,i=2,o=2;function c(f,p){if(p){let m=`${f.padEnd(n+o)}${p}`;return t.wrap(m,s-i,n+o)}return f}function a(f){return f.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(i))}let l=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(l=l.concat([t.wrap(d,s,0),""]));let u=t.visibleArguments(e).map(f=>c(t.argumentTerm(f),t.argumentDescription(f)));u.length>0&&(l=l.concat(["Arguments:",a(u),""]));let h=t.visibleOptions(e).map(f=>c(t.optionTerm(f),t.optionDescription(f)));if(h.length>0&&(l=l.concat(["Options:",a(h),""])),this.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(p=>c(t.optionTerm(p),t.optionDescription(p)));f.length>0&&(l=l.concat(["Global Options:",a(f),""]))}let g=t.visibleCommands(e).map(f=>c(t.subcommandTerm(f),t.subcommandDescription(f)));return g.length>0&&(l=l.concat(["Commands:",a(g),""])),l.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,s=40){let i=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",o=new RegExp(`[\\n][${i}]+`);if(e.match(o))return e;let c=t-n;if(c<s)return e;let a=e.slice(0,n),l=e.slice(n).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),d=" ".repeat(n),h="\\s\u200B",g=new RegExp(`
|
|
7
|
+
|.{1,${c-1}}([${h}]|$)|[^${h}]+?([${h}]|$)`,"g"),f=l.match(g)||[];return a+f.map((p,m)=>p===`
|
|
8
|
+
`?"":(m>0?d:"")+p.trimEnd()).join(`
|
|
9
|
+
`)}};zt.Help=nt});var lt=E(at=>{var{InvalidArgumentError:ms}=de(),it=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=ys(e);this.short=n.shortFlag,this.long=n.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(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new ms(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return _s(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ot=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,i=s!==void 0?s:!1;return t.negate===(i===e)}};function _s(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ys(r){let e,t,n=r.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}at.Option=it;at.DualOptions=ot});var Xt=E(Jt=>{function bs(r,e){if(Math.abs(r.length-e.length)>3)return Math.max(r.length,e.length);let t=[];for(let n=0;n<=r.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=r.length;s++){let i=1;r[s-1]===e[n-1]?i=0:i=1,t[s][n]=Math.min(t[s-1][n]+1,t[s][n-1]+1,t[s-1][n-1]+i),s>1&&n>1&&r[s-1]===e[n-2]&&r[s-2]===e[n-1]&&(t[s][n]=Math.min(t[s][n],t[s-2][n-2]+1))}return t[r.length][e.length]}function Ss(r,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=r.startsWith("--");t&&(r=r.slice(2),e=e.map(o=>o.slice(2)));let n=[],s=3,i=.4;return e.forEach(o=>{if(o.length<=1)return;let c=bs(r,o),a=Math.max(r.length,o.length);(a-c)/a>i&&(c<s?(s=c,n=[o]):c===s&&n.push(o))}),n.sort((o,c)=>o.localeCompare(c)),t&&(n=n.map(o=>`--${o}`)),n.length>1?`
|
|
10
|
+
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Jt.suggestSimilar=Ss});var rr=E(tr=>{var ws=require("node:events").EventEmitter,ct=require("node:child_process"),j=require("node:path"),dt=require("node:fs"),x=require("node:process"),{Argument:Es,humanReadableArgName:xs}=Ce(),{CommanderError:ut}=de(),{Help:vs}=st(),{Option:Qt,DualOptions:ks}=lt(),{suggestSimilar:Zt}=Xt(),ht=class r extends ws{constructor(e){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=e||"",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:t=>x.stdout.write(t),writeErr:t=>x.stderr.write(t),getOutHelpWidth:()=>x.stdout.isTTY?x.stdout.columns:void 0,getErrHelpWidth:()=>x.stderr.isTTY?x.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let s=t,i=n;typeof s=="object"&&s!==null&&(i=s,s=null),i=i||{};let[,o,c]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(o);return s&&(a.description(s),a._executableHandler=!0),i.isDefault&&(this._defaultCommandName=a._name),a._hidden=!!(i.noHelp||i.hidden),a._executableFile=i.executableFile||null,c&&a.arguments(c),this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),s?this:a}createCommand(e){return new r(e)}createHelp(){return Object.assign(new vs,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new Es(e,t)}argument(e,t,n,s){let i=this.createArgument(e,t);return typeof n=="function"?i.default(s).argParser(n):i.default(n),this.addArgument(i),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,s]=e.match(/([^ ]+) *(.*)/),i=t??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),i&&o.description(i),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,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(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new ut(e,t,n)),x.exit(e)}action(e){let t=n=>{let s=this.registeredArguments.length,i=n.slice(0,s);return this._storeOptionsAsProperties?i[s]=this:i[s]=this.opts(),i.push(this),e.apply(this,i)};return this._actionHandler=t,this}createOption(e,t){return new Qt(e,t)}_callParseArg(e,t,n,s){try{return e.parseArg(t,n)}catch(i){if(i.code==="commander.invalidArgument"){let o=`${s} ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=s=>[s.name()].concat(s.aliases()),n=t(e).find(s=>this._findCommand(s));if(n){let s=t(this._findCommand(n)).join("|"),i=t(e).join("|");throw new Error(`cannot add command '${i}' as already have command '${s}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let i=e.long.replace(/^--no-/,"--");this._findOption(i)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let s=(i,o,c)=>{i==null&&e.presetArg!==void 0&&(i=e.presetArg);let a=this.getOptionValue(n);i!==null&&e.parseArg?i=this._callParseArg(e,i,a,o):i!==null&&e.variadic&&(i=e._concatValue(i,a)),i==null&&(e.negate?i=!1:e.isBoolean()||e.optional?i=!0:i=""),this.setOptionValueWithSource(n,i,c)};return this.on("option:"+t,i=>{let o=`error: option '${e.flags}' argument '${i}' is invalid.`;s(i,o,"cli")}),e.envVar&&this.on("optionEnv:"+t,i=>{let o=`error: option '${e.flags}' value '${i}' from env '${e.envVar}' is invalid.`;s(i,o,"env")}),this}_optionEx(e,t,n,s,i){if(typeof t=="object"&&t instanceof Qt)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),typeof s=="function")o.default(i).argParser(s);else if(s instanceof RegExp){let c=s;s=(a,l)=>{let d=c.exec(a);return d?d[0]:l},o.default(i).argParser(s)}else o.default(s);return this.addOption(o)}option(e,t,n,s){return this._optionEx({},e,t,n,s)}requiredOption(e,t,n,s){return this._optionEx({mandatory:!0},e,t,n,s)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,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(e=!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=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){x.versions?.electron&&(t.from="electron");let s=x.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=x.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":x.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function i(d,u){let h=j.resolve(d,u);if(dt.existsSync(h))return h;if(s.includes(j.extname(u)))return;let g=s.find(f=>dt.existsSync(`${h}${f}`));if(g)return`${h}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let d;try{d=dt.realpathSync(this._scriptPath)}catch{d=this._scriptPath}c=j.resolve(j.dirname(d),c)}if(c){let d=i(c,o);if(!d&&!e._executableFile&&this._scriptPath){let u=j.basename(this._scriptPath,j.extname(this._scriptPath));u!==this._name&&(d=i(c,`${u}-${e._name}`))}o=d||o}n=s.includes(j.extname(o));let a;x.platform!=="win32"?n?(t.unshift(o),t=er(x.execArgv).concat(t),a=ct.spawn(x.argv[0],t,{stdio:"inherit"})):a=ct.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=er(x.execArgv).concat(t),a=ct.spawn(x.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{x.on(u,()=>{a.killed===!1&&a.exitCode===null&&a.kill(u)})});let l=this._exitCallback;a.on("close",d=>{d=d??1,l?l(new ut(d,"commander.executeSubCommandAsync","(close)")):x.exit(d)}),a.on("error",d=>{if(d.code==="ENOENT"){let u=c?`searched for local subcommand relative to directory '${c}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",h=`'${o}' does not exist
|
|
15
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${u}`;throw new Error(h)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)x.exit(1);else{let u=new ut(1,"commander.executeSubCommandAsync","(error)");u.nestedError=d,l(u)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let s=this._findCommand(e);s||this.help({error:!0});let i;return i=this._chainOrCallSubCommandHook(i,s,"preSubcommand"),i=this._chainOrCall(i,()=>{if(s._executableHandler)this._executeSubCommand(s,t.concat(n));else return s._parseCommand(t,n)}),i}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,s,i)=>{let o=s;if(s!==null&&n.parseArg){let c=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,i,c)}return o};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,s)=>{let i=n.defaultValue;n.variadic?s<this.args.length?(i=this.args.slice(s),n.parseArg&&(i=i.reduce((o,c)=>e(n,c,o),n.defaultValue))):i===void 0&&(i=[]):s<this.args.length&&(i=this.args[s],n.parseArg&&(i=e(n,i,n.defaultValue))),t[s]=i}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,s=[];return this._getCommandAndAncestors().reverse().filter(i=>i._lifeCycleHooks[t]!==void 0).forEach(i=>{i._lifeCycleHooks[t].forEach(o=>{s.push({hookedCommand:i,callback:o})})}),t==="postAction"&&s.reverse(),s.forEach(i=>{n=this._chainOrCall(n,()=>i.callback(i.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let s=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(i=>{s=this._chainOrCall(s,()=>i(this,t))}),s}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},i=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(i,e,t)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(i))s(),this._processArguments(),this.parent.emit(i,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=e.find(i=>n.conflictsWith.includes(i.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],s=t,i=e.slice();function o(a){return a.length>1&&a[0]==="-"}let c=null;for(;i.length;){let a=i.shift();if(a==="--"){s===n&&s.push(a),s.push(...i);break}if(c&&!o(a)){this.emit(`option:${c.name()}`,a);continue}if(c=null,o(a)){let l=this._findOption(a);if(l){if(l.required){let d=i.shift();d===void 0&&this.optionMissingArgument(l),this.emit(`option:${l.name()}`,d)}else if(l.optional){let d=null;i.length>0&&!o(i[0])&&(d=i.shift()),this.emit(`option:${l.name()}`,d)}else this.emit(`option:${l.name()}`);c=l.variadic?l:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let l=this._findOption(`-${a[1]}`);if(l){l.required||l.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${l.name()}`,a.slice(2)):(this.emit(`option:${l.name()}`),i.unshift(`-${a.slice(2)}`));continue}}if(/^--[^=]+=/.test(a)){let l=a.indexOf("="),d=this._findOption(a.slice(0,l));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,a.slice(l+1));continue}}if(o(a)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){t.push(a),i.length>0&&n.push(...i);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){t.push(a),i.length>0&&t.push(...i);break}else if(this._defaultCommandName){n.push(a),i.length>0&&n.push(...i);break}}if(this._passThroughOptions){s.push(a),i.length>0&&s.push(...i);break}s.push(a)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let s=this.options[n].attributeName();e[s]=s===this._versionOptionName?this._version:this[s]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let n=t||{},s=n.exitCode||1,i=n.code||"commander.error";this._exit(s,i,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in x.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,x.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ks(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!t(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=o=>{let c=o.attributeName(),a=this.getOptionValue(c),l=this.options.find(u=>u.negate&&c===u.attributeName()),d=this.options.find(u=>!u.negate&&c===u.attributeName());return l&&(l.presetArg===void 0&&a===!1||l.presetArg!==void 0&&a===l.presetArg)?l:d||o},s=o=>{let c=n(o),a=c.attributeName();return this.getOptionValueSource(a)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},i=`error: ${s(e)} cannot be used with ${s(t)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let s=[],i=this;do{let o=i.createHelp().visibleOptions(i).filter(c=>c.long).map(c=>c.long);s=s.concat(o),i=i.parent}while(i&&!i._enablePositionalOptions);t=Zt(e,s)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",i=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(i,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(i=>{s.push(i.name()),i.alias()&&s.push(i.alias())}),t=Zt(e,s)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let s=this.createOption(t,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${s}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>xs(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=j.basename(e,j.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=s=>this._outputConfiguration.writeErr(s):n=s=>this._outputConfiguration.writeOut(s),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation(n);if(t&&(s=t(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=x.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${n.join("', '")}'`);let s=`${e}Help`;return this.on(s,i=>{let o;typeof t=="function"?o=t({error:i.error,command:i.command}):o=t,o&&i.write(`${o}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function er(r){return r.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",s="9229",i;return(i=e.match(/^(--inspect(-brk)?)$/))!==null?t=i[1]:(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=i[1],/^\d+$/.test(i[3])?s=i[3]:n=i[3]):(i=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=i[1],n=i[3],s=i[4]),t&&s!=="0"?`${t}=${n}:${parseInt(s)+1}`:e})}tr.Command=ht});var or=E(T=>{var{Argument:nr}=Ce(),{Command:ft}=rr(),{CommanderError:Os,InvalidArgumentError:sr}=de(),{Help:Cs}=st(),{Option:ir}=lt();T.program=new ft;T.createCommand=r=>new ft(r);T.createOption=(r,e)=>new ir(r,e);T.createArgument=(r,e)=>new nr(r,e);T.Command=ft;T.Option=ir;T.Argument=nr;T.Help=Cs;T.CommanderError=Os;T.InvalidArgumentError=sr;T.InvalidOptionArgumentError=sr});var pr=E(k=>{"use strict";var pt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Is=pt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=async(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i(await(0,t.stat)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.isexe=n;var s=(c,a={})=>{let{ignoreErrors:l=!1}=a;try{return i((0,e.statSync)(c),a)}catch(d){let u=d;if(l||u.code==="EACCES")return!1;throw u}};r.sync=s;var i=(c,a)=>c.isFile()&&o(c,a),o=(c,a)=>{let l=a.uid??process.getuid?.(),d=a.groups??process.getgroups?.()??[],u=a.gid??process.getgid?.()??d[0];if(l===void 0||u===void 0)throw new Error("cannot get uid or gid");let h=new Set([u,...d]),g=c.mode,f=c.uid,p=c.gid,m=parseInt("100",8),v=parseInt("010",8),I=parseInt("001",8),b=m|v;return!!(g&I||g&v&&h.has(p)||g&m&&f===l||g&b&&l===0)}}),As=pt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.sync=r.isexe=void 0;var e=require("node:fs"),t=require("node:fs/promises"),n=require("node:path"),s=async(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c(await(0,t.stat)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let h=u;if(d||h.code==="EACCES")return!1;throw h}};r.sync=i;var o=(a,l)=>{let{pathExt:d=process.env.PATHEXT||""}=l,u=d.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let h of u){let g=h.toLowerCase(),f=a.substring(a.length-g.length).toLowerCase();if(g&&f===g)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),Ts=pt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),cr=k&&k.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(e,t);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,s)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Ps=k&&k.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),dr=k&&k.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),s=0;s<n.length;s++)n[s]!=="default"&&cr(t,e,n[s]);return Ps(t,e),t}})(),Ns=k&&k.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&cr(e,r,t)};Object.defineProperty(k,"__esModule",{value:!0});k.sync=k.isexe=k.posix=k.win32=void 0;var ur=dr(Is());k.posix=ur;var hr=dr(As());k.win32=hr;Ns(Ts(),k);var Rs=process.env._ISEXE_TEST_PLATFORM_||process.platform,fr=Rs==="win32"?hr:ur;k.isexe=fr.isexe;k.sync=fr.sync});var vr=E((da,xr)=>{var{isexe:Ds,sync:Ls}=pr(),{join:Ms,delimiter:js,sep:gr,posix:mr}=require("path"),_r=process.platform==="win32",yr=new RegExp(`[${mr.sep}${gr===mr.sep?"":gr}]`.replace(/(\\)/g,"\\$1")),Bs=new RegExp(`^\\.${yr.source}`),br=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Sr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=js})=>{let s=r.match(yr)?[""]:[..._r?[process.cwd()]:[],...(e||"").split(n)];if(_r){let i=t||[".EXE",".CMD",".BAT",".COM"].join(n),o=i.split(n).flatMap(c=>[c,c.toLowerCase()]);return r.includes(".")&&o[0]!==""&&o.unshift(""),{pathEnv:s,pathExt:o,pathExtExe:i}}return{pathEnv:s,pathExt:[""]}},wr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&Bs.test(e)?e.slice(0,2):"")+Ms(t,e)},Er=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Sr(r,e),i=[];for(let o of t){let c=wr(o,r);for(let a of n){let l=c+a;if(await Ds(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw br(r)},$s=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Sr(r,e),i=[];for(let o of t){let c=wr(o,r);for(let a of n){let l=c+a;if(Ls(l,{pathExt:s,ignoreErrors:!0})){if(!e.all)return l;i.push(l)}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw br(r)};xr.exports=Er;Er.sync=$s});var B=E((pa,Nr)=>{"use strict";var Tr=["nodebuffer","arraybuffer","fragments"],Pr=typeof Blob<"u";Pr&&Tr.push("blob");Nr.exports={BINARY_TYPES:Tr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Pr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ue=E((ga,Pe)=>{"use strict";var{EMPTY_BUFFER:Ws}=B(),_t=Buffer[Symbol.species];function Fs(r,e){if(r.length===0)return Ws;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new _t(t.buffer,t.byteOffset,n):t}function Rr(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function Dr(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function qs(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function yt(r){if(yt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new _t(r):ArrayBuffer.isView(r)?e=new _t(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),yt.readOnly=!1),e}Pe.exports={concat:Fs,mask:Rr,toArrayBuffer:qs,toBuffer:yt,unmask:Dr};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Pe.exports.mask=function(e,t,n,s,i){i<48?Rr(e,t,n,s,i):r.mask(e,t,n,s,i)},Pe.exports.unmask=function(e,t){e.length<32?Dr(e,t):r.unmask(e,t)}}catch{}});var jr=E((ma,Mr)=>{"use strict";var Lr=Symbol("kDone"),bt=Symbol("kRun"),St=class{constructor(e){this[Lr]=()=>{this.pending--,this[bt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[bt]()}[bt](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Lr])}}};Mr.exports=St});var se=E((_a,Wr)=>{"use strict";var he=require("zlib"),Br=ue(),Vs=jr(),{kStatusCode:$r}=B(),Hs=Buffer[Symbol.species],Gs=Buffer.from([0,0,255,255]),Re=Symbol("permessage-deflate"),$=Symbol("total-length"),re=Symbol("callback"),q=Symbol("buffers"),ne=Symbol("error"),Ne,wt=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ne){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ne=new Vs(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[re];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Ne.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Ne.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?he.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=he.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Re]=this,this._inflate[$]=0,this._inflate[q]=[],this._inflate.on("error",Ys),this._inflate.on("data",Ur)}this._inflate[re]=n,this._inflate.write(e),t&&this._inflate.write(Gs),this._inflate.flush(()=>{let i=this._inflate[ne];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=Br.concat(this._inflate[q],this._inflate[$]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$]=0,this._inflate[q]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?he.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=he.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[$]=0,this._deflate[q]=[],this._deflate.on("data",Ks)}this._deflate[re]=n,this._deflate.write(e),this._deflate.flush(he.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Br.concat(this._deflate[q],this._deflate[$]);t&&(i=new Hs(i.buffer,i.byteOffset,i.length-4)),this._deflate[re]=null,this._deflate[$]=0,this._deflate[q]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Wr.exports=wt;function Ks(r){this[q].push(r),this[$]+=r.length}function Ur(r){if(this[$]+=r.length,this[Re]._maxPayload<1||this[$]<=this[Re]._maxPayload){this[q].push(r);return}this[ne]=new RangeError("Max payload size exceeded"),this[ne].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ne][$r]=1009,this.removeListener("data",Ur),this.reset()}function Ys(r){if(this[Re]._inflate=null,this[ne]){this[re](this[ne]);return}r[$r]=1007,this[re](r)}});var ie=E((ya,De)=>{"use strict";var{isUtf8:Fr}=require("buffer"),{hasBlob:zs}=B(),Js=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Xs(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Et(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Qs(r){return zs&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}De.exports={isBlob:Qs,isValidStatusCode:Xs,isValidUTF8:Et,tokenChars:Js};if(Fr)De.exports.isValidUTF8=function(r){return r.length<24?Et(r):Fr(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");De.exports.isValidUTF8=function(e){return e.length<32?Et(e):r(e)}}catch{}});var Ct=E((ba,zr)=>{"use strict";var{Writable:Zs}=require("stream"),qr=se(),{BINARY_TYPES:ei,EMPTY_BUFFER:Vr,kStatusCode:ti,kWebSocket:ri}=B(),{concat:xt,toArrayBuffer:ni,unmask:si}=ue(),{isValidStatusCode:ii,isValidUTF8:Hr}=ie(),Le=Buffer[Symbol.species],P=0,Gr=1,Kr=2,Yr=3,vt=4,kt=5,Me=6,Ot=class extends Zs{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ei[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ri]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=P}_write(e,t,n){if(this._opcode===8&&this._state==P)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Le(n.buffer,n.byteOffset+e,n.length-e),new Le(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new Le(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case P:this.getInfo(e);break;case Gr:this.getPayloadLength16(e);break;case Kr:this.getPayloadLength64(e);break;case Yr:this.getMask();break;case vt:this.getData(e);break;case kt:case Me:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[qr.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Gr:this._payloadLength===127?this._state=Kr:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Yr:this._state=vt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=vt}getData(e){let t=Vr;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&si(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=kt,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[qr.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===P&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=P;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=xt(n,t):this._binaryType==="arraybuffer"?s=ni(xt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=P):(this._state=Me,setImmediate(()=>{this.emit("message",s,!0),this._state=P,this.startLoop(e)}))}else{let s=xt(n,t);if(!this._skipUTF8Validation&&!Hr(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===kt||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=P):(this._state=Me,setImmediate(()=>{this.emit("message",s,!1),this._state=P,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Vr),this.end();else{let n=e.readUInt16BE(0);if(!ii(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Le(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hr(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=P;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=P):(this._state=Me,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=P,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ti]=s,o}};zr.exports=Ot});var Tt=E((wa,Qr)=>{"use strict";var{Duplex:Sa}=require("stream"),{randomFillSync:oi}=require("crypto"),Jr=se(),{EMPTY_BUFFER:ai,kWebSocket:li,NOOP:ci}=B(),{isBlob:oe,isValidStatusCode:di}=ie(),{mask:Xr,toBuffer:K}=ue(),N=Symbol("kByteLength"),ui=Buffer.alloc(4),je=8*1024,Y,ae=je,D=0,hi=1,fi=2,It=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=D,this.onerror=ci,this[li]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||ui,t.generateMask?t.generateMask(n):(ae===je&&(Y===void 0&&(Y=Buffer.alloc(je)),oi(Y,0,je),ae=0),n[0]=Y[ae++],n[1]=Y[ae++],n[2]=Y[ae++],n[3]=Y[ae++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[N]!==void 0?c=t[N]:(e=Buffer.from(e),c=e.length):(c=e.length,s=t.mask&&t.readOnly&&!o);let a=c;c>=65536?(i+=8,a=127):c>125&&(i+=2,a=126);let l=Buffer.allocUnsafe(s?c+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=a,a===126?l.writeUInt16BE(c,2):a===127&&(l[2]=l[3]=0,l.writeUIntBE(c,4,6)),t.mask?(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],o?[l,e]:s?(Xr(e,n,l,i,c),[l]):(Xr(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=ai;else{if(typeof e!="number"||!di(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+c),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[N]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==D?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):oe(e)?(s=e.size,i=!1):(e=K(e),s=e.length,i=K.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[N]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};oe(e)?this._state!==D?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==D?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):oe(e)?(s=e.size,i=!1):(e=K(e),s=e.length,i=K.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[N]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};oe(e)?this._state!==D?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==D?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Jr.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):oe(e)?(c=e.size,a=!1):(e=K(e),c=e.length,a=K.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=c>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[N]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};oe(e)?this._state!==D?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==D?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[N],this._state=fi,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(At,this,c,s);return}this._bufferedBytes-=n[N];let o=K(i);t?this.dispatch(o,t,n,s):(this._state=D,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(pi,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Jr.extensionName];this._bufferedBytes+=n[N],this._state=hi,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");At(this,a,s);return}this._bufferedBytes-=n[N],this._state=D,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===D&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][N],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][N],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Qr.exports=It;function At(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function pi(r,e,t){At(r,e,t),r.onerror(e)}});var ln=E((Ea,an)=>{"use strict";var{kForOnEventAttribute:fe,kListener:Pt}=B(),Zr=Symbol("kCode"),en=Symbol("kData"),tn=Symbol("kError"),rn=Symbol("kMessage"),nn=Symbol("kReason"),le=Symbol("kTarget"),sn=Symbol("kType"),on=Symbol("kWasClean"),U=class{constructor(e){this[le]=null,this[sn]=e}get target(){return this[le]}get type(){return this[sn]}};Object.defineProperty(U.prototype,"target",{enumerable:!0});Object.defineProperty(U.prototype,"type",{enumerable:!0});var z=class extends U{constructor(e,t={}){super(e),this[Zr]=t.code===void 0?0:t.code,this[nn]=t.reason===void 0?"":t.reason,this[on]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Zr]}get reason(){return this[nn]}get wasClean(){return this[on]}};Object.defineProperty(z.prototype,"code",{enumerable:!0});Object.defineProperty(z.prototype,"reason",{enumerable:!0});Object.defineProperty(z.prototype,"wasClean",{enumerable:!0});var ce=class extends U{constructor(e,t={}){super(e),this[tn]=t.error===void 0?null:t.error,this[rn]=t.message===void 0?"":t.message}get error(){return this[tn]}get message(){return this[rn]}};Object.defineProperty(ce.prototype,"error",{enumerable:!0});Object.defineProperty(ce.prototype,"message",{enumerable:!0});var pe=class extends U{constructor(e,t={}){super(e),this[en]=t.data===void 0?null:t.data}get data(){return this[en]}};Object.defineProperty(pe.prototype,"data",{enumerable:!0});var gi={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[fe]&&s[Pt]===e&&!s[fe])return;let n;if(r==="message")n=function(i,o){let c=new pe("message",{data:o?i:i.toString()});c[le]=this,Be(e,this,c)};else if(r==="close")n=function(i,o){let c=new z("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[le]=this,Be(e,this,c)};else if(r==="error")n=function(i){let o=new ce("error",{error:i,message:i.message});o[le]=this,Be(e,this,o)};else if(r==="open")n=function(){let i=new U("open");i[le]=this,Be(e,this,i)};else return;n[fe]=!!t[fe],n[Pt]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[Pt]===e&&!t[fe]){this.removeListener(r,t);break}}};an.exports={CloseEvent:z,ErrorEvent:ce,Event:U,EventTarget:gi,MessageEvent:pe};function Be(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var $e=E((xa,cn)=>{"use strict";var{tokenChars:ge}=ie();function M(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function mi(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,c,a=-1,l=-1,d=-1,u=0;for(;u<r.length;u++)if(l=r.charCodeAt(u),o===void 0)if(d===-1&&ge[l]===1)a===-1&&(a=u);else if(u!==0&&(l===32||l===9))d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);l===44?(M(e,g,t),t=Object.create(null)):o=g,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===void 0)if(d===-1&&ge[l]===1)a===-1&&(a=u);else if(l===32||l===9)d===-1&&a!==-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),M(t,r.slice(a,d),!0),l===44&&(M(e,o,t),t=Object.create(null),o=void 0),a=d=-1}else if(l===61&&a!==-1&&d===-1)c=r.slice(a,u),a=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(ge[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(ge[l]===1)a===-1&&(a=u);else if(l===34&&a!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&ge[l]===1)a===-1&&(a=u);else if(a!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(a===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=r.slice(a,d);n&&(g=g.replace(/\\/g,""),n=!1),M(t,c,g),l===44&&(M(e,o,t),t=Object.create(null),o=void 0),c=void 0,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(a===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=r.slice(a,d);return o===void 0?M(e,h,t):(c===void 0?M(t,h,!0):n?M(t,c,h.replace(/\\/g,"")):M(t,c,h),M(e,o,t)),e}function _i(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}cn.exports={format:_i,parse:mi}});var qe=E((Oa,wn)=>{"use strict";var yi=require("events"),bi=require("https"),Si=require("http"),hn=require("net"),wi=require("tls"),{randomBytes:Ei,createHash:xi}=require("crypto"),{Duplex:va,Readable:ka}=require("stream"),{URL:Nt}=require("url"),V=se(),vi=Ct(),ki=Tt(),{isBlob:Oi}=ie(),{BINARY_TYPES:dn,CLOSE_TIMEOUT:Ci,EMPTY_BUFFER:Ue,GUID:Ii,kForOnEventAttribute:Rt,kListener:Ai,kStatusCode:Ti,kWebSocket:C,NOOP:fn}=B(),{EventTarget:{addEventListener:Pi,removeEventListener:Ni}}=ln(),{format:Ri,parse:Di}=$e(),{toBuffer:Li}=ue(),pn=Symbol("kAborted"),Dt=[8,13],W=["CONNECTING","OPEN","CLOSING","CLOSED"],Mi=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,S=class r extends yi{constructor(e,t,n){super(),this._binaryType=dn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ue,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),gn(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){dn.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new vi({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new ki(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[C]=this,i[C]=this,e[C]=this,s.on("conclude",$i),s.on("drain",Ui),s.on("error",Wi),s.on("message",Fi),s.on("ping",qi),s.on("pong",Vi),i.onerror=Hi,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",yn),e.on("data",Fe),e.on("end",bn),e.on("error",Sn),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[V.extensionName]&&this._extensions[V.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){A(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),_n(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Lt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ue,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Lt(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ue,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){Lt(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[V.extensionName]||(s.compress=!1),this._sender.send(e||Ue,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){A(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(S,"CONNECTING",{enumerable:!0,value:W.indexOf("CONNECTING")});Object.defineProperty(S.prototype,"CONNECTING",{enumerable:!0,value:W.indexOf("CONNECTING")});Object.defineProperty(S,"OPEN",{enumerable:!0,value:W.indexOf("OPEN")});Object.defineProperty(S.prototype,"OPEN",{enumerable:!0,value:W.indexOf("OPEN")});Object.defineProperty(S,"CLOSING",{enumerable:!0,value:W.indexOf("CLOSING")});Object.defineProperty(S.prototype,"CLOSING",{enumerable:!0,value:W.indexOf("CLOSING")});Object.defineProperty(S,"CLOSED",{enumerable:!0,value:W.indexOf("CLOSED")});Object.defineProperty(S.prototype,"CLOSED",{enumerable:!0,value:W.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(S.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(S.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Rt])return e[Ai];return null},set(e){for(let t of this.listeners(r))if(t[Rt]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[Rt]:!0})}})});S.prototype.addEventListener=Pi;S.prototype.removeEventListener=Ni;wn.exports=S;function gn(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ci,protocolVersion:Dt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!Dt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Dt.join(", ")})`);let i;if(e instanceof Nt)i=e;else try{i=new Nt(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",c=i.protocol==="ws+unix:",a;if(i.protocol!=="ws:"&&!o&&!c?a=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!i.pathname?a="The URL's pathname is empty":i.hash&&(a="The URL contains a fragment identifier"),a){let p=new SyntaxError(a);if(r._redirects===0)throw p;We(r,p);return}let l=o?443:80,d=Ei(16).toString("base64"),u=o?bi.request:Si.request,h=new Set,g;if(s.createConnection=s.createConnection||(o?Bi:ji),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new V({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Ri({[V.extensionName]:g.offer()})),t.length){for(let p of t){if(typeof p!="string"||!Mi.test(p)||h.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(p)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),c){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let f;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let p=n&&n.headers;if(n={...n,headers:{}},p)for(let[m,v]of Object.entries(p))n.headers[m.toLowerCase()]=v}else if(r.listenerCount("redirect")===0){let p=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!p||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),f=r._req=u(s),r._redirects&&r.emit("redirect",r.url,f)}else f=r._req=u(s);s.timeout&&f.on("timeout",()=>{A(r,f,"Opening handshake has timed out")}),f.on("error",p=>{f===null||f[pn]||(f=r._req=null,We(r,p))}),f.on("response",p=>{let m=p.headers.location,v=p.statusCode;if(m&&s.followRedirects&&v>=300&&v<400){if(++r._redirects>s.maxRedirects){A(r,f,"Maximum redirects exceeded");return}f.abort();let I;try{I=new Nt(m,e)}catch{let w=new SyntaxError(`Invalid URL: ${m}`);We(r,w);return}gn(r,I,t,n)}else r.emit("unexpected-response",f,p)||A(r,f,`Unexpected server response: ${p.statusCode}`)}),f.on("upgrade",(p,m,v)=>{if(r.emit("upgrade",p),r.readyState!==S.CONNECTING)return;f=r._req=null;let I=p.headers.upgrade;if(I===void 0||I.toLowerCase()!=="websocket"){A(r,m,"Invalid Upgrade header");return}let b=xi("sha1").update(d+Ii).digest("base64");if(p.headers["sec-websocket-accept"]!==b){A(r,m,"Invalid Sec-WebSocket-Accept header");return}let w=p.headers["sec-websocket-protocol"],y;if(w!==void 0?h.size?h.has(w)||(y="Server sent an invalid subprotocol"):y="Server sent a subprotocol but none was requested":h.size&&(y="Server sent no subprotocol"),y){A(r,m,y);return}w&&(r._protocol=w);let R=p.headers["sec-websocket-extensions"];if(R!==void 0){if(!g){A(r,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let G;try{G=Di(R)}catch{A(r,m,"Invalid Sec-WebSocket-Extensions header");return}let ke=Object.keys(G);if(ke.length!==1||ke[0]!==V.extensionName){A(r,m,"Server indicated an extension that was not requested");return}try{g.accept(G[V.extensionName])}catch{A(r,m,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[V.extensionName]=g}r.setSocket(m,v,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,r):f.end()}function We(r,e){r._readyState=S.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function ji(r){return r.path=r.socketPath,hn.connect(r)}function Bi(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=hn.isIP(r.host)?"":r.host),wi.connect(r)}function A(r,e,t){r._readyState=S.CLOSING;let n=new Error(t);Error.captureStackTrace(n,A),e.setHeader?(e[pn]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(We,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Lt(r,e,t){if(e){let n=Oi(e)?e.size:Li(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${W[r.readyState]})`);process.nextTick(t,n)}}function $i(r,e){let t=this[C];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[C]!==void 0&&(t._socket.removeListener("data",Fe),process.nextTick(mn,t._socket),r===1005?t.close():t.close(r,e))}function Ui(){let r=this[C];r.isPaused||r._socket.resume()}function Wi(r){let e=this[C];e._socket[C]!==void 0&&(e._socket.removeListener("data",Fe),process.nextTick(mn,e._socket),e.close(r[Ti])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function un(){this[C].emitClose()}function Fi(r,e){this[C].emit("message",r,e)}function qi(r){let e=this[C];e._autoPong&&e.pong(r,!this._isServer,fn),e.emit("ping",r)}function Vi(r){this[C].emit("pong",r)}function mn(r){r.resume()}function Hi(r){let e=this[C];e.readyState!==S.CLOSED&&(e.readyState===S.OPEN&&(e._readyState=S.CLOSING,_n(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _n(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function yn(){let r=this[C];if(this.removeListener("close",yn),this.removeListener("data",Fe),this.removeListener("end",bn),r._readyState=S.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[C]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",un),r._receiver.on("finish",un))}function Fe(r){this[C]._receiver.write(r)||this.pause()}function bn(){let r=this[C];r._readyState=S.CLOSING,r._receiver.end(),this.end()}function Sn(){let r=this[C];this.removeListener("error",Sn),this.on("error",fn),r&&(r._readyState=S.CLOSING,this.destroy())}});var kn=E((Ia,vn)=>{"use strict";var Ca=qe(),{Duplex:Gi}=require("stream");function En(r){r.emit("close")}function Ki(){!this.destroyed&&this._writableState.finished&&this.destroy()}function xn(r){this.removeListener("error",xn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Yi(r,e){let t=!0,n=new Gi({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let c=!o&&n._readableState.objectMode?i.toString():i;n.push(c)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(En,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(En,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Ki),n.on("error",xn),n}vn.exports=Yi});var Mt=E((Aa,On)=>{"use strict";var{tokenChars:zi}=ie();function Ji(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&zi[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let c=r.slice(t,n);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}On.exports={parse:Ji}});var Rn=E((Pa,Nn)=>{"use strict";var Xi=require("events"),Ve=require("http"),{Duplex:Ta}=require("stream"),{createHash:Qi}=require("crypto"),Cn=$e(),J=se(),Zi=Mt(),eo=qe(),{CLOSE_TIMEOUT:to,GUID:ro,kWebSocket:no}=B(),so=/^[+/0-9A-Za-z]{22}==$/,In=0,An=1,Pn=2,jt=class extends Xi{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:to,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:eo,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Ve.createServer((n,s)=>{let i=Ve.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=io(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=In}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Pn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(me,this);return}if(e&&this.once("close",e),this._state!==An)if(this._state=An,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(me,this):process.nextTick(me,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{me(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",Tn);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){X(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){X(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!so.test(i)){X(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){X(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){_e(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=Zi.parse(a)}catch{X(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new J({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Cn.parse(d);g[J.extensionName]&&(h.accept(g[J.extensionName]),u[J.extensionName]=h)}catch{X(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(g,f,p,m)=>{if(!g)return _e(t,f||401,p,m);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(h))return _e(t,401)}this.completeUpgrade(u,i,l,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,c){if(!i.readable||!i.writable)return i.destroy();if(i[no])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>In)return _e(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Qi("sha1").update(t+ro).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[J.extensionName]){let u=e[J.extensionName].params,h=Cn.format({[J.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
24
|
+
`).join(`\r
|
|
25
|
+
`)),i.removeListener("error",Tn),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(me,this)})),c(d,s)}};Nn.exports=jt;function io(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function me(r){r._state=Pn,r.emit("close")}function Tn(){this.destroy()}function _e(r,e,t,n){t=t||Ve.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Ve.STATUS_CODES[e]}\r
|
|
26
|
+
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
27
|
+
`)+`\r
|
|
28
|
+
\r
|
|
29
|
+
`+t)}function X(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,X),r.emit("wsClientError",o,t,e)}else _e(t,n,s,i)}});var $n={};us($n,{loadConfig:()=>$t,loadProjectSettings:()=>Wt,saveConfig:()=>Ut});function $t(){let r=F.default.existsSync(He)?He:Bn;F.default.existsSync(r)||(console.error("[bridge] Config not found. Run: bridge-agent auth"),process.exit(1));let e=F.default.readFileSync(r,"utf-8"),t;try{t=JSON.parse(e)}catch{console.error("[bridge] Invalid config file at",Bn),process.exit(1)}(!t||typeof t!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let n=t,s=typeof n.server=="string"?n.server:"",i=typeof n.token=="string"?n.token:"",o=typeof n.name=="string"?n.name:"bridge-agent";return(!s||!i)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1)),{server:s,token:i,name:o}}function Ut(r){let e=ye.default.dirname(He);F.default.existsSync(e)||F.default.mkdirSync(e,{recursive:!0}),F.default.writeFileSync(He,JSON.stringify(r,null,2),{mode:384})}function Wt(r){let e=ye.default.join(r??process.cwd(),".jerico","settings.json");if(!F.default.existsSync(e))return{};try{let t=F.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};return typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent),s.hooks&&typeof s.hooks=="object"&&!Array.isArray(s.hooks)&&(i.hooks=Object.fromEntries(Object.entries(s.hooks).filter(([,o])=>typeof o=="string"))),s.env&&typeof s.env=="object"&&!Array.isArray(s.env)&&(i.env=Object.fromEntries(Object.entries(s.env).filter(([,o])=>typeof o=="string"))),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var F,ye,Bt,He,Bn,Ge=ds(()=>{"use strict";F=_(require("fs")),ye=_(require("path")),Bt=_(require("os")),He=ye.default.join(Bt.default.homedir(),".jerico","settings.json"),Bn=ye.default.join(Bt.default.homedir(),".bridge","config.json")});var ar=_(or(),1),{program:Qo,createCommand:Zo,createArgument:ea,createOption:ta,CommanderError:ra,InvalidArgumentError:na,InvalidOptionArgumentError:sa,Command:lr,Argument:ia,Option:oa,Help:aa}=ar.default;var Zn=require("node:http");var Ar=_(require("node-pty"));var kr=_(vr()),Or=_(require("fs")),Cr=_(require("path")),Ir=_(require("net")),Ie=r=>r+`
|
|
30
|
+
`,Ae=r=>r.replace(/[\r\n]+$/,"")+"\r",te=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:Ie},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>gt(".claude")||ee("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:Ae},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>ee("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:Ae},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>gt(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:Ae},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>ee("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:Ie},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>Us(11434),formatInput:Ie},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>ee("OPENAI_API_KEY")||ee("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:Ie},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>gt(".kimi")||ee("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:Ae}];async function mt(){let r=[];for(let e of te)try{let t=await(0,kr.default)(e.binary),s=await e.checkAuth()?"ok":"missing";r.push({key:e.key,displayName:e.displayName,binaryPath:t,authStatus:s})}catch{}return console.log("[daemon] agent.detect.done",{found:r.map(e=>e.key),missing:te.map(e=>e.key).filter(e=>!r.find(t=>t.key===e))}),r}function gt(r){return Or.default.existsSync(Cr.default.join(process.env.HOME??"",r))}function ee(r){return!!process.env[r]}async function Us(r){return new Promise(e=>{let t=Ir.default.createConnection(r,"127.0.0.1");t.setTimeout(200),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("error",()=>e(!1)),t.on("timeout",()=>{t.destroy(),e(!1)})})}var Te=class{handles=new Map;spawn(e,t,n,s,i,o,c,a,l){this.handles.has(e)&&this.kill(e,!0);let d=Math.max(1,Math.min(500,i)),u=Math.max(1,Math.min(500,o)),h={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(h.BRIDGE_SERVER_URL=l.serverUrl,h.BRIDGE_TOKEN=l.token,h.BRIDGE_WORKSPACE_ID=l.workspaceId,h.BRIDGE_PROJECT_ID=l.projectId,l.projectEnv&&Object.assign(h,l.projectEnv));let g=process.env.BRIDGE_MCP_URL;g&&(h.BRIDGE_MCP_URL=g);let f;try{f=Ar.spawn(n,s,{name:"xterm-256color",cols:d,rows:u,cwd:l?.cwd,env:h})}catch(m){let v=m instanceof Error?m.message:String(m);return console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:v}),!1}let p={agentId:e,agentKey:t,process:f,pid:f.pid,killed:!1};return f.onData(m=>{c(Buffer.from(m).toString("base64"))}),f.onExit(({exitCode:m,signal:v})=>{p.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:m,signal:v}),a(m??null,v?String(v):null))}),this.handles.set(e,p),console.log("[daemon] pty.spawn.success",{agentId:e,agentKey:t,args:s,cwd:l?.cwd}),!0}write(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Buffer.from(t,"base64").toString(),o=te.find(a=>a.key===s.agentKey),c=n==="orchestrator"&&o?.formatInput?o.formatInput(i):i;s.process.write(c)}kill(e,t=!1){let n=this.handles.get(e);if(!n)return;n.killed=!0,this.handles.delete(e);let s=n.pid;if(t){try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}setTimeout(()=>{try{process.kill(-s,"SIGKILL")}catch{}},2e3)}else try{process.kill(-s,"SIGTERM")}catch{n.process.kill()}console.log("[daemon] pty.kill",{agentId:e,force:t})}resize(e,t,n){let s=this.handles.get(e);if(!s)return;let i=Math.max(1,Math.min(500,t)),o=Math.max(1,Math.min(500,n));s.process.resize(i,o)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}};var oo=_(kn(),1),ao=_($e(),1),lo=_(se(),1),co=_(Ct(),1),uo=_(Tt(),1),ho=_(Mt(),1),Dn=_(qe(),1),fo=_(Rn(),1);var O=Dn.default;var Z=_(require("fs")),L=_(require("path")),xe=_(require("os")),Gt=require("node:child_process"),zn=require("node:crypto");var Ln=r=>r;var Mn=r=>r,jn=r=>r;Ge();var be=_(require("fs")),Ft=_(require("path")),Un=_(require("os")),po=2e5;function go(r){let e=Ft.default.join(Un.default.homedir(),".claude","projects");if(be.default.existsSync(e))try{let t=be.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=Ft.default.join(e,n.name,`${r}.jsonl`);if(be.default.existsSync(s))return s}}catch{}}function mo(r){try{let t=be.default.readFileSync(r,"utf-8").trim().split(`
|
|
31
|
+
`);for(let n=t.length-1;n>=0;n--){let s=t[n]?.trim();if(s)try{let i=JSON.parse(s),o=i.message?.usage??i.usage;if(!o||typeof o!="object")continue;let c=o,a=(c.input_tokens??0)+(c.cache_creation_input_tokens??0)+(c.cache_read_input_tokens??0);if(a===0)continue;return{usedPct:Math.min(100,Math.round(a/po*100)),usedTokens:a}}catch{continue}}}catch{}return null}function qt(r,e,t){let n,s=-1,i=()=>{if(n||(n=go(e)),!n)return;let a=mo(n);a&&a.usedTokens!==s&&(s=a.usedTokens,t(r,a.usedPct,a.usedTokens))},o=setTimeout(i,2e3),c=setInterval(i,3e3);return()=>{clearTimeout(o),clearInterval(c)}}var H=_(require("fs")),Se=_(require("path")),Vt=_(require("os")),Wn=300*60*1e3,Fn={free:10,pro:40,max_5x:200,max_20x:200};function _o(){let r=Se.default.join(Vt.default.homedir(),".jerico","settings.json");try{if(!H.default.existsSync(r))return"pro";let t=JSON.parse(H.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in Fn)return t}catch{}return"pro"}function yo(){let r=Se.default.join(Vt.default.homedir(),".claude","projects");if(!H.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-Wn,n=1/0,s=0;try{let o=H.default.readdirSync(r,{withFileTypes:!0}).filter(c=>c.isDirectory());for(let c of o){let a=Se.default.join(r,c.name),l;try{l=H.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of l){let u=Se.default.join(a,d),h;try{if(H.default.statSync(u).size>20*1024*1024)continue;h=H.default.readFileSync(u,"utf-8")}catch{continue}for(let g of h.split(`
|
|
32
|
+
`)){let f=g.trim();if(f)try{let p=JSON.parse(f);if(p.type!=="user"||p.message?.role!=="user"||p.userType!==void 0&&p.userType!=="external")continue;let v=p.timestamp;if(typeof v!="string")continue;let I=Date.parse(v);if(isNaN(I)||I<t)continue;s++,I<n&&(n=I)}catch{continue}}}}}catch{}let i=isFinite(n)?n+Wn:0;return{prompts5h:s,resetAt:i}}function qn(r){let e=()=>{let n=_o(),s=Fn[n]??40,{prompts5h:i,resetAt:o}=yo();r({prompts5h:i,limit5h:s,resetAt:o,tier:n})};try{e()}catch(n){console.warn("[quota] initial poll failed",n)}let t=setInterval(()=>{try{e()}catch{}},6e4);return()=>clearInterval(t)}var Ye=_(require("os")),Ke=_(require("fs")),Hn=require("node:child_process");function Gn(){let r=0,e=0;for(let t of Ye.default.cpus())r+=t.times.idle,e+=t.times.user+t.times.nice+t.times.sys+t.times.idle+(t.times.irq??0);return{idle:r,total:e}}var Ht=Gn();function bo(){let r=Gn(),e=r.idle-Ht.idle,t=r.total-Ht.total;return Ht=r,t===0?0:Math.round((1-e/t)*100)}function So(){let r=Ye.default.totalmem(),e=Ye.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024)}}function wo(){try{let r=(0,Hn.spawnSync)("pmset",["-g","batt"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(r.status!==0||!r.stdout)return;let e=r.stdout.match(/(\d+)%;\s*(charging|discharging|charged|finishing charge)/i);if(!e)return;let t=parseInt(e[1],10),n=/charging|charged|finishing/i.test(e[2]);return{percent:t,charging:n}}catch{return}}function Eo(){try{let r="/sys/class/power_supply",e=Ke.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(Ke.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=Ke.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function Vn(){let r=process.platform;if(r==="darwin")return wo();if(r==="linux")return Eo()}var xo=1e4,vo=3;function Kn(r){let e=0,t=Vn(),n=setInterval(()=>{e++,e%vo===0&&(t=Vn());let s=So();r({cpu:bo(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,battery:t})},xo);return()=>clearInterval(n)}var Q=new Map,ko=r=>r.replace(/[\r\n]+$/,"")+"\r",Kt=null,Oo=qn(r=>{Kt=r}),Co=3e4,Io=5e3,Ao=400;function To(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function Po(r,e=Ao){return r.length<=e?r:`${r.slice(0,e)}...`}function No(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function Je(){let r=Z.default.realpathSync(process.argv[1]??""),e=L.default.dirname(r);return[L.default.resolve(e,"../../mcp-server/dist/index.cjs"),L.default.resolve(e,"bridge-mcp.cjs"),L.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>Z.default.existsSync(n))??"bridge-mcp"}function Ro(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:Je(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=L.default.join(xe.default.tmpdir(),`bridge-mcp-${r.agentId??r.projectId}.json`);return Z.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
33
|
+
`,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config",n]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var Do={bridge_get_project:"Project metadata: name, cwd, machineId",bridge_get_plan:"Read project spec/description",bridge_update_plan:"Update project spec/description",bridge_get_project_history:"Past run history and failure patterns",bridge_get_execution_status:"Run history with todo completion counts",bridge_get_todos:"List todos + session state for this project",bridge_add_todo:"Create a new todo (title, todoType, dependsOn)",bridge_update_todo:"Update a todo title or status",bridge_cancel_run:"Cancel active run (use before restarting a stale plan)",bridge_list_agents:"All agents: role, status, inRun flag",bridge_get_agent_status:"Single agent status check",bridge_spawn_worker:"Spawn a new worker agent (agentKey, role)",bridge_kill_agent:"Terminate a stuck or dead agent",bridge_get_agent_output:"Read terminal output of any agent",bridge_send_input:"Send text input to an agent PTY",bridge_get_my_task:"Get the task assigned to this agent",bridge_complete_task:"Signal task completion",bridge_fail_task:"Signal task failure with a specific reason",bridge_get_todo_context:"Read todo output/error for a specific todo",bridge_assign_task:"Assign a pending todo to a specific agent"};function we(...r){return`
|
|
34
|
+
|
|
35
|
+
**Available MCP tools:** ${r.join(", ")}`}function Lo(...r){return`
|
|
36
|
+
|
|
37
|
+
## Tool reference (only call tools listed here)
|
|
38
|
+
|
|
39
|
+
| Tool | Purpose |
|
|
40
|
+
|------|---------|
|
|
41
|
+
${r.map(t=>`| \`${t}\` | ${Do[t]} |`).join(`
|
|
42
|
+
`)}`}var Jn={developer:`# Bridge Worker \u2014 Developer Role
|
|
43
|
+
|
|
44
|
+
You are a **Developer** worker in a multi-agent orchestration system called Bridge.
|
|
45
|
+
|
|
46
|
+
**Your responsibilities:**
|
|
47
|
+
- Implement assigned tasks completely and correctly \u2014 no stubs, no TODOs
|
|
48
|
+
- Work inside the project working directory
|
|
49
|
+
- Run existing tests after changes and fix any failures
|
|
50
|
+
- Read dependency outputs with \`bridge_get_todo_context\` before starting a task
|
|
51
|
+
- Signal completion with \`bridge_complete_task\`, failure with \`bridge_fail_task\` + reason
|
|
52
|
+
- After making changes, check the runner agent (role:'runner' in bridge_list_agents) for build errors: bridge_get_agent_output(runnerAgentId)
|
|
53
|
+
- Trigger hot reload after file changes: bridge_send_input(runnerAgentId, "r")
|
|
54
|
+
|
|
55
|
+
${we("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,reviewer:`# Bridge Worker \u2014 Reviewer Role
|
|
56
|
+
|
|
57
|
+
You are a **Quality-Obsessed Tech Lead** reviewing code changes in a multi-agent system called Bridge.
|
|
58
|
+
Your identity: Agile, pragmatic, anti-fragile. You ship with confidence or you send it back.
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Workflow
|
|
63
|
+
|
|
64
|
+
### Step 1 \u2014 Load context
|
|
65
|
+
1. Call \`bridge_get_my_task\` \u2014 understand what this review covers
|
|
66
|
+
2. Call \`bridge_get_todo_context\` on ALL dependency task IDs \u2014 read what the developer produced
|
|
67
|
+
3. Read the actual changed files in the codebase (Glob, Grep, Read)
|
|
68
|
+
|
|
69
|
+
### Step 2 \u2014 Pareto scan (do this first)
|
|
70
|
+
Identify the 20% of changes that carry 80% of the risk:
|
|
71
|
+
- New external interfaces (API endpoints, public functions, exports)
|
|
72
|
+
- State mutations (DB writes, file I/O, global state)
|
|
73
|
+
- Error handling paths and fallbacks
|
|
74
|
+
- Auth, validation, and input boundaries
|
|
75
|
+
Focus your deep review on these. Skim the rest.
|
|
76
|
+
|
|
77
|
+
### Step 3 \u2014 Review lenses (apply all, in order)
|
|
78
|
+
|
|
79
|
+
**Principles (KISS \xB7 DRY \xB7 SOLID \xB7 YAGNI)**
|
|
80
|
+
- Is the solution simpler than it needs to be, or over-engineered?
|
|
81
|
+
- Is logic duplicated that should be shared?
|
|
82
|
+
- Are responsibilities clearly separated (single responsibility)?
|
|
83
|
+
- Is anything implemented "for the future" with no current use?
|
|
84
|
+
|
|
85
|
+
**Chaos Engineering lens**
|
|
86
|
+
- What happens when a dependency (DB, API, file system) is unavailable?
|
|
87
|
+
- What happens under partial failure \u2014 does the system leave inconsistent state?
|
|
88
|
+
- Are retries safe? Is idempotency guaranteed for mutations?
|
|
89
|
+
- Are resources (connections, file handles, timers) properly disposed on failure paths?
|
|
90
|
+
|
|
91
|
+
**Safety & correctness**
|
|
92
|
+
- Fail fast: are invalid states caught at entry points, not deep in logic?
|
|
93
|
+
- Strict types: no implicit any, no unchecked casts, no dynamic keys without guards
|
|
94
|
+
- Are all async paths awaited? Are race conditions possible?
|
|
95
|
+
- Edge cases: empty input, null/undefined, zero, max values, concurrent calls
|
|
96
|
+
|
|
97
|
+
**Security**
|
|
98
|
+
- Assume all external input is malicious \u2014 is it sanitized before use?
|
|
99
|
+
- SQL/command/template injection vectors?
|
|
100
|
+
- Are secrets never logged or exposed in error messages?
|
|
101
|
+
- Auth checks before data access, not after?
|
|
102
|
+
|
|
103
|
+
**Observability**
|
|
104
|
+
- Does every failure path emit a structured log with enough context to debug?
|
|
105
|
+
- Are errors surfaced to the caller or silently swallowed?
|
|
106
|
+
- Is there a way to trace what happened without a debugger?
|
|
107
|
+
|
|
108
|
+
### Step 4 \u2014 Follow the dependency chain
|
|
109
|
+
- Pull the output of each dependency todo via \`bridge_get_todo_context\`
|
|
110
|
+
- Verify the developer actually used the context from prior tasks correctly
|
|
111
|
+
- Check that interfaces between tasks are consistent (types match, contracts hold)
|
|
112
|
+
|
|
113
|
+
### Step 5 \u2014 Compile & runtime check
|
|
114
|
+
Detect the stack and run the appropriate compile/typecheck/lint/test commands.
|
|
115
|
+
Do NOT approve if any check fails. Do NOT skip this step.
|
|
116
|
+
If a runner agent exists (bridge_list_agents \u2192 role:'runner'), call bridge_get_agent_output to verify the app still builds and runs after changes.
|
|
117
|
+
|
|
118
|
+
### Step 6 \u2014 Verdict
|
|
119
|
+
|
|
120
|
+
**Approve** (\`bridge_complete_task\`) only when:
|
|
121
|
+
- All lenses pass or issues are trivial cosmetic nits
|
|
122
|
+
- Compile check is clean
|
|
123
|
+
|
|
124
|
+
**Reject** (\`bridge_fail_task\`) with a specific, actionable message:
|
|
125
|
+
- Quote the file + line number
|
|
126
|
+
- State what is wrong and why
|
|
127
|
+
- State the approach to fix it \u2014 not the exact code, but the direction (e.g. "validate before accessing, not after" not "write this exact line")
|
|
128
|
+
- Do NOT reject for style preferences \u2014 only for correctness, safety, resilience, or security issues
|
|
129
|
+
|
|
130
|
+
**Retry limit:** If the same issue persists after 2 retries, approve with a documented caveat in your completion message rather than blocking indefinitely.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Rules
|
|
135
|
+
- Never fix the code yourself \u2014 only review and report
|
|
136
|
+
- One \`bridge_fail_task\` per review cycle \u2014 consolidate all issues into a single message
|
|
137
|
+
- If unsure whether something is a bug or intentional design: flag it as a question, don't reject
|
|
138
|
+
|
|
139
|
+
${we("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_get_todos","bridge_list_agents","bridge_get_agent_output")}`,planner:`# Bridge Worker \u2014 Planner Role
|
|
140
|
+
|
|
141
|
+
You are a **Planner** in Bridge. Your job: understand the project, listen to the user, then create a well-structured and verified execution plan.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## Workflow
|
|
146
|
+
|
|
147
|
+
### Phase 1 \u2014 Load context
|
|
148
|
+
Call all three tools (can be parallel):
|
|
149
|
+
1. \`bridge_get_plan\` \u2014 project spec and goals
|
|
150
|
+
2. \`bridge_get_project_history\` \u2014 past runs, successes, failures
|
|
151
|
+
3. \`bridge_get_todos\` \u2014 currently open todos
|
|
152
|
+
|
|
153
|
+
Then ask the user what they want to work on. Wait for their answer.
|
|
154
|
+
|
|
155
|
+
### Phase 1.5 \u2014 Ambiguity check (after user responds, before planning)
|
|
156
|
+
|
|
157
|
+
Evaluate the user's task against these criteria:
|
|
158
|
+
|
|
159
|
+
**CLEAR \u2014 skip to Phase 2 immediately if ALL of these hold:**
|
|
160
|
+
- A specific component, file, endpoint, or UI element is named
|
|
161
|
+
- The outcome is observable (passes tests, renders on page, endpoint returns X)
|
|
162
|
+
- No vague scope verbs without a target: "improve", "refactor", "optimize", "clean up"
|
|
163
|
+
|
|
164
|
+
**AMBIGUOUS \u2014 ask ONE targeted question if any of these apply:**
|
|
165
|
+
- Multiple layers could be the target (server vs daemon vs web UI)
|
|
166
|
+
- Success criteria are unclear (what does "faster" or "better" mean here?)
|
|
167
|
+
- A named tool/library is requested but its scope is open (e.g. "add Sentry" \u2014 errors only? performance? which layer?)
|
|
168
|
+
|
|
169
|
+
**How to ask (if needed):**
|
|
170
|
+
- Forced-choice format: "Are we targeting (a) [X] or (b) [Y]?"
|
|
171
|
+
- Include concrete options drawn from the project context you just loaded
|
|
172
|
+
- Do NOT ask: "What exactly do you mean?" \u2014 too open, wastes a turn
|
|
173
|
+
- Do NOT ask multiple questions at once
|
|
174
|
+
|
|
175
|
+
**After the user's ONE clarifying response:**
|
|
176
|
+
- Proceed to Phase 2 immediately \u2014 no more questions
|
|
177
|
+
- If still unclear, state your assumption explicitly: "I'll proceed assuming [X]. Let me know if that's wrong."
|
|
178
|
+
|
|
179
|
+
### Phase 2 \u2014 Plan & create todos (triggered after user specifies the task)
|
|
180
|
+
|
|
181
|
+
**Step A \u2014 False positive check (MANDATORY)**
|
|
182
|
+
For any feature or area the user mentions that appears "completed" in history:
|
|
183
|
+
- Search the codebase (Glob, Grep, Read) to confirm it actually exists in code
|
|
184
|
+
- If "completed" but missing from code \u2192 it needs a new todo, note the discrepancy
|
|
185
|
+
- If a pending todo is already fully implemented \u2192 close it: \`bridge_complete_task\` with that todo's ID
|
|
186
|
+
Past runs can lie. Always verify before trusting history.
|
|
187
|
+
|
|
188
|
+
**Step B \u2014 Gap analysis (MANDATORY)**
|
|
189
|
+
For the scope the user requested, compare plan goals vs verified-done vs open todos:
|
|
190
|
+
- \u2705 Done (verified in Step A)
|
|
191
|
+
- \u{1F504} In progress (open todos)
|
|
192
|
+
- \u274C Missing (in plan, no todo, not implemented)
|
|
193
|
+
Show this to the user before creating anything.
|
|
194
|
+
|
|
195
|
+
**Step C \u2014 Confirm scope**
|
|
196
|
+
Based on the gap analysis, confirm with the user exactly what to create todos for.
|
|
197
|
+
Do NOT create todos before this confirmation.
|
|
198
|
+
|
|
199
|
+
**Step D \u2014 Create todos**
|
|
200
|
+
For each subtask (3\u201310 todos):
|
|
201
|
+
- Call \`bridge_add_todo\` with: title, description, todoType, dependsOn
|
|
202
|
+
- **Do not set estimatedAgent** \u2014 it is set automatically from todoType (\`infra\` \u2192 \`sh\`, others \u2192 \`claude\`)
|
|
203
|
+
- **todoType determines who does the work:**
|
|
204
|
+
- \`implementation\` \u2192 developer worker
|
|
205
|
+
- \`review\` \u2192 reviewer worker (validation, QA, sign-off)
|
|
206
|
+
- \`infra\` \u2192 infra/shell worker (migrations, scripts, CI)
|
|
207
|
+
- \`planning\` \u2192 meta tasks (specs, design decisions)
|
|
208
|
+
- **description**: include relevant file paths, expected inputs/outputs, what the worker needs from prior todos \u2014 workers only see title + description
|
|
209
|
+
- **dependsOn**: set when a task needs a prior task's output; omit for parallel tasks
|
|
210
|
+
|
|
211
|
+
**Step E \u2014 Dependency chain validation (MANDATORY)**
|
|
212
|
+
After all todos are created:
|
|
213
|
+
- Identify all leaf todos (nothing else depends on them)
|
|
214
|
+
- Every leaf must be covered by a \`review\` todo that depends on it
|
|
215
|
+
- If any leaf is uncovered \u2192 add a review todo now
|
|
216
|
+
- Verify: no circular dependencies, no orphaned chains
|
|
217
|
+
|
|
218
|
+
**Step F \u2014 Final summary**
|
|
219
|
+
Show the complete todo list with types and dependency chain. Then stop.
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
## Rules
|
|
224
|
+
- Never implement anything yourself
|
|
225
|
+
- You MAY read the codebase during Steps A\u2013B \u2014 this is required, not optional
|
|
226
|
+
- To close a stale open todo that's already done: \`bridge_complete_task\` with its ID
|
|
227
|
+
- Todo titles must be specific: name the files, endpoints, components \u2014 no vague verbs
|
|
228
|
+
|
|
229
|
+
${we("bridge_get_plan","bridge_get_project_history","bridge_get_todos","bridge_add_todo","bridge_complete_task","bridge_fail_task")}`,executor:`# Bridge Worker \u2014 Executor Role
|
|
230
|
+
|
|
231
|
+
You are an **Executor** worker in a multi-agent orchestration system called Bridge.
|
|
232
|
+
|
|
233
|
+
**Your responsibilities:**
|
|
234
|
+
- Run the specified commands, scripts, or CLI tools exactly as described in the task
|
|
235
|
+
- Use \`bridge_get_todo_context\` to fetch artefacts from dependencies (file paths, config, etc.)
|
|
236
|
+
- Capture and report all relevant output
|
|
237
|
+
- Call \`bridge_complete_task\` on success, \`bridge_fail_task\` with error details on failure
|
|
238
|
+
|
|
239
|
+
${we("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context","bridge_list_agents","bridge_get_agent_output","bridge_send_input")}`,shell:`# Bridge Worker \u2014 Shell Role
|
|
240
|
+
|
|
241
|
+
You are a **Shell** worker in a multi-agent orchestration system called Bridge.
|
|
242
|
+
|
|
243
|
+
**Your responsibilities:**
|
|
244
|
+
- Execute shell commands given in each task title directly and faithfully
|
|
245
|
+
- Do not modify, interpret, or add to the command unless it clearly contains a typo
|
|
246
|
+
- Call \`bridge_complete_task\` when the command exits cleanly
|
|
247
|
+
- Call \`bridge_fail_task\` with the error output if the command fails
|
|
248
|
+
|
|
249
|
+
${we("bridge_get_my_task","bridge_complete_task","bridge_fail_task")}`,orchestrator:`# Bridge Orchestrator
|
|
250
|
+
|
|
251
|
+
You are a **Bridge Orchestrator**. Your sole purpose is to decompose specs into todos, delegate them to worker agents, and report results. Nothing else.
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
## Identity constraints (absolute)
|
|
256
|
+
|
|
257
|
+
- Do NOT answer questions, browse files, run bash, or use mem0
|
|
258
|
+
- Do NOT call any tool not listed in the tool reference below \u2014 if a tool isn't listed, it does not exist
|
|
259
|
+
- Do NOT ask "should I start?" / "shall I proceed?" \u2014 if you have work and workers, act
|
|
260
|
+
- If a user asks you to do something outside orchestration, respond: "I'm an orchestrator. Give me a task spec and I'll delegate it to workers."
|
|
261
|
+
|
|
262
|
+
**Your own agent ID: \`{{PANEL_ID}}\`**
|
|
263
|
+
Never call \`bridge_kill_agent\` with this ID \u2014 killing yourself terminates the orchestration session.
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
## Workflow
|
|
268
|
+
|
|
269
|
+
### Step 1 \u2014 Orient
|
|
270
|
+
Call these in parallel:
|
|
271
|
+
- \`bridge_get_project\` \u2014 project name, cwd, machineId
|
|
272
|
+
- \`bridge_get_todos\` \u2014 open todos and current session state
|
|
273
|
+
- \`bridge_list_agents\` \u2014 worker availability (role, status, inRun)
|
|
274
|
+
|
|
275
|
+
**Decision after Step 1:**
|
|
276
|
+
- If todos exist AND idle workers available \u2192 go directly to Step 4 (assign now, no re-planning)
|
|
277
|
+
- If todos exist but no workers \u2192 go to Step 4 (spawn first)
|
|
278
|
+
- If no todos exist \u2192 go to Step 2
|
|
279
|
+
- If session is stale or wrong \u2192 call \`bridge_cancel_run\`, then go to Step 2
|
|
280
|
+
|
|
281
|
+
### Step 2 \u2014 Clarify (if needed)
|
|
282
|
+
If the spec is genuinely ambiguous, ask ONE question. Otherwise skip.
|
|
283
|
+
|
|
284
|
+
### Step 3 \u2014 Plan
|
|
285
|
+
Create 3\u201310 todos with \`bridge_add_todo\`:
|
|
286
|
+
- \`todoType\`: \`implementation\` \u2192 developer, \`review\` \u2192 reviewer, \`infra\` \u2192 shell/executor
|
|
287
|
+
- \`dependsOn\`: list todo IDs that must complete first
|
|
288
|
+
- Every implementation block must have a \`review\` todo depending on it
|
|
289
|
+
- Descriptions: include file paths, expected inputs/outputs, relevant context
|
|
290
|
+
|
|
291
|
+
Verify plan with \`bridge_get_todos\` before proceeding.
|
|
292
|
+
|
|
293
|
+
### Step 4 \u2014 Spawn workers if needed
|
|
294
|
+
\`bridge_list_agents\` \u2014 check for idle agents first (previous sessions may have them).
|
|
295
|
+
Missing a required role \u2192 \`bridge_spawn_worker\` (role: developer, reviewer, shell, executor).
|
|
296
|
+
|
|
297
|
+
### Step 5 \u2014 Assign initial work
|
|
298
|
+
For each idle agent matching a needed role:
|
|
299
|
+
- Get the todo ID from \`bridge_list_agents\` (assignedTodo field shows what's already running)
|
|
300
|
+
- \`bridge_assign_task\` \u2014 pin the todo to the agent (\`inRun:false\` agents are valid targets)
|
|
301
|
+
- Server dispatches remaining todos automatically as workers complete \u2014 you do NOT need to manually assign every todo
|
|
302
|
+
|
|
303
|
+
After assigning, call \`bridge_get_execution_status\` and report current progress to the user:
|
|
304
|
+
- How many todos are running / done / total
|
|
305
|
+
- Which workers are active
|
|
306
|
+
|
|
307
|
+
Then go idle. The server handles dispatch automatically.
|
|
308
|
+
|
|
309
|
+
### Step 6 \u2014 Monitor (only when user explicitly requests it)
|
|
310
|
+
|
|
311
|
+
**Default behavior: stop after Step 5 and go idle.**
|
|
312
|
+
|
|
313
|
+
Only enter this step if the user explicitly asks to "monitor", "watch this", "drive to completion", or similar.
|
|
314
|
+
|
|
315
|
+
**Bounded monitoring loop \u2014 maximum 5 poll iterations:**
|
|
316
|
+
|
|
317
|
+
Each iteration:
|
|
318
|
+
1. \`bridge_get_execution_status\`
|
|
319
|
+
- run status = \`completed\` \u2192 DONE: go to Step 7
|
|
320
|
+
- run status = \`circuit_broken\` \u2192 all retries exhausted: go to Step 7 with failure summary
|
|
321
|
+
- done = total \u2192 DONE: go to Step 7
|
|
322
|
+
2. \`bridge_list_agents\`
|
|
323
|
+
- Any agent \`status: busy\` \u2192 work in progress, continue to next iteration
|
|
324
|
+
- **ALL agents idle + done < total = DEADLOCK:**
|
|
325
|
+
- \`bridge_get_agent_output\` on recently-idle agents to diagnose
|
|
326
|
+
- Missing a required role? \u2192 \`bridge_spawn_worker\` **once** (do NOT spawn repeatedly)
|
|
327
|
+
- Report to user: what is stuck and why. Exit loop.
|
|
328
|
+
3. Continue to next iteration (max 5 total)
|
|
329
|
+
|
|
330
|
+
After 5 iterations: report current \`bridge_get_execution_status\` snapshot and go idle. Tell the user to re-engage you for another status check.
|
|
331
|
+
|
|
332
|
+
**Hard limits in monitoring mode:**
|
|
333
|
+
- Max 5 poll iterations \u2014 never exceed this
|
|
334
|
+
- Max 1 \`bridge_spawn_worker\` call per deadlock \u2014 never spawn repeatedly
|
|
335
|
+
- If \`bridge_get_execution_status\` returns an error \u2192 exit loop, report to user
|
|
336
|
+
|
|
337
|
+
### Step 7 \u2014 Wrap up
|
|
338
|
+
Summarize: todos completed, failed, any blockers. List what workers did.
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
${Lo("bridge_get_project","bridge_get_plan","bridge_get_todos","bridge_add_todo","bridge_cancel_run","bridge_get_project_history","bridge_get_execution_status","bridge_list_agents","bridge_get_agent_status","bridge_spawn_worker","bridge_assign_task","bridge_get_todo_context","bridge_get_agent_output","bridge_kill_agent")}`};function Mo(r,e,t){if(!e)return[];let n=Jn[e];if(!n)return[];if(r==="claude")try{let s=L.default.join(xe.default.tmpdir(),`bridge-role-${t}.md`),i=n.replaceAll("{{PANEL_ID}}",t);return Z.default.writeFileSync(s,i+`
|
|
343
|
+
`,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:s}),["--append-system-prompt-file",s]}catch(s){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(s)}),[]}return r==="qwen"?["--append-system-prompt",n]:[]}function Ee(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function jo(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:Je(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=L.default.join(xe.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??r.projectId}.json`);return Z.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
344
|
+
`,"utf-8"),console.log("[daemon] kimi.mcp.config.written",{tmpPath:n,transport:e?"http":"stdio"}),["--mcp-config-file",n]}catch(e){return console.warn("[daemon] kimi.mcp.config.build.failed",{error:String(e)}),[]}}function Bo(r){try{let e=Je(),t=`{BRIDGE_SERVER_URL=${Ee(r.serverUrl)},BRIDGE_TOKEN=${Ee(r.token)},BRIDGE_WORKSPACE_ID=${Ee(r.workspaceId)},BRIDGE_PROJECT_ID=${Ee(r.projectId)},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Ee(e)}`,"-c","mcp_servers.bridge.args=[]","-c",`mcp_servers.bridge.env=${t}`]}catch(e){return console.warn("[daemon] codex.mcp.config.build.failed",{error:String(e)}),[]}}function $o(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId}),!1;let e=Je(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,Gt.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,Gt.spawnSync)("qwen",["mcp","add","--scope","project","-t","stdio","-e",`BRIDGE_SERVER_URL=${r.serverUrl}`,"-e",`BRIDGE_TOKEN=${r.token}`,"-e",`BRIDGE_WORKSPACE_ID=${r.workspaceId}`,"-e",`BRIDGE_PROJECT_ID=${r.projectId}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return n.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:n.status,stderr:(n.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] qwen.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}var ze=[],Yt=!1,Yn=!1;function Xn(){return Yt}function Qn(r){if(Yn)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");Yn=!0;let e=$t(),t=(0,zn.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0;function c(){s&&(clearTimeout(s),s=null),n=new O(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let l=n,d=null;l.on("open",()=>{Yt=!0,console.log("[daemon] ws.connected",{server:e.server}),i=setInterval(()=>{l.readyState===O.OPEN&&l.ping()},Co),l.send(JSON.stringify({type:"ready",version:"1.1",name:e.name})),mt().then(u=>{ze=u,l.readyState===O.OPEN&&l.send(JSON.stringify({type:"agents",list:ze}))}),d=Kn(u=>{l.readyState===O.OPEN&&l.send(JSON.stringify({type:"system_metrics",daemonId:t,...u}))})}),l.on("message",u=>{let h;try{h=JSON.parse(u.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}Uo(h,l,r,e)}),l.on("close",u=>{Yt=!1,i&&(clearInterval(i),i=null),d?.(),d=null,u===1008?(o++,o>=2&&(console.error("[daemon] ws.auth_failed \u2014 token invalid or expired (2 consecutive rejections), stopping. Re-run: bridge-agent auth"),process.exit(1)),console.warn("[daemon] ws.auth_rejected \u2014 transient 1008, will retry once",{attempt:o})):o=0,!s&&(console.log("[daemon] ws.reconnecting",{attempt:1}),s=setTimeout(c,3e3))}),l.on("error",u=>{console.error("[daemon] ws.error",{message:u.message})})}function a(){i&&(clearInterval(i),i=null),Oo();for(let l of Q.values())l();r.killAll(),n?.close()}process.on("SIGINT",()=>{a(),process.exit(0)}),process.on("SIGTERM",()=>{a(),process.exit(0)}),process.on("uncaughtException",l=>{console.error("[daemon] uncaughtException",{error:l.message}),r.killAll(),process.exit(1)}),c()}function Uo(r,e,t,n){switch(r.type){case"spawn":{console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role});let s=ze.find(b=>b.key===r.agentKey);if(!s){e.readyState===O.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=te.find(b=>b.key===r.agentKey),o=[];if(r.sessionId&&i?.resumeArgs)o=i.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(Q.get(r.agentId)?.(),Q.set(r.agentId,qt(r.agentId,r.sessionId,(b,w,y)=>{e.readyState===O.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:b,usedPct:w,usedTokens:y,...Kt}))})));else if(i?.assignSessionId){let b=crypto.randomUUID(),w=r.agentKey==="kimi"?"--session":"--session-id";o=[...i.spawnArgs??[],w,b],e.readyState===O.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:b})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:b})),r.agentKey==="claude"&&(Q.get(r.agentId)?.(),Q.set(r.agentId,qt(r.agentId,b,(y,R,G)=>{e.readyState===O.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:y,usedPct:R,usedTokens:G,...Kt}))})))}else e.readyState===O.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let c,a=!1,l;if(r.projectId&&r.workspaceId){let b=No(n.server),w=Wt(r.cwd);if(c={serverUrl:b,token:n.token,workspaceId:Mn(r.workspaceId),projectId:jn(r.projectId),agentId:r.agentId?Ln(r.agentId):void 0,cwd:r.cwd,projectEnv:w.env},r.agentKey==="claude"){let y=Ro(c);a=y.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...y]}else if(r.agentKey==="codex"){let y=Bo(c);a=y.length>0,l="stdio",o=[...o,...y]}else if(r.agentKey==="qwen")a=$o(c),l=a?"stdio":void 0;else if(r.agentKey==="kimi"){let y=jo(c);a=y.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...y]}else a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"})}let d=Mo(r.agentKey,r.role,r.agentId);d.length>0&&(o=[...o,...d]);let u=Math.max(1,Math.min(500,r.cols)),h=Math.max(1,Math.min(500,r.rows)),g=Date.now(),f="",p=0,m=!1,v=!1;t.spawn(r.agentId,r.agentKey,s.binaryPath,o,u,h,b=>{p+=b.length;try{let w=Buffer.from(b,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!v&&Date.now()-g<3e4&&(/yolo agent/.test(w)||/●/.test(w)||/○/.test(w))){v=!0;let y=Jn[r.role];if(y){let R=y.replaceAll("{{PANEL_ID}}",r.agentId),G=ko(R),ke=Buffer.from(G).toString("base64");t.write(r.agentId,ke,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let w=Buffer.from(b,"base64").toString("utf-8"),y=To(w).replace(/\x00/g,"").trim();if(y&&(f=Po(y)),r.agentKey==="codex"&&!m&&Date.now()-g<2e4&&/included in your plan for free|let[’']s build together/i.test(y)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(y)){m=!0;let R=Buffer.from("y").toString("base64");t.write(r.agentId,R,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===O.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:b}))},(b,w)=>{let y=Date.now()-g,R=y<=Io;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:b,signal:w,uptimeMs:y,earlyExit:R,outputBytes:p,firstOutputSnippet:f||void 0}),R&&e.readyState===O.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${b??"null"} signal=${w??"null"} snippet="${f||"no output"}"`})),e.readyState===O.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:b,signal:w}))},c)?e.readyState===O.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?l:void 0,projectId:c?.projectId})):e.readyState===O.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_DUPLICATE",message:`Panel ${r.agentId} is already running`}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":Q.get(r.agentId)?.(),Q.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":mt().then(s=>{ze=s,e.readyState===O.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=xe.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=L.default.resolve(i);if(o!==s&&!o.startsWith(s+L.default.sep)){e.readyState===O.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let c=Z.default.readdirSync(o,{withFileTypes:!0}).filter(a=>a.isDirectory()&&!a.name.startsWith(".")).map(a=>({name:a.name,path:L.default.join(o,a.name)})).sort((a,l)=>a.name.localeCompare(l.name));e.readyState===O.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:c}))}catch(c){e.readyState===O.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:[],error:c instanceof Error?c.message:"Cannot read directory"}))}break}default:{let s=r}}}function es(){console.log("[bridge] Starting bridge-agent daemon...");let r=new Te;Qn(r);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,Zn.createServer)((n,s)=>{let i=Xn(),o=JSON.stringify({status:"ok",connected:i,uptime:process.uptime()});s.writeHead(i?200:503,{"Content-Type":"application/json"}),s.end(o)});t.listen(e,"127.0.0.1",()=>{console.log(`[bridge] health check listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.server.error",{error:n.message})})}var ts=_(require("https")),rs=_(require("http"));Ge();function Wo(r){return(r??"").trim()}async function ns(r,e=!1,t){console.log("[bridge] Starting auth flow..."),console.log(`[bridge] Server: ${r}`),console.log("[bridge] Open this URL to generate a daemon token:"),console.log(` ${r}/connect`);let n=Wo(t);n&&console.log("[bridge] Using token from --token"),e&&(n?console.log("[bridge] --no-browser ignored because --token is provided."):(console.log("[bridge] --no-browser: exiting after printing URL."),process.exit(0)));let s=n;s||(console.log(),console.log("[bridge] After authenticating, paste your token here:"),s=await Fo()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await qo(r,s)||(console.error("[bridge] Token validation failed. Please try again."),process.exit(1));let c=r.replace(/^https?:\/\//,a=>a.startsWith("https")?"wss://":"ws://").replace(/\/?$/,"/ws/daemon");Ut({server:c,token:s,name:process.env.HOSTNAME??"My Machine"}),console.log("[bridge] Auth successful! Config saved to ~/.bridge/config.json"),console.log("[bridge] Run: bridge-agent start")}async function Fo(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
|
|
345
|
+
`)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function qo(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?ts.default:rs.default,o={hostname:n.hostname,port:n.port||(s?443:80),path:n.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}},c=i.request(o,a=>{t(a.statusCode===200)});c.on("error",()=>t(!1)),c.end()})}var ve=new lr;ve.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.1.0");ve.command("start").description("Start the bridge-agent daemon").action(()=>{es()});ve.command("auth").description("Authenticate with Bridge server").requiredOption("-s, --server <url>","Server URL (e.g., https://your-server.com)").option("-t, --token <token>","Use token non-interactively").option("--no-browser","Print auth URL without opening browser or interactive prompt").action(r=>{ns(r.server,!r.browser,r.token)});ve.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(Ge(),$n)),e=r();console.log("[bridge] Config found"),console.log(" Server:",e.server),console.log(" Name:",e.name)}catch{console.log("[bridge] Not authenticated. Run: bridge-agent auth")}});ve.parse();
|