bridge-agent 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge-mcp.cjs +1 -1
- package/dist/index.js +42 -40
- package/dist/scripts/install-sim-prereqs.sh +169 -0
- package/package.json +3 -1
- package/scripts/postinstall.mjs +21 -1
package/dist/bridge-mcp.cjs
CHANGED
|
@@ -22684,7 +22684,7 @@ function registerWorkspaceTools(server, ctx) {
|
|
|
22684
22684
|
);
|
|
22685
22685
|
server.tool(
|
|
22686
22686
|
"bridge_get_group_status",
|
|
22687
|
-
"Get all agents in a group with their current status and last output line.",
|
|
22687
|
+
"Get all agents in a group with their current status, projectId, and last output line.",
|
|
22688
22688
|
{ groupId: external_exports.string().describe("The group ID to inspect") },
|
|
22689
22689
|
({ groupId }) => safe2(() => request(ctx, "GET", workspacePath(ctx, `/groups/${groupId}`)))
|
|
22690
22690
|
);
|
package/dist/index.js
CHANGED
|
@@ -1,46 +1,48 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
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(
|
|
2
|
+
"use strict";var pi=Object.create;var Dt=Object.defineProperty;var fi=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,_i=Object.prototype.hasOwnProperty;var Ur=(r,e)=>()=>(r&&(e=r(r=0)),e);var O=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),yi=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},bi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gi(e))!_i.call(r,s)&&s!==t&&Dt(r,s,{get:()=>e[s],enumerable:!(n=fi(e,s))||n.enumerable});return r};var _=(r,e,t)=>(t=r!=null?pi(mi(r)):{},bi(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r));var Ae=O(jt=>{var et=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}},Rt=class extends et{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};jt.CommanderError=et;jt.InvalidArgumentError=Rt});var tt=O(Mt=>{var{InvalidArgumentError:wi}=Ae(),Lt=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 wi(`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 Si(r){let e=r.name()+(r.variadic===!0?"...":"");return r.required?"<"+e+">":"["+e+"]"}Mt.Argument=Lt;Mt.humanReadableArgName=Si});var Bt=O(Wr=>{var{humanReadableArgName:vi}=tt(),$t=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=>vi(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(g,h){if(h){let m=`${g.padEnd(n+o)}${h}`;return t.wrap(m,s-i,n+o)}return g}function a(g){return g.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(g=>c(t.argumentTerm(g),t.argumentDescription(g)));u.length>0&&(l=l.concat(["Arguments:",a(u),""]));let f=t.visibleOptions(e).map(g=>c(t.optionTerm(g),t.optionDescription(g)));if(f.length>0&&(l=l.concat(["Options:",a(f),""])),this.showGlobalOptions){let g=t.visibleGlobalOptions(e).map(h=>c(t.optionTerm(h),t.optionDescription(h)));g.length>0&&(l=l.concat(["Global Options:",a(g),""]))}let p=t.visibleCommands(e).map(g=>c(t.subcommandTerm(g),t.subcommandDescription(g)));return p.length>0&&(l=l.concat(["Commands:",a(p),""])),l.join(`
|
|
4
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
5
|
`,`
|
|
6
|
-
`),d=" ".repeat(n),
|
|
7
|
-
|.{1,${c-1}}([${
|
|
8
|
-
`?"":(m>0?d:"")+
|
|
9
|
-
`)}};
|
|
6
|
+
`),d=" ".repeat(n),f="\\s\u200B",p=new RegExp(`
|
|
7
|
+
|.{1,${c-1}}([${f}]|$)|[^${f}]+?([${f}]|$)`,"g"),g=l.match(p)||[];return a+g.map((h,m)=>h===`
|
|
8
|
+
`?"":(m>0?d:"")+h.trimEnd()).join(`
|
|
9
|
+
`)}};Wr.Help=$t});var Ht=O(Ft=>{var{InvalidArgumentError:Ei}=Ae(),Ut=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=xi(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 Ei(`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 ki(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Wt=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 ki(r){return r.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function xi(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}}Ft.Option=Ut;Ft.DualOptions=Wt});var Hr=O(Fr=>{function Ii(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 Oi(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=Ii(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
10
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
11
|
-
(Did you mean ${n[0]}?)`:""}
|
|
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
|
|
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
|
|
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
|
|
11
|
+
(Did you mean ${n[0]}?)`:""}Fr.suggestSimilar=Oi});var Jr=O(Kr=>{var Ci=require("node:events").EventEmitter,Gt=require("node:child_process"),V=require("node:path"),qt=require("node:fs"),C=require("node:process"),{Argument:Pi,humanReadableArgName:Ai}=tt(),{CommanderError:Vt}=Ae(),{Help:Ti}=Bt(),{Option:Gr,DualOptions:Ni}=Ht(),{suggestSimilar:qr}=Hr(),Kt=class r extends Ci{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=>C.stdout.write(t),writeErr:t=>C.stderr.write(t),getOutHelpWidth:()=>C.stdout.isTTY?C.stdout.columns:void 0,getErrHelpWidth:()=>C.stderr.isTTY?C.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 Ti,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 Pi(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 Vt(e,t,n)),C.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 Gr(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 Gr)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){C.versions?.electron&&(t.from="electron");let s=C.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(t.from="eval")}e===void 0&&(e=C.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":C.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 f=V.resolve(d,u);if(qt.existsSync(f))return f;if(s.includes(V.extname(u)))return;let p=s.find(g=>qt.existsSync(`${f}${g}`));if(p)return`${f}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let d;try{d=qt.realpathSync(this._scriptPath)}catch{d=this._scriptPath}c=V.resolve(V.dirname(d),c)}if(c){let d=i(c,o);if(!d&&!e._executableFile&&this._scriptPath){let u=V.basename(this._scriptPath,V.extname(this._scriptPath));u!==this._name&&(d=i(c,`${u}-${e._name}`))}o=d||o}n=s.includes(V.extname(o));let a;C.platform!=="win32"?n?(t.unshift(o),t=Vr(C.execArgv).concat(t),a=Gt.spawn(C.argv[0],t,{stdio:"inherit"})):a=Gt.spawn(o,t,{stdio:"inherit"}):(t.unshift(o),t=Vr(C.execArgv).concat(t),a=Gt.spawn(C.execPath,t,{stdio:"inherit"})),a.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(u=>{C.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 Vt(d,"commander.executeSubCommandAsync","(close)")):C.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",f=`'${o}' does not exist
|
|
15
15
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
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(
|
|
17
|
+
- ${u}`;throw new Error(f)}else if(d.code==="EACCES")throw new Error(`'${o}' not executable`);if(!l)C.exit(1);else{let u=new Vt(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
18
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
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
|
|
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=>
|
|
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 C.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()}`,C.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ni(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=qr(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=qr(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=>Ai(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=V.basename(e,V.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=C.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
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 Nr(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})}Dr.Command=$t});var $r=O(M=>{var{Argument:jr}=Ke(),{Command:Bt}=Rr(),{CommanderError:di,InvalidArgumentError:Lr}=Ie(),{Help:ui}=Pt(),{Option:Mr}=Rt();M.program=new Bt;M.createCommand=r=>new Bt(r);M.createOption=(r,e)=>new Mr(r,e);M.createArgument=(r,e)=>new jr(r,e);M.Command=Bt;M.Option=Mr;M.Argument=jr;M.Help=ui;M.CommanderError=di;M.InvalidArgumentError=Lr;M.InvalidOptionArgumentError=Lr});var Vr=O(P=>{"use strict";var Ut=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),hi=Ut(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 p=new Set([u,...d]),g=c.mode,h=c.uid,f=c.gid,m=parseInt("100",8),k=parseInt("010",8),S=parseInt("001",8),N=m|k;return!!(g&S||g&k&&p.has(f)||g&m&&h===l||g&N&&l===0)}}),fi=Ut(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 p=u;if(d||p.code==="EACCES")return!1;throw p}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let p=u;if(d||p.code==="EACCES")return!1;throw p}};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 p of u){let g=p.toLowerCase(),h=a.substring(a.length-g.length).toLowerCase();if(g&&h===g)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),pi=Ut(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),Wr=P&&P.__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]})),gi=P&&P.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),Fr=P&&P.__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"&&Wr(t,e,n[s]);return gi(t,e),t}})(),mi=P&&P.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Wr(e,r,t)};Object.defineProperty(P,"__esModule",{value:!0});P.sync=P.isexe=P.posix=P.win32=void 0;var Gr=Fr(hi());P.posix=Gr;var qr=Fr(fi());P.win32=qr;mi(pi(),P);var _i=process.env._ISEXE_TEST_PLATFORM_||process.platform,Hr=_i==="win32"?qr:Gr;P.isexe=Hr.isexe;P.sync=Hr.sync});var rn=O((gc,tn)=>{var{isexe:yi,sync:bi}=Vr(),{join:wi,delimiter:Si,sep:Kr,posix:Jr}=require("path"),Yr=process.platform==="win32",zr=new RegExp(`[${Jr.sep}${Kr===Jr.sep?"":Kr}]`.replace(/(\\)/g,"\\$1")),vi=new RegExp(`^\\.${zr.source}`),Xr=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),Qr=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=Si})=>{let s=r.match(zr)?[""]:[...Yr?[process.cwd()]:[],...(e||"").split(n)];if(Yr){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:[""]}},Zr=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&vi.test(e)?e.slice(0,2):"")+wi(t,e)},en=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Qr(r,e),i=[];for(let o of t){let c=Zr(o,r);for(let a of n){let l=c+a;if(await yi(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 Xr(r)},Ei=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=Qr(r,e),i=[];for(let o of t){let c=Zr(o,r);for(let a of n){let l=c+a;if(bi(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 Xr(r)};tn.exports=en;en.sync=Ei});var H=O((bc,dn)=>{"use strict";var cn=["nodebuffer","arraybuffer","fragments"],ln=typeof Blob<"u";ln&&cn.push("blob");dn.exports={BINARY_TYPES:cn,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ln,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Pe=O((wc,Qe)=>{"use strict";var{EMPTY_BUFFER:Ii}=H(),Gt=Buffer[Symbol.species];function Ci(r,e){if(r.length===0)return Ii;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 Gt(t.buffer,t.byteOffset,n):t}function un(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function hn(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Ai(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function qt(r){if(qt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Gt(r):ArrayBuffer.isView(r)?e=new Gt(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),qt.readOnly=!1),e}Qe.exports={concat:Ci,mask:un,toArrayBuffer:Ai,toBuffer:qt,unmask:hn};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");Qe.exports.mask=function(e,t,n,s,i){i<48?un(e,t,n,s,i):r.mask(e,t,n,s,i)},Qe.exports.unmask=function(e,t){e.length<32?hn(e,t):r.unmask(e,t)}}catch{}});var gn=O((Sc,pn)=>{"use strict";var fn=Symbol("kDone"),Ht=Symbol("kRun"),Vt=class{constructor(e){this[fn]=()=>{this.pending--,this[Ht]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ht]()}[Ht](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[fn])}}};pn.exports=Vt});var ge=O((vc,bn)=>{"use strict";var Te=require("zlib"),mn=Pe(),Pi=gn(),{kStatusCode:_n}=H(),Ti=Buffer[Symbol.species],Ni=Buffer.from([0,0,255,255]),et=Symbol("permessage-deflate"),V=Symbol("total-length"),fe=Symbol("callback"),z=Symbol("buffers"),pe=Symbol("error"),Ze,Kt=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,!Ze){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ze=new Pi(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[fe];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){Ze.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Ze.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"?Te.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Te.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[et]=this,this._inflate[V]=0,this._inflate[z]=[],this._inflate.on("error",Ri),this._inflate.on("data",yn)}this._inflate[fe]=n,this._inflate.write(e),t&&this._inflate.write(Ni),this._inflate.flush(()=>{let i=this._inflate[pe];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=mn.concat(this._inflate[z],this._inflate[V]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[V]=0,this._inflate[z]=[],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"?Te.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Te.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[V]=0,this._deflate[z]=[],this._deflate.on("data",Di)}this._deflate[fe]=n,this._deflate.write(e),this._deflate.flush(Te.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=mn.concat(this._deflate[z],this._deflate[V]);t&&(i=new Ti(i.buffer,i.byteOffset,i.length-4)),this._deflate[fe]=null,this._deflate[V]=0,this._deflate[z]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};bn.exports=Kt;function Di(r){this[z].push(r),this[V]+=r.length}function yn(r){if(this[V]+=r.length,this[et]._maxPayload<1||this[V]<=this[et]._maxPayload){this[z].push(r);return}this[pe]=new RangeError("Max payload size exceeded"),this[pe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pe][_n]=1009,this.removeListener("data",yn),this.reset()}function Ri(r){if(this[et]._inflate=null,this[pe]){this[fe](this[pe]);return}r[_n]=1007,this[fe](r)}});var me=O((Ec,tt)=>{"use strict";var{isUtf8:wn}=require("buffer"),{hasBlob:ji}=H(),Li=[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 Mi(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Jt(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 $i(r){return ji&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}tt.exports={isBlob:$i,isValidStatusCode:Mi,isValidUTF8:Jt,tokenChars:Li};if(wn)tt.exports.isValidUTF8=function(r){return r.length<24?Jt(r):wn(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");tt.exports.isValidUTF8=function(e){return e.length<32?Jt(e):r(e)}}catch{}});var Zt=O((kc,In)=>{"use strict";var{Writable:Bi}=require("stream"),Sn=ge(),{BINARY_TYPES:Ui,EMPTY_BUFFER:vn,kStatusCode:Wi,kWebSocket:Fi}=H(),{concat:Yt,toArrayBuffer:Gi,unmask:qi}=Pe(),{isValidStatusCode:Hi,isValidUTF8:En}=me(),rt=Buffer[Symbol.species],$=0,kn=1,xn=2,On=3,zt=4,Xt=5,nt=6,Qt=class extends Bi{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ui[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Fi]=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=$}_write(e,t,n){if(this._opcode===8&&this._state==$)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 rt(n.buffer,n.byteOffset+e,n.length-e),new rt(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 rt(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 $:this.getInfo(e);break;case kn:this.getPayloadLength16(e);break;case xn:this.getPayloadLength64(e);break;case On:this.getMask();break;case zt:this.getData(e);break;case Xt:case nt: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[Sn.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=kn:this._payloadLength===127?this._state=xn: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=On:this._state=zt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zt}getData(e){let t=vn;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&&qi(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Xt,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Sn.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===$&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=$;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=Yt(n,t):this._binaryType==="arraybuffer"?s=Gi(Yt(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=$):(this._state=nt,setImmediate(()=>{this.emit("message",s,!0),this._state=$,this.startLoop(e)}))}else{let s=Yt(n,t);if(!this._skipUTF8Validation&&!En(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Xt||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=$):(this._state=nt,setImmediate(()=>{this.emit("message",s,!1),this._state=$,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,vn),this.end();else{let n=e.readUInt16BE(0);if(!Hi(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new rt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!En(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=$;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$):(this._state=nt,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$,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[Wi]=s,o}};In.exports=Qt});var rr=O((Oc,Pn)=>{"use strict";var{Duplex:xc}=require("stream"),{randomFillSync:Vi}=require("crypto"),Cn=ge(),{EMPTY_BUFFER:Ki,kWebSocket:Ji,NOOP:Yi}=H(),{isBlob:_e,isValidStatusCode:zi}=me(),{mask:An,toBuffer:ee}=Pe(),B=Symbol("kByteLength"),Xi=Buffer.alloc(4),st=8*1024,te,ye=st,U=0,Qi=1,Zi=2,er=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=U,this.onerror=Yi,this[Ji]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||Xi,t.generateMask?t.generateMask(n):(ye===st&&(te===void 0&&(te=Buffer.alloc(st)),Vi(te,0,st),ye=0),n[0]=te[ye++],n[1]=te[ye++],n[2]=te[ye++],n[3]=te[ye++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[B]!==void 0?c=t[B]:(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?(An(e,n,l,i,c),[l]):(An(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=Ki;else{if(typeof e!="number"||!zi(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={[B]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==U?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):_e(e)?(s=e.size,i=!1):(e=ee(e),s=e.length,i=ee.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[B]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==U?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):_e(e)?(s=e.size,i=!1):(e=ee(e),s=e.length,i=ee.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[B]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==U?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Cn.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):_e(e)?(c=e.size,a=!1):(e=ee(e),c=e.length,a=ee.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={[B]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};_e(e)?this._state!==U?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==U?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[B],this._state=Zi,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(tr,this,c,s);return}this._bufferedBytes-=n[B];let o=ee(i);t?this.dispatch(o,t,n,s):(this._state=U,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(eo,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Cn.extensionName];this._bufferedBytes+=n[B],this._state=Qi,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");tr(this,a,s);return}this._bufferedBytes-=n[B],this._state=U,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===U&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][B],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][B],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)}};Pn.exports=er;function tr(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 eo(r,e,t){tr(r,e,t),r.onerror(e)}});var Bn=O((Ic,$n)=>{"use strict";var{kForOnEventAttribute:Ne,kListener:nr}=H(),Tn=Symbol("kCode"),Nn=Symbol("kData"),Dn=Symbol("kError"),Rn=Symbol("kMessage"),jn=Symbol("kReason"),be=Symbol("kTarget"),Ln=Symbol("kType"),Mn=Symbol("kWasClean"),K=class{constructor(e){this[be]=null,this[Ln]=e}get target(){return this[be]}get type(){return this[Ln]}};Object.defineProperty(K.prototype,"target",{enumerable:!0});Object.defineProperty(K.prototype,"type",{enumerable:!0});var re=class extends K{constructor(e,t={}){super(e),this[Tn]=t.code===void 0?0:t.code,this[jn]=t.reason===void 0?"":t.reason,this[Mn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Tn]}get reason(){return this[jn]}get wasClean(){return this[Mn]}};Object.defineProperty(re.prototype,"code",{enumerable:!0});Object.defineProperty(re.prototype,"reason",{enumerable:!0});Object.defineProperty(re.prototype,"wasClean",{enumerable:!0});var we=class extends K{constructor(e,t={}){super(e),this[Dn]=t.error===void 0?null:t.error,this[Rn]=t.message===void 0?"":t.message}get error(){return this[Dn]}get message(){return this[Rn]}};Object.defineProperty(we.prototype,"error",{enumerable:!0});Object.defineProperty(we.prototype,"message",{enumerable:!0});var De=class extends K{constructor(e,t={}){super(e),this[Nn]=t.data===void 0?null:t.data}get data(){return this[Nn]}};Object.defineProperty(De.prototype,"data",{enumerable:!0});var to={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[Ne]&&s[nr]===e&&!s[Ne])return;let n;if(r==="message")n=function(i,o){let c=new De("message",{data:o?i:i.toString()});c[be]=this,it(e,this,c)};else if(r==="close")n=function(i,o){let c=new re("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[be]=this,it(e,this,c)};else if(r==="error")n=function(i){let o=new we("error",{error:i,message:i.message});o[be]=this,it(e,this,o)};else if(r==="open")n=function(){let i=new K("open");i[be]=this,it(e,this,i)};else return;n[Ne]=!!t[Ne],n[nr]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[nr]===e&&!t[Ne]){this.removeListener(r,t);break}}};$n.exports={CloseEvent:re,ErrorEvent:we,Event:K,EventTarget:to,MessageEvent:De};function it(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ot=O((Cc,Un)=>{"use strict";var{tokenChars:Re}=me();function G(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function ro(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&&Re[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?(G(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&&Re[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),G(t,r.slice(a,d),!0),l===44&&(G(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(Re[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Re[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&&Re[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),G(t,c,g),l===44&&(G(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 p=r.slice(a,d);return o===void 0?G(e,p,t):(c===void 0?G(t,p,!0):n?G(t,c,p.replace(/\\/g,"")):G(t,c,p),G(e,o,t)),e}function no(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(", ")}Un.exports={format:no,parse:ro}});var dt=O((Tc,Qn)=>{"use strict";var so=require("events"),io=require("https"),oo=require("http"),Gn=require("net"),ao=require("tls"),{randomBytes:co,createHash:lo}=require("crypto"),{Duplex:Ac,Readable:Pc}=require("stream"),{URL:sr}=require("url"),X=ge(),uo=Zt(),ho=rr(),{isBlob:fo}=me(),{BINARY_TYPES:Wn,CLOSE_TIMEOUT:po,EMPTY_BUFFER:at,GUID:go,kForOnEventAttribute:ir,kListener:mo,kStatusCode:_o,kWebSocket:T,NOOP:qn}=H(),{EventTarget:{addEventListener:yo,removeEventListener:bo}}=Bn(),{format:wo,parse:So}=ot(),{toBuffer:vo}=Pe(),Hn=Symbol("kAborted"),or=[8,13],J=["CONNECTING","OPEN","CLOSING","CLOSED"],Eo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class r extends so{constructor(e,t,n){super(),this._binaryType=Wn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=at,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]),Vn(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Wn.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 uo({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new ho(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[T]=this,i[T]=this,e[T]=this,s.on("conclude",Oo),s.on("drain",Io),s.on("error",Co),s.on("message",Ao),s.on("ping",Po),s.on("pong",To),i.onerror=No,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yn),e.on("data",lt),e.on("end",zn),e.on("error",Xn),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[X.extensionName]&&this._extensions[X.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){j(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())}),Jn(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){ar(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||at,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){ar(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||at,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){ar(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[X.extensionName]||(s.compress=!1),this._sender.send(e||at,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){j(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:J.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:J.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:J.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:J.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:J.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:J.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:J.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:J.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(x.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(x.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[ir])return e[mo];return null},set(e){for(let t of this.listeners(r))if(t[ir]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[ir]:!0})}})});x.prototype.addEventListener=yo;x.prototype.removeEventListener=bo;Qn.exports=x;function Vn(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:po,protocolVersion:or[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,!or.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${or.join(", ")})`);let i;if(e instanceof sr)i=e;else try{i=new sr(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 f=new SyntaxError(a);if(r._redirects===0)throw f;ct(r,f);return}let l=o?443:80,d=co(16).toString("base64"),u=o?io.request:oo.request,p=new Set,g;if(s.createConnection=s.createConnection||(o?xo:ko),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 X({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=wo({[X.extensionName]:g.offer()})),t.length){for(let f of t){if(typeof f!="string"||!Eo.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}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 f=s.path.split(":");s.socketPath=f[0],s.path=f[1]}let h;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let f=n&&n.headers;if(n={...n,headers:{}},f)for(let[m,k]of Object.entries(f))n.headers[m.toLowerCase()]=k}else if(r.listenerCount("redirect")===0){let f=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!f||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,f||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=r._req=u(s),r._redirects&&r.emit("redirect",r.url,h)}else h=r._req=u(s);s.timeout&&h.on("timeout",()=>{j(r,h,"Opening handshake has timed out")}),h.on("error",f=>{h===null||h[Hn]||(h=r._req=null,ct(r,f))}),h.on("response",f=>{let m=f.headers.location,k=f.statusCode;if(m&&s.followRedirects&&k>=300&&k<400){if(++r._redirects>s.maxRedirects){j(r,h,"Maximum redirects exceeded");return}h.abort();let S;try{S=new sr(m,e)}catch{let y=new SyntaxError(`Invalid URL: ${m}`);ct(r,y);return}Vn(r,S,t,n)}else r.emit("unexpected-response",h,f)||j(r,h,`Unexpected server response: ${f.statusCode}`)}),h.on("upgrade",(f,m,k)=>{if(r.emit("upgrade",f),r.readyState!==x.CONNECTING)return;h=r._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){j(r,m,"Invalid Upgrade header");return}let N=lo("sha1").update(d+go).digest("base64");if(f.headers["sec-websocket-accept"]!==N){j(r,m,"Invalid Sec-WebSocket-Accept header");return}let y=f.headers["sec-websocket-protocol"],v;if(y!==void 0?p.size?p.has(y)||(v="Server sent an invalid subprotocol"):v="Server sent a subprotocol but none was requested":p.size&&(v="Server sent no subprotocol"),v){j(r,m,v);return}y&&(r._protocol=y);let w=f.headers["sec-websocket-extensions"];if(w!==void 0){if(!g){j(r,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let E;try{E=So(w)}catch{j(r,m,"Invalid Sec-WebSocket-Extensions header");return}let b=Object.keys(E);if(b.length!==1||b[0]!==X.extensionName){j(r,m,"Server indicated an extension that was not requested");return}try{g.accept(E[X.extensionName])}catch{j(r,m,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[X.extensionName]=g}r.setSocket(m,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,r):h.end()}function ct(r,e){r._readyState=x.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function ko(r){return r.path=r.socketPath,Gn.connect(r)}function xo(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Gn.isIP(r.host)?"":r.host),ao.connect(r)}function j(r,e,t){r._readyState=x.CLOSING;let n=new Error(t);Error.captureStackTrace(n,j),e.setHeader?(e[Hn]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ct,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function ar(r,e,t){if(e){let n=fo(e)?e.size:vo(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${J[r.readyState]})`);process.nextTick(t,n)}}function Oo(r,e){let t=this[T];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[T]!==void 0&&(t._socket.removeListener("data",lt),process.nextTick(Kn,t._socket),r===1005?t.close():t.close(r,e))}function Io(){let r=this[T];r.isPaused||r._socket.resume()}function Co(r){let e=this[T];e._socket[T]!==void 0&&(e._socket.removeListener("data",lt),process.nextTick(Kn,e._socket),e.close(r[_o])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Fn(){this[T].emitClose()}function Ao(r,e){this[T].emit("message",r,e)}function Po(r){let e=this[T];e._autoPong&&e.pong(r,!this._isServer,qn),e.emit("ping",r)}function To(r){this[T].emit("pong",r)}function Kn(r){r.resume()}function No(r){let e=this[T];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,Jn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Jn(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Yn(){let r=this[T];if(this.removeListener("close",Yn),this.removeListener("data",lt),this.removeListener("end",zn),r._readyState=x.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[T]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Fn),r._receiver.on("finish",Fn))}function lt(r){this[T]._receiver.write(r)||this.pause()}function zn(){let r=this[T];r._readyState=x.CLOSING,r._receiver.end(),this.end()}function Xn(){let r=this[T];this.removeListener("error",Xn),this.on("error",qn),r&&(r._readyState=x.CLOSING,this.destroy())}});var rs=O((Dc,ts)=>{"use strict";var Nc=dt(),{Duplex:Do}=require("stream");function Zn(r){r.emit("close")}function Ro(){!this.destroyed&&this._writableState.finished&&this.destroy()}function es(r){this.removeListener("error",es),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function jo(r,e){let t=!0,n=new Do({...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(Zn,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(Zn,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",Ro),n.on("error",es),n}ts.exports=jo});var cr=O((Rc,ns)=>{"use strict";var{tokenChars:Lo}=me();function Mo(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&&Lo[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}ns.exports={parse:Mo}});var ds=O((Lc,ls)=>{"use strict";var $o=require("events"),ut=require("http"),{Duplex:jc}=require("stream"),{createHash:Bo}=require("crypto"),ss=ot(),ne=ge(),Uo=cr(),Wo=dt(),{CLOSE_TIMEOUT:Fo,GUID:Go,kWebSocket:qo}=H(),Ho=/^[+/0-9A-Za-z]{22}==$/,is=0,os=1,cs=2,lr=class extends $o{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Fo,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wo,...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=ut.createServer((n,s)=>{let i=ut.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=Vo(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=is}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===cs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(je,this);return}if(e&&this.once("close",e),this._state!==os)if(this._state=os,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(je,this):process.nextTick(je,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{je(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",as);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){se(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){se(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ho.test(i)){se(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){se(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Le(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=Uo.parse(a)}catch{se(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 p=new ne({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=ss.parse(d);g[ne.extensionName]&&(p.accept(g[ne.extensionName]),u[ne.extensionName]=p)}catch{se(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={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(p,(g,h,f,m)=>{if(!g)return Le(t,h||401,f,m);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(p))return Le(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[qo])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>is)return Le(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bo("sha1").update(t+Go).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[ne.extensionName]){let u=e[ne.extensionName].params,p=ss.format({[ne.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${p}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(s=>t.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function Vr(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})}Kr.Command=Kt});var Qr=O($=>{var{Argument:Yr}=tt(),{Command:Jt}=Jr(),{CommanderError:Di,InvalidArgumentError:zr}=Ae(),{Help:Ri}=Bt(),{Option:Xr}=Ht();$.program=new Jt;$.createCommand=r=>new Jt(r);$.createOption=(r,e)=>new Xr(r,e);$.createArgument=(r,e)=>new Yr(r,e);$.Command=Jt;$.Option=Xr;$.Argument=Yr;$.Help=Ri;$.CommanderError=Di;$.InvalidArgumentError=zr;$.InvalidOptionArgumentError=zr});var an=O(T=>{"use strict";var Yt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ji=Yt(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 f=new Set([u,...d]),p=c.mode,g=c.uid,h=c.gid,m=parseInt("100",8),x=parseInt("010",8),S=parseInt("001",8),P=m|x;return!!(p&S||p&x&&f.has(h)||p&m&&g===l||p&P&&l===0)}}),Li=Yt(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 f=u;if(d||f.code==="EACCES")return!1;throw f}};r.isexe=s;var i=(a,l={})=>{let{ignoreErrors:d=!1}=l;try{return c((0,e.statSync)(a),a,l)}catch(u){let f=u;if(d||f.code==="EACCES")return!1;throw f}};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 f of u){let p=f.toLowerCase(),g=a.substring(a.length-p.length).toLowerCase();if(p&&g===p)return!0}return!1},c=(a,l,d)=>a.isFile()&&o(l,d)}),Mi=Yt(r=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0})}),tn=T&&T.__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]})),$i=T&&T.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),rn=T&&T.__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"&&tn(t,e,n[s]);return $i(t,e),t}})(),Bi=T&&T.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&tn(e,r,t)};Object.defineProperty(T,"__esModule",{value:!0});T.sync=T.isexe=T.posix=T.win32=void 0;var nn=rn(ji());T.posix=nn;var sn=rn(Li());T.win32=sn;Bi(Mi(),T);var Ui=process.env._ISEXE_TEST_PLATFORM_||process.platform,on=Ui==="win32"?sn:nn;T.isexe=on.isexe;T.sync=on.sync});var _n=O((Fc,mn)=>{var{isexe:Wi,sync:Fi}=an(),{join:Hi,delimiter:Gi,sep:cn,posix:ln}=require("path"),dn=process.platform==="win32",un=new RegExp(`[${ln.sep}${cn===ln.sep?"":cn}]`.replace(/(\\)/g,"\\$1")),qi=new RegExp(`^\\.${un.source}`),hn=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),pn=(r,{path:e=process.env.PATH,pathExt:t=process.env.PATHEXT,delimiter:n=Gi})=>{let s=r.match(un)?[""]:[...dn?[process.cwd()]:[],...(e||"").split(n)];if(dn){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:[""]}},fn=(r,e)=>{let t=/^".*"$/.test(r)?r.slice(1,-1):r;return(!t&&qi.test(e)?e.slice(0,2):"")+Hi(t,e)},gn=async(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=pn(r,e),i=[];for(let o of t){let c=fn(o,r);for(let a of n){let l=c+a;if(await Wi(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 hn(r)},Vi=(r,e={})=>{let{pathEnv:t,pathExt:n,pathExtExe:s}=pn(r,e),i=[];for(let o of t){let c=fn(o,r);for(let a of n){let l=c+a;if(Fi(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 hn(r)};mn.exports=gn;gn.sync=Vi});var K=O((Vc,kn)=>{"use strict";var vn=["nodebuffer","arraybuffer","fragments"],En=typeof Blob<"u";En&&vn.push("blob");kn.exports={BINARY_TYPES:vn,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:En,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var De=O((Kc,ot)=>{"use strict";var{EMPTY_BUFFER:zi}=K(),Qt=Buffer[Symbol.species];function Xi(r,e){if(r.length===0)return zi;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 Qt(t.buffer,t.byteOffset,n):t}function xn(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function In(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Qi(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Zt(r){if(Zt.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Qt(r):ArrayBuffer.isView(r)?e=new Qt(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Zt.readOnly=!1),e}ot.exports={concat:Xi,mask:xn,toArrayBuffer:Qi,toBuffer:Zt,unmask:In};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=require("bufferutil");ot.exports.mask=function(e,t,n,s,i){i<48?xn(e,t,n,s,i):r.mask(e,t,n,s,i)},ot.exports.unmask=function(e,t){e.length<32?In(e,t):r.unmask(e,t)}}catch{}});var Pn=O((Jc,Cn)=>{"use strict";var On=Symbol("kDone"),er=Symbol("kRun"),tr=class{constructor(e){this[On]=()=>{this.pending--,this[er]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[er]()}[er](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[On])}}};Cn.exports=tr});var me=O((Yc,Dn)=>{"use strict";var Re=require("zlib"),An=De(),Zi=Pn(),{kStatusCode:Tn}=K(),eo=Buffer[Symbol.species],to=Buffer.from([0,0,255,255]),ct=Symbol("permessage-deflate"),J=Symbol("total-length"),fe=Symbol("callback"),X=Symbol("buffers"),ge=Symbol("error"),at,rr=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,!at){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;at=new Zi(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[fe];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){at.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){at.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"?Re.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Re.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ct]=this,this._inflate[J]=0,this._inflate[X]=[],this._inflate.on("error",no),this._inflate.on("data",Nn)}this._inflate[fe]=n,this._inflate.write(e),t&&this._inflate.write(to),this._inflate.flush(()=>{let i=this._inflate[ge];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=An.concat(this._inflate[X],this._inflate[J]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[J]=0,this._inflate[X]=[],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"?Re.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Re.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[J]=0,this._deflate[X]=[],this._deflate.on("data",ro)}this._deflate[fe]=n,this._deflate.write(e),this._deflate.flush(Re.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=An.concat(this._deflate[X],this._deflate[J]);t&&(i=new eo(i.buffer,i.byteOffset,i.length-4)),this._deflate[fe]=null,this._deflate[J]=0,this._deflate[X]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};Dn.exports=rr;function ro(r){this[X].push(r),this[J]+=r.length}function Nn(r){if(this[J]+=r.length,this[ct]._maxPayload<1||this[J]<=this[ct]._maxPayload){this[X].push(r);return}this[ge]=new RangeError("Max payload size exceeded"),this[ge].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ge][Tn]=1009,this.removeListener("data",Nn),this.reset()}function no(r){if(this[ct]._inflate=null,this[ge]){this[fe](this[ge]);return}r[Tn]=1007,this[fe](r)}});var _e=O((zc,lt)=>{"use strict";var{isUtf8:Rn}=require("buffer"),{hasBlob:so}=K(),io=[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 oo(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function nr(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 ao(r){return so&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}lt.exports={isBlob:ao,isValidStatusCode:oo,isValidUTF8:nr,tokenChars:io};if(Rn)lt.exports.isValidUTF8=function(r){return r.length<24?nr(r):Rn(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=require("utf-8-validate");lt.exports.isValidUTF8=function(e){return e.length<32?nr(e):r(e)}}catch{}});var cr=O((Xc,Wn)=>{"use strict";var{Writable:co}=require("stream"),jn=me(),{BINARY_TYPES:lo,EMPTY_BUFFER:Ln,kStatusCode:uo,kWebSocket:ho}=K(),{concat:sr,toArrayBuffer:po,unmask:fo}=De(),{isValidStatusCode:go,isValidUTF8:Mn}=_e(),dt=Buffer[Symbol.species],B=0,$n=1,Bn=2,Un=3,ir=4,or=5,ut=6,ar=class extends co{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||lo[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ho]=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=B}_write(e,t,n){if(this._opcode===8&&this._state==B)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 dt(n.buffer,n.byteOffset+e,n.length-e),new dt(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 dt(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 B:this.getInfo(e);break;case $n:this.getPayloadLength16(e);break;case Bn:this.getPayloadLength64(e);break;case Un:this.getMask();break;case ir:this.getData(e);break;case or:case ut: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[jn.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=$n:this._payloadLength===127?this._state=Bn: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=Un:this._state=ir}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ir}getData(e){let t=Ln;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&&fo(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=or,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[jn.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===B&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=B;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=sr(n,t):this._binaryType==="arraybuffer"?s=po(sr(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=B):(this._state=ut,setImmediate(()=>{this.emit("message",s,!0),this._state=B,this.startLoop(e)}))}else{let s=sr(n,t);if(!this._skipUTF8Validation&&!Mn(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===or||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=B):(this._state=ut,setImmediate(()=>{this.emit("message",s,!1),this._state=B,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ln),this.end();else{let n=e.readUInt16BE(0);if(!go(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new dt(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mn(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=B;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=B):(this._state=ut,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=B,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[uo]=s,o}};Wn.exports=ar});var ur=O((Zc,Gn)=>{"use strict";var{Duplex:Qc}=require("stream"),{randomFillSync:mo}=require("crypto"),Fn=me(),{EMPTY_BUFFER:_o,kWebSocket:yo,NOOP:bo}=K(),{isBlob:ye,isValidStatusCode:wo}=_e(),{mask:Hn,toBuffer:re}=De(),U=Symbol("kByteLength"),So=Buffer.alloc(4),ht=8*1024,ne,be=ht,F=0,vo=1,Eo=2,lr=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=F,this.onerror=bo,this[yo]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||So,t.generateMask?t.generateMask(n):(be===ht&&(ne===void 0&&(ne=Buffer.alloc(ht)),mo(ne,0,ht),be=0),n[0]=ne[be++],n[1]=ne[be++],n[2]=ne[be++],n[3]=ne[be++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let c;typeof e=="string"?(!t.mask||o)&&t[U]!==void 0?c=t[U]:(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?(Hn(e,n,l,i,c),[l]):(Hn(e,n,e,0,c),[l,e])):[l,e]}close(e,t,n,s){let i;if(e===void 0)i=_o;else{if(typeof e!="number"||!wo(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={[U]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==F?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):ye(e)?(s=e.size,i=!1):(e=re(e),s=e.length,i=re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[U]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ye(e)?this._state!==F?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==F?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):ye(e)?(s=e.size,i=!1):(e=re(e),s=e.length,i=re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[U]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ye(e)?this._state!==F?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==F?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Fn.extensionName],i=t.binary?2:1,o=t.compress,c,a;typeof e=="string"?(c=Buffer.byteLength(e),a=!1):ye(e)?(c=e.size,a=!1):(e=re(e),c=e.length,a=re.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={[U]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:a,rsv1:o};ye(e)?this._state!==F?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==F?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[U],this._state=Eo,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(dr,this,c,s);return}this._bufferedBytes-=n[U];let o=re(i);t?this.dispatch(o,t,n,s):(this._state=F,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(ko,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Fn.extensionName];this._bufferedBytes+=n[U],this._state=vo,i.compress(e,n.fin,(o,c)=>{if(this._socket.destroyed){let a=new Error("The socket was closed while data was being compressed");dr(this,a,s);return}this._bufferedBytes-=n[U],this._state=F,n.readOnly=!1,this.sendFrame(r.frame(c,n),s),this.dequeue()})}dequeue(){for(;this._state===F&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][U],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][U],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)}};Gn.exports=lr;function dr(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 ko(r,e,t){dr(r,e,t),r.onerror(e)}});var Zn=O((el,Qn)=>{"use strict";var{kForOnEventAttribute:je,kListener:hr}=K(),qn=Symbol("kCode"),Vn=Symbol("kData"),Kn=Symbol("kError"),Jn=Symbol("kMessage"),Yn=Symbol("kReason"),we=Symbol("kTarget"),zn=Symbol("kType"),Xn=Symbol("kWasClean"),Y=class{constructor(e){this[we]=null,this[zn]=e}get target(){return this[we]}get type(){return this[zn]}};Object.defineProperty(Y.prototype,"target",{enumerable:!0});Object.defineProperty(Y.prototype,"type",{enumerable:!0});var se=class extends Y{constructor(e,t={}){super(e),this[qn]=t.code===void 0?0:t.code,this[Yn]=t.reason===void 0?"":t.reason,this[Xn]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[qn]}get reason(){return this[Yn]}get wasClean(){return this[Xn]}};Object.defineProperty(se.prototype,"code",{enumerable:!0});Object.defineProperty(se.prototype,"reason",{enumerable:!0});Object.defineProperty(se.prototype,"wasClean",{enumerable:!0});var Se=class extends Y{constructor(e,t={}){super(e),this[Kn]=t.error===void 0?null:t.error,this[Jn]=t.message===void 0?"":t.message}get error(){return this[Kn]}get message(){return this[Jn]}};Object.defineProperty(Se.prototype,"error",{enumerable:!0});Object.defineProperty(Se.prototype,"message",{enumerable:!0});var Le=class extends Y{constructor(e,t={}){super(e),this[Vn]=t.data===void 0?null:t.data}get data(){return this[Vn]}};Object.defineProperty(Le.prototype,"data",{enumerable:!0});var xo={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[je]&&s[hr]===e&&!s[je])return;let n;if(r==="message")n=function(i,o){let c=new Le("message",{data:o?i:i.toString()});c[we]=this,pt(e,this,c)};else if(r==="close")n=function(i,o){let c=new se("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[we]=this,pt(e,this,c)};else if(r==="error")n=function(i){let o=new Se("error",{error:i,message:i.message});o[we]=this,pt(e,this,o)};else if(r==="open")n=function(){let i=new Y("open");i[we]=this,pt(e,this,i)};else return;n[je]=!!t[je],n[hr]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[hr]===e&&!t[je]){this.removeListener(r,t);break}}};Qn.exports={CloseEvent:se,ErrorEvent:Se,Event:Y,EventTarget:xo,MessageEvent:Le};function pt(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ft=O((tl,es)=>{"use strict";var{tokenChars:Me}=_e();function q(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function Io(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&&Me[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 p=r.slice(a,d);l===44?(q(e,p,t),t=Object.create(null)):o=p,a=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===void 0)if(d===-1&&Me[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),q(t,r.slice(a,d),!0),l===44&&(q(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(Me[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);a===-1?a=u:n||(n=!0),s=!1}else if(i)if(Me[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&&Me[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 p=r.slice(a,d);n&&(p=p.replace(/\\/g,""),n=!1),q(t,c,p),l===44&&(q(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 f=r.slice(a,d);return o===void 0?q(e,f,t):(c===void 0?q(t,f,!0):n?q(t,c,f.replace(/\\/g,"")):q(t,c,f),q(e,o,t)),e}function Oo(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(", ")}es.exports={format:Oo,parse:Io}});var yt=O((sl,hs)=>{"use strict";var Co=require("events"),Po=require("https"),Ao=require("http"),ns=require("net"),To=require("tls"),{randomBytes:No,createHash:Do}=require("crypto"),{Duplex:rl,Readable:nl}=require("stream"),{URL:pr}=require("url"),Q=me(),Ro=cr(),jo=ur(),{isBlob:Lo}=_e(),{BINARY_TYPES:ts,CLOSE_TIMEOUT:Mo,EMPTY_BUFFER:gt,GUID:$o,kForOnEventAttribute:fr,kListener:Bo,kStatusCode:Uo,kWebSocket:D,NOOP:ss}=K(),{EventTarget:{addEventListener:Wo,removeEventListener:Fo}}=Zn(),{format:Ho,parse:Go}=ft(),{toBuffer:qo}=De(),is=Symbol("kAborted"),gr=[8,13],z=["CONNECTING","OPEN","CLOSING","CLOSED"],Vo=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,I=class r extends Co{constructor(e,t,n){super(),this._binaryType=ts[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=gt,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]),os(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ts.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 Ro({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new jo(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[D]=this,i[D]=this,e[D]=this,s.on("conclude",Yo),s.on("drain",zo),s.on("error",Xo),s.on("message",Qo),s.on("ping",Zo),s.on("pong",ea),i.onerror=ta,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ls),e.on("data",_t),e.on("end",ds),e.on("error",us),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[Q.extensionName]&&this._extensions[Q.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){L(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())}),cs(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){mr(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||gt,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){mr(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||gt,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){mr(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Q.extensionName]||(s.compress=!1),this._sender.send(e||gt,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){L(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(I,"CONNECTING",{enumerable:!0,value:z.indexOf("CONNECTING")});Object.defineProperty(I.prototype,"CONNECTING",{enumerable:!0,value:z.indexOf("CONNECTING")});Object.defineProperty(I,"OPEN",{enumerable:!0,value:z.indexOf("OPEN")});Object.defineProperty(I.prototype,"OPEN",{enumerable:!0,value:z.indexOf("OPEN")});Object.defineProperty(I,"CLOSING",{enumerable:!0,value:z.indexOf("CLOSING")});Object.defineProperty(I.prototype,"CLOSING",{enumerable:!0,value:z.indexOf("CLOSING")});Object.defineProperty(I,"CLOSED",{enumerable:!0,value:z.indexOf("CLOSED")});Object.defineProperty(I.prototype,"CLOSED",{enumerable:!0,value:z.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(I.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(I.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[fr])return e[Bo];return null},set(e){for(let t of this.listeners(r))if(t[fr]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[fr]:!0})}})});I.prototype.addEventListener=Wo;I.prototype.removeEventListener=Fo;hs.exports=I;function os(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Mo,protocolVersion:gr[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,!gr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${gr.join(", ")})`);let i;if(e instanceof pr)i=e;else try{i=new pr(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 h=new SyntaxError(a);if(r._redirects===0)throw h;mt(r,h);return}let l=o?443:80,d=No(16).toString("base64"),u=o?Po.request:Ao.request,f=new Set,p;if(s.createConnection=s.createConnection||(o?Jo:Ko),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&&(p=new Q({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Ho({[Q.extensionName]:p.offer()})),t.length){for(let h of t){if(typeof h!="string"||!Vo.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}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 h=s.path.split(":");s.socketPath=h[0],s.path=h[1]}let g;if(s.followRedirects){if(r._redirects===0){r._originalIpc=c,r._originalSecure=o,r._originalHostOrSocketPath=c?s.socketPath:i.host;let h=n&&n.headers;if(n={...n,headers:{}},h)for(let[m,x]of Object.entries(h))n.headers[m.toLowerCase()]=x}else if(r.listenerCount("redirect")===0){let h=c?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!h||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,h||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=r._req=u(s),r._redirects&&r.emit("redirect",r.url,g)}else g=r._req=u(s);s.timeout&&g.on("timeout",()=>{L(r,g,"Opening handshake has timed out")}),g.on("error",h=>{g===null||g[is]||(g=r._req=null,mt(r,h))}),g.on("response",h=>{let m=h.headers.location,x=h.statusCode;if(m&&s.followRedirects&&x>=300&&x<400){if(++r._redirects>s.maxRedirects){L(r,g,"Maximum redirects exceeded");return}g.abort();let S;try{S=new pr(m,e)}catch{let M=new SyntaxError(`Invalid URL: ${m}`);mt(r,M);return}os(r,S,t,n)}else r.emit("unexpected-response",g,h)||L(r,g,`Unexpected server response: ${h.statusCode}`)}),g.on("upgrade",(h,m,x)=>{if(r.emit("upgrade",h),r.readyState!==I.CONNECTING)return;g=r._req=null;let S=h.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){L(r,m,"Invalid Upgrade header");return}let P=Do("sha1").update(d+$o).digest("base64");if(h.headers["sec-websocket-accept"]!==P){L(r,m,"Invalid Sec-WebSocket-Accept header");return}let M=h.headers["sec-websocket-protocol"],w;if(M!==void 0?f.size?f.has(M)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":f.size&&(w="Server sent no subprotocol"),w){L(r,m,w);return}M&&(r._protocol=M);let k=h.headers["sec-websocket-extensions"];if(k!==void 0){if(!p){L(r,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let b;try{b=Go(k)}catch{L(r,m,"Invalid Sec-WebSocket-Extensions header");return}let v=Object.keys(b);if(v.length!==1||v[0]!==Q.extensionName){L(r,m,"Server indicated an extension that was not requested");return}try{p.accept(b[Q.extensionName])}catch{L(r,m,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Q.extensionName]=p}r.setSocket(m,x,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,r):g.end()}function mt(r,e){r._readyState=I.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Ko(r){return r.path=r.socketPath,ns.connect(r)}function Jo(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ns.isIP(r.host)?"":r.host),To.connect(r)}function L(r,e,t){r._readyState=I.CLOSING;let n=new Error(t);Error.captureStackTrace(n,L),e.setHeader?(e[is]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(mt,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function mr(r,e,t){if(e){let n=Lo(e)?e.size:qo(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${z[r.readyState]})`);process.nextTick(t,n)}}function Yo(r,e){let t=this[D];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[D]!==void 0&&(t._socket.removeListener("data",_t),process.nextTick(as,t._socket),r===1005?t.close():t.close(r,e))}function zo(){let r=this[D];r.isPaused||r._socket.resume()}function Xo(r){let e=this[D];e._socket[D]!==void 0&&(e._socket.removeListener("data",_t),process.nextTick(as,e._socket),e.close(r[Uo])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function rs(){this[D].emitClose()}function Qo(r,e){this[D].emit("message",r,e)}function Zo(r){let e=this[D];e._autoPong&&e.pong(r,!this._isServer,ss),e.emit("ping",r)}function ea(r){this[D].emit("pong",r)}function as(r){r.resume()}function ta(r){let e=this[D];e.readyState!==I.CLOSED&&(e.readyState===I.OPEN&&(e._readyState=I.CLOSING,cs(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function cs(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function ls(){let r=this[D];if(this.removeListener("close",ls),this.removeListener("data",_t),this.removeListener("end",ds),r._readyState=I.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[D]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",rs),r._receiver.on("finish",rs))}function _t(r){this[D]._receiver.write(r)||this.pause()}function ds(){let r=this[D];r._readyState=I.CLOSING,r._receiver.end(),this.end()}function us(){let r=this[D];this.removeListener("error",us),this.on("error",ss),r&&(r._readyState=I.CLOSING,this.destroy())}});var ms=O((ol,gs)=>{"use strict";var il=yt(),{Duplex:ra}=require("stream");function ps(r){r.emit("close")}function na(){!this.destroyed&&this._writableState.finished&&this.destroy()}function fs(r){this.removeListener("error",fs),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function sa(r,e){let t=!0,n=new ra({...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(ps,n);return}let o=!1;r.once("error",function(a){o=!0,i(a)}),r.once("close",function(){o||i(s),process.nextTick(ps,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",na),n.on("error",fs),n}gs.exports=sa});var _r=O((al,_s)=>{"use strict";var{tokenChars:ia}=_e();function oa(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&&ia[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}_s.exports={parse:oa}});var ks=O((ll,Es)=>{"use strict";var aa=require("events"),bt=require("http"),{Duplex:cl}=require("stream"),{createHash:ca}=require("crypto"),ys=ft(),ie=me(),la=_r(),da=yt(),{CLOSE_TIMEOUT:ua,GUID:ha,kWebSocket:pa}=K(),fa=/^[+/0-9A-Za-z]{22}==$/,bs=0,ws=1,vs=2,yr=class extends aa{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ua,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:da,...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=bt.createServer((n,s)=>{let i=bt.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=ga(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=bs}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===vs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick($e,this);return}if(e&&this.once("close",e),this._state!==ws)if(this._state=ws,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($e,this):process.nextTick($e,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{$e(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",Ss);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){oe(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){oe(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!fa.test(i)){oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Be(t,400);return}let a=e.headers["sec-websocket-protocol"],l=new Set;if(a!==void 0)try{l=la.parse(a)}catch{oe(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 f=new ie({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=ys.parse(d);p[ie.extensionName]&&(f.accept(p[ie.extensionName]),u[ie.extensionName]=f)}catch{oe(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={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(f,(p,g,h,m)=>{if(!p)return Be(t,g||401,h,m);this.completeUpgrade(u,i,l,e,t,n,s)});return}if(!this.options.verifyClient(f))return Be(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[pa])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>bs)return Be(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ca("sha1").update(t+ha).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[ie.extensionName]){let u=e[ie.extensionName].params,f=ys.format({[ie.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${f}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
24
24
|
`).join(`\r
|
|
25
|
-
`)),i.removeListener("error",
|
|
25
|
+
`)),i.removeListener("error",Ss),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($e,this)})),c(d,s)}};Es.exports=yr;function ga(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 $e(r){r._state=vs,r.emit("close")}function Ss(){this.destroy()}function Be(r,e,t,n){t=t||bt.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} ${bt.STATUS_CODES[e]}\r
|
|
26
26
|
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
27
27
|
`)+`\r
|
|
28
28
|
\r
|
|
29
|
-
`+t)}function
|
|
30
|
-
`,
|
|
31
|
-
`)[0].trim()||void 0}catch{return}}function ki(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=Ae.default.join(nn,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=ue.default.readdirSync(s)}catch{}i.sort((o,c)=>c.localeCompare(o));for(let o of i){let c=Ae.default.join(s,o,r.binary);if(ue.default.existsSync(c)){let a=ze(c);e.push({path:c,version:a})}}}else{let i=Ae.default.join(nn,n);if(ue.default.existsSync(i)){let o=ze(i);e.push({path:i,version:o})}}}return e}async function xi(r,e={}){if(e[r.key]){let n=e[r.key],s=ze(n);if(s)return{path:n,version:s}}try{let n=await(0,Wt.default)(r.binary);if(n&&ue.default.existsSync(n)){let s=ze(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=ki(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,Wt.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function Ft(r={}){let e=[];for(let t of he)try{let{path:n,version:s}=await xi(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:he.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function Ye(r){return ue.default.existsSync(Ae.default.join(process.env.HOME??"",r))}function Z(r){return!!process.env[r]}async function Oi(r){return new Promise(e=>{let t=sn.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 Xe=class{handles=new Map;nextInstanceId=1;lastErrors=new Map;livenessTimer=null;startLivenessCheck(e=6e4){this.livenessTimer||(this.livenessTimer=setInterval(()=>{for(let[t,n]of this.handles.entries()){if(n.killed)continue;let s=!1;try{s=process.kill(n.pid,0)}catch{s=!1}s||(console.warn("[daemon] pty.liveness.dead",{agentId:t,pid:n.pid}),this.handles.delete(t),n.onExit(137,"SIGKILL"))}},e),console.log("[daemon] pty.liveness.started",{intervalMs:e}))}stopLivenessCheck(){this.livenessTimer&&(clearInterval(this.livenessTimer),this.livenessTimer=null,console.log("[daemon] pty.liveness.stopped"))}spawn(e,t,n,s,i,o,c,a,l){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),p=Math.max(1,Math.min(500,o)),g={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(g.BRIDGE_SERVER_URL=l.serverUrl,g.BRIDGE_TOKEN=l.token,g.BRIDGE_WORKSPACE_ID=l.workspaceId,g.BRIDGE_PROJECT_ID=l.projectId||"",l.projectEnv&&Object.assign(g,l.projectEnv));let h=process.env.BRIDGE_MCP_URL;h&&(g.BRIDGE_MCP_URL=h);let f;try{f=an.spawn(n,s,{name:"xterm-256color",cols:u,rows:p,cwd:l?.cwd,env:g})}catch(S){let N=S instanceof Error?S.message:String(S);return this.lastErrors.set(e,N),console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:N}),!1}let m=this.nextInstanceId++,k={agentId:e,agentKey:t,process:f,pid:f.pid,killed:!1,instanceId:m,onExit:a};return f.onData(S=>{let N=this.handles.get(e);!N||N.instanceId!==m||k.killed||c(Buffer.from(S).toString("base64"))}),f.onExit(({exitCode:S,signal:N})=>{let y=this.handles.get(e);!y||y.instanceId!==m||k.killed||k.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:S,signal:N}),a(S??null,N?String(N):null))}),this.lastErrors.delete(e),this.handles.set(e,k),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){console.warn("[daemon] pty.write.no_handle",{agentId:e.slice(-8),source:n,dataLength:t.length});return}let i=Buffer.from(t,"base64").toString(),o=he.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)}getLastError(e){return this.lastErrors.get(e)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}getLiveAgentIds(){return[...this.handles.keys()]}};var Ko=_(rs(),1),Jo=_(ot(),1),Yo=_(ge(),1),zo=_(Zt(),1),Xo=_(rr(),1),Qo=_(cr(),1),us=_(dt(),1),Zo=_(ds(),1);var C=us.default;var W=_(require("fs")),L=_(require("path")),F=_(require("os")),ke=require("node:child_process"),qe=require("node:crypto");var hs=r=>r;var fs=r=>r,ps=r=>r;function dr(r){return(process.env.JERICO_FEATURES??"").split(",").map(t=>t.trim()).filter(Boolean).includes(r)}Se();gt();var Ue=_(require("fs")),fr=_(require("path")),bs=_(require("os")),ta=2e5;function ra(r){let e=fr.default.join(bs.default.homedir(),".claude","projects");if(Ue.default.existsSync(e))try{let t=Ue.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=fr.default.join(e,n.name,`${r}.jsonl`);if(Ue.default.existsSync(s))return s}}catch{}}function na(r){try{let t=Ue.default.readFileSync(r,"utf-8").trim().split(`
|
|
32
|
-
`)
|
|
33
|
-
`))
|
|
34
|
-
|
|
29
|
+
`+t)}function oe(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,oe),r.emit("wsClientError",o,t,e)}else Be(t,n,s,i)}});function Fe(){return process.env.BRIDGE_PROFILE||void 0}function Et(){let r=Fe();return r?ae.default.join(Ls,"profiles",r,"settings.json"):ae.default.join(Ls,"settings.json")}function He(){let r=Fe(),e=r?`${r}.daemon.lock`:"daemon.lock";return ae.default.join((0,We.homedir)(),".bridge",e)}function ke(){let r=Fe();return r?`com.jerico.bridge-agent.${r}.plist`:"com.jerico.bridge-agent.plist"}function kt(){let r=Fe(),e=r?`-${r}`:"";return{out:ae.default.join((0,We.homedir)(),`bridge-daemon${e}.log`),err:ae.default.join((0,We.homedir)(),`bridge-daemon${e}.err.log`)}}function Ms(){let r=Fe();return r?`:profile:${r}`:""}var We,ae,Ls,Ge=Ur(()=>{"use strict";We=require("node:os"),ae=_(require("path")),Ls=ae.default.join((0,We.homedir)(),".jerico")});var Bs={};yi(Bs,{getConfigPath:()=>Et,loadConfig:()=>ce,loadProjectSettings:()=>kr,saveConfig:()=>le});function qe(r,e){let t=r[e];if(!(!t||typeof t!="object"||Array.isArray(t)))return Object.fromEntries(Object.entries(t).filter(([,n])=>typeof n=="string"))}function ce(){let r=Et(),e=H.default.existsSync(r)?r:Ia;if(!H.default.existsSync(e)){let p=process.env.BRIDGE_PROFILE?`bridge-agent --profile ${process.env.BRIDGE_PROFILE} auth`:"bridge-agent auth";console.error(`[bridge] Config not found. Run: ${p}`),process.exit(1)}let t=H.default.readFileSync(e,"utf-8"),n;try{n=JSON.parse(t)}catch{console.error("[bridge] Invalid config file at",e),process.exit(1)}(!n||typeof n!="object")&&(console.error("[bridge] Config must be a JSON object. Run: bridge-agent auth"),process.exit(1));let s=n,i=typeof s.server=="string"?s.server:"",o=typeof s.token=="string"?s.token:"",c=typeof s.name=="string"?s.name:"bridge-agent",a=[/23-88-110-113\.sslip\.io/i,/23\.88\.110\.113:443\/ws\/daemon$/,/23\.88\.110\.113:3100\/ws\/daemon$/],l="wss://lcars.jerico.appnova.io/ws/daemon";if(i&&a.some(p=>p.test(i))){console.warn(`[daemon] config.url_migration: migrating stale URL ${i} \u2192 ${l}`),i=l,s.server=i;try{H.default.writeFileSync(e,JSON.stringify(s,null,2),{mode:384}),H.default.chmodSync(e,384)}catch(p){console.warn("[daemon] config.url_migration: failed to save migrated config",String(p))}}(!i||!o)&&(console.error("[bridge] Config missing server or token. Run: bridge-agent auth"),process.exit(1));let d={server:i,token:o,name:c},u=qe(s,"agentPaths"),f=qe(s,"projectPaths");return u&&(d.agentPaths=u),f&&(d.projectPaths=f),d}function le(r){let e=Et(),t=xt.default.dirname(e);H.default.existsSync(t)||H.default.mkdirSync(t,{recursive:!0}),H.default.writeFileSync(e,JSON.stringify(r,null,2),{mode:384})}function kr(r){let e=xt.default.join(r??process.cwd(),".jerico","settings.json");if(!H.default.existsSync(e))return{};try{let t=H.default.readFileSync(e,"utf-8"),n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return{};let s=n,i={};typeof s.preferredAgent=="string"&&(i.preferredAgent=s.preferredAgent);let o=qe(s,"hooks"),c=qe(s,"env"),a=qe(s,"agentPaths");return o&&(i.hooks=o),c&&(i.env=c),a&&(i.agentPaths=a),i}catch{return console.warn("[bridge] Failed to parse .jerico/settings.json, ignoring"),{}}}var H,xt,$s,Ia,xe=Ur(()=>{"use strict";H=_(require("fs")),xt=_(require("path")),$s=_(require("os"));Ge();Ia=xt.default.join($s.default.homedir(),".bridge","config.json")});var Zr=_(Qr(),1),{program:Ac,createCommand:Tc,createArgument:Nc,createOption:Dc,CommanderError:Rc,InvalidArgumentError:jc,InvalidOptionArgumentError:Lc,Command:en,Argument:Mc,Option:$c,Help:Bc}=Zr.default;var Zs=require("node:http"),ue=require("node:child_process"),A=require("node:fs"),Pe=require("node:os"),j=_(require("path"));var Sn=_(require("node-pty"));var zt=_(_n()),he=_(require("fs")),Ne=_(require("path")),bn=_(require("net")),wn=require("child_process"),rt=r=>r+`
|
|
30
|
+
`,Te=r=>r.replace(/[\r\n]+$/,"")+"\r",pe=[{key:"sh",displayName:"Shell",binary:"sh",checkAuth:async()=>!0,formatInput:rt},{key:"claude",displayName:"Claude Code",binary:"claude",checkAuth:async()=>nt(".claude")||te("ANTHROPIC_API_KEY"),assignSessionId:!0,spawnArgs:["--dangerously-skip-permissions"],resumeArgs:r=>["--dangerously-skip-permissions","--resume",r],supportsMcpConfig:!0,formatInput:Te,versionDirGlobs:[".local/share/claude/versions/*"]},{key:"codex",displayName:"Codex CLI",binary:"codex",checkAuth:async()=>te("OPENAI_API_KEY"),spawnArgs:["--full-auto"],supportsMcpConfig:!0,formatInput:Te},{key:"qwen",displayName:"Qwen CLI",binary:"qwen",checkAuth:async()=>nt(".qwen"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["--resume",r,"--yolo"],supportsMcpConfig:!0,formatInput:Te,versionDirGlobs:[".local/share/qwen/versions/*"]},{key:"gemini",displayName:"Gemini",binary:"gemini",checkAuth:async()=>te("GEMINI_API_KEY"),supportsMcpConfig:!0,formatInput:rt},{key:"ollama",displayName:"Ollama",binary:"ollama",checkAuth:async()=>Yi(11434),formatInput:rt},{key:"aider",displayName:"Aider",binary:"aider",checkAuth:async()=>te("OPENAI_API_KEY")||te("ANTHROPIC_API_KEY"),supportsMcpConfig:!0,formatInput:rt},{key:"kimi",displayName:"Kimi Code",binary:"kimi",checkAuth:async()=>nt(".kimi")||te("KIMI_API_KEY"),assignSessionId:!0,spawnArgs:["--yolo"],resumeArgs:r=>["-r",r,"--yolo"],supportsMcpConfig:!0,formatInput:Te,versionDirGlobs:[".local/share/uv/tools/kimi-cli/bin",".local/share/kimi/versions/*"]},{key:"forge",displayName:"Forge",binary:"forge",checkAuth:async()=>nt(".forge/.credentials.json")||te("FORGE_API_KEY"),assignSessionId:!0,resumeArgs:r=>["--conversation-id",r],supportsMcpConfig:!0,formatInput:Te}];var yn=process.env.HOME??"/Users/unknown";function st(r){try{let e=(0,wn.spawnSync)(r,["--version"],{timeout:5e3});return e.status!==0?void 0:(e.stdout??e.stderr??Buffer.from("")).toString("utf8").split(`
|
|
31
|
+
`)[0].trim()||void 0}catch{return}}function Ki(r){if(!r.versionDirGlobs?.length)return[];let e=[],t=r.versionDirGlobs;for(let n of t){let s=Ne.default.join(yn,n.replace(/\/\*$/,""));if(n.endsWith("/*")){let i=[];try{i=he.default.readdirSync(s)}catch{}i.sort((o,c)=>c.localeCompare(o));for(let o of i){let c=Ne.default.join(s,o,r.binary);if(he.default.existsSync(c)){let a=st(c);e.push({path:c,version:a})}}}else{let i=Ne.default.join(yn,n);if(he.default.existsSync(i)){let o=st(i);e.push({path:i,version:o})}}}return e}async function Ji(r,e={}){if(e[r.key]){let n=e[r.key],s=st(n);if(s)return{path:n,version:s}}try{let n=await(0,zt.default)(r.binary);if(n&&he.default.existsSync(n)){let s=st(n);if(s!==void 0)return{path:n,version:s}}}catch{}let t=Ki(r);for(let n of t)if(n.version!==void 0)return n;try{let n=await(0,zt.default)(r.binary);if(n)return{path:n}}catch{}throw new Error(`No working binary found for agent '${r.key}'`)}async function Xt(r={}){let e=[];for(let t of pe)try{let{path:n,version:s}=await Ji(t,r),o=await t.checkAuth()?"ok":"missing";e.push({key:t.key,displayName:t.displayName,binaryPath:n,authStatus:o,version:s})}catch{}return console.log("[daemon] agent.detect.done",{found:e.map(t=>t.key),missing:pe.map(t=>t.key).filter(t=>!e.find(n=>n.key===t))}),e}function nt(r){return he.default.existsSync(Ne.default.join(process.env.HOME??"",r))}function te(r){return!!process.env[r]}async function Yi(r){return new Promise(e=>{let t=bn.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 it=class{handles=new Map;nextInstanceId=1;lastErrors=new Map;livenessTimer=null;startLivenessCheck(e=6e4){this.livenessTimer||(this.livenessTimer=setInterval(()=>{for(let[t,n]of this.handles.entries()){if(n.killed)continue;let s=!1;try{s=process.kill(n.pid,0)}catch{s=!1}s||(console.warn("[daemon] pty.liveness.dead",{agentId:t,pid:n.pid}),this.handles.delete(t),n.onExit(137,"SIGKILL"))}},e),console.log("[daemon] pty.liveness.started",{intervalMs:e}))}stopLivenessCheck(){this.livenessTimer&&(clearInterval(this.livenessTimer),this.livenessTimer=null,console.log("[daemon] pty.liveness.stopped"))}spawn(e,t,n,s,i,o,c,a,l){let d=this.handles.get(e);d&&(console.warn("[daemon] pty.spawn.replace_existing",{agentId:e,oldPid:d.pid,newAgentKey:t}),this.kill(e,!0));let u=Math.max(1,Math.min(500,i)),f=Math.max(1,Math.min(500,o)),p={...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"};l&&(p.BRIDGE_SERVER_URL=l.serverUrl,p.BRIDGE_TOKEN=l.token,p.BRIDGE_WORKSPACE_ID=l.workspaceId,p.BRIDGE_PROJECT_ID=l.projectId||"",l.projectEnv&&Object.assign(p,l.projectEnv));let g=process.env.BRIDGE_MCP_URL;g&&(p.BRIDGE_MCP_URL=g);let h;try{h=Sn.spawn(n,s,{name:"xterm-256color",cols:u,rows:f,cwd:l?.cwd,env:p})}catch(S){let P=S instanceof Error?S.message:String(S);return this.lastErrors.set(e,P),console.error("[daemon] pty.spawn.failed",{agentId:e,agentKey:t,error:P}),!1}let m=this.nextInstanceId++,x={agentId:e,agentKey:t,process:h,pid:h.pid,killed:!1,instanceId:m,onExit:a};return h.onData(S=>{let P=this.handles.get(e);!P||P.instanceId!==m||x.killed||c(Buffer.from(S).toString("base64"))}),h.onExit(({exitCode:S,signal:P})=>{let M=this.handles.get(e);!M||M.instanceId!==m||x.killed||x.killed||(this.handles.delete(e),console.log("[daemon] pty.exit",{agentId:e,exitCode:S,signal:P}),a(S??null,P?String(P):null))}),this.lastErrors.delete(e),this.handles.set(e,x),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){console.warn("[daemon] pty.write.no_handle",{agentId:e.slice(-8),source:n,dataLength:t.length});return}let i=Buffer.from(t,"base64").toString(),o=pe.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)}getLastError(e){return this.lastErrors.get(e)}killAll(){for(let e of this.handles.values())try{process.kill(-e.pid,"SIGTERM")}catch{e.process.kill()}this.handles.clear()}getLiveAgentIds(){return[...this.handles.keys()]}};var ma=_(ms(),1),_a=_(ft(),1),ya=_(me(),1),ba=_(cr(),1),wa=_(ur(),1),Sa=_(_r(),1),xs=_(yt(),1),va=_(ks(),1);var E=xs.default;var G=_(require("fs")),R=_(require("path")),W=_(require("os")),Ce=require("node:child_process"),Xe=require("node:crypto");var Is=r=>r;var Os=r=>r,Cs=r=>r;function br(r){return(process.env.JERICO_FEATURES??"").split(",").map(t=>t.trim()).filter(Boolean).includes(r)}var Ps=_(require("os"));async function wr(){return Ps.default.platform()!=="darwin"?null:{key:"sim_ios",displayName:"iOS Simulator",binaryPath:"xcrun",authStatus:"ok"}}var Ee=require("child_process"),Rs=require("fs/promises"),js=require("crypto"),ve=_(require("fs")),St=_(require("path")),vr=_(require("os"));var Ue=require("child_process"),As=require("fs/promises"),Ts=_(require("path")),Ns=_(require("os"));async function Ea(){return new Promise(r=>{let e=(0,Ue.spawn)("xcrun",["simctl","list","devices","booted","--json"],{timeout:5e3}),t="";e.stdout.on("data",n=>{t+=n.toString("utf8")}),e.on("close",n=>{if(n!==0){r(null);return}try{let s=JSON.parse(t);for(let i of Object.values(s.devices)){let o=i.find(c=>c.state==="Booted");if(o){r(o.udid);return}}r(null)}catch{r(null)}}),e.on("error",()=>r(null))})}async function ka(){return new Promise(r=>{let e=(0,Ue.spawn)("xcrun",["simctl","list","devices","available","--json"],{timeout:5e3}),t="";e.stdout.on("data",n=>{t+=n.toString("utf8")}),e.on("close",n=>{if(n!==0){r([]);return}try{let s=JSON.parse(t),i=[];for(let[o,c]of Object.entries(s.devices)){for(let a of c){let l=o.replace(/^com\.apple\.CoreSimulator\.SimRuntime\./,"").replace(/-/g,".");if(i.push(`${a.name} (${l})`),i.length>=3)break}if(i.length>=3)break}r(i)}catch{r([])}}),e.on("error",()=>r([]))})}async function Sr(r){let e=[],t=null,n=await new Promise(i=>{let o=(0,Ue.spawn)("xcrun",["simctl","help"],{timeout:2e3});o.on("close",c=>i(c===0)),o.on("error",()=>i(!1)),o.stdout?.resume(),o.stderr?.resume()});e.push({id:"xcrun_exists",status:n?"pass":"fail",label:"Xcode CLI tools",detail:n?void 0:"Xcode command-line tools not found. Install them to use the iOS Simulator panel.",fixCmd:n?void 0:"xcode-select --install"});let s=!1;if(n){let i=Ts.default.join(Ns.default.homedir(),".local/bin/idb");s=await(0,As.access)(i).then(()=>!0).catch(()=>!1)}if(e.push({id:"idb_present",status:s?"pass":"fail",label:"idb",detail:s?void 0:"idb not found at ~/.local/bin/idb. Required for simulator automation.",fixCmd:s?void 0:"pip3 install fb-idb && brew install facebook/fb/idb-companion"}),n){let i=await new Promise(o=>{let c=(0,Ue.spawn)("xcrun",["simctl","list","--json"],{timeout:5e3});c.on("close",a=>o(a===0)),c.on("error",()=>o(!1)),c.stdout?.resume(),c.stderr?.resume()});if(e.push({id:"simctl_ok",status:i?"pass":"fail",label:"simctl",detail:i?void 0:"simctl is not responding. Xcode may not be fully installed.",fixCmd:i?void 0:"sudo xcode-select --reset"}),i)if(t=await Ea(),t)e.push({id:"booted_simulator",status:"pass",label:"Booted simulator"});else{let o=await ka();e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:o.length>0?`No simulator is booted. Available: ${o.join(", ")}. Open Simulator.app and boot one.`:"No simulator is booted and no devices found. Open Xcode \u2192 Window \u2192 Devices and Simulators to add one.",fixCmd:"open -a Simulator"})}else e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"})}else e.push({id:"simctl_ok",status:"fail",label:"simctl",detail:"Skipped \u2014 previous check failed"}),e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"});return{checks:e,udid:t}}var Er=St.default.join(vr.default.homedir(),".local/bin/idb");async function Ds(r){try{let e=await new Promise((i,o)=>{let c=(0,Ee.spawn)(Er,["describe","--udid",r,"--json"],{timeout:1e4}),a="",l="";c.stdout.on("data",d=>{a+=d.toString("utf8")}),c.stderr.on("data",d=>{l+=d.toString("utf8")}),c.on("close",d=>{d!==0?o(new Error(l||`idb exited ${d}`)):i(a)}),c.on("error",d=>o(d))}),t=JSON.parse(e),n=t.screen_dimensions?.width_points,s=t.screen_dimensions?.height_points;if(Number.isFinite(n)&&Number.isFinite(s))return{width:n,height:s}}catch(e){console.warn("[daemon] simulator.metadata.error",{udid:r,error:String(e)})}return{}}function xa(r,e){let t=`/tmp/sim_frame_${e}.png`;return new Promise(n=>{let s=(0,Ee.spawn)("xcrun",["simctl","io",r,"screenshot",t],{stdio:["ignore","ignore","ignore"]});s.on("close",async i=>{if(i!==0){n(null);return}try{n(await(0,Rs.readFile)(t))}catch{n(null)}}),s.on("error",()=>n(null))})}function wt(r,e){return new Promise((t,n)=>{let s=(0,Ee.spawn)(Er,[...e,"--udid",r],{timeout:15e3}),i="";s.stderr.on("data",o=>{i+=o.toString("utf8")}),s.on("close",o=>{o!==0?n(new Error(i||`idb exited ${o}`)):t()}),s.on("error",o=>n(o))})}var vt=class{sessions=new Map;pendingSubscriptions=new Set;pendingUdids=new Map;ws=null;daemonId;installProc=new Map;cancelledInstalls=new Set;constructor(e){this.daemonId=e}updateWs(e){this.ws=e}async start(e){if(this.sessions.has(e)){console.warn("[daemon] simulator.start: session already exists",{agentId:e});return}let{checks:t,udid:n}=await Sr(e);if(this.sendSimHealth(e,t),t.find(d=>d.status==="fail"))return;if(!n){this.sendError(e,"SPAWN_FAILED","No booted iOS simulator found");return}let i=[...this.sessions.values()].find(d=>d.udid===n);if(i){this.sendError(e,"DUPLICATE_SIMULATOR",`Simulator already attached as agent ${i.agentId}`,{existingAgentId:i.agentId,udid:n});return}let o=this.pendingUdids.get(n);if(o&&o!==e){this.sendError(e,"DUPLICATE_SIMULATOR",`Simulator already being attached as agent ${o}`,{existingAgentId:o,udid:n});return}this.pendingUdids.set(n,e);let c=this.pendingSubscriptions.has(e);this.pendingSubscriptions.delete(e);let a=await Ds(n);a.width!=null&&a.height!=null&&console.log("[daemon] simulator.metadata",{agentId:e,udid:n,logicalWidth:a.width,logicalHeight:a.height});let l={agentId:e,udid:n,frameInterval:null,capturing:!1,subscribed:c,logicalWidth:a.width,logicalHeight:a.height,lastDescribeAt:Date.now()};if(this.sessions.set(e,l),this.pendingUdids.delete(n),l.frameInterval=setInterval(async()=>{if(!(!l.subscribed||l.capturing)){l.capturing=!0;try{Date.now()-l.lastDescribeAt>=5e3&&(l.lastDescribeAt=Date.now(),Ds(n).then(u=>{u.width!=null&&u.height!=null&&(u.width!==l.logicalWidth||u.height!==l.logicalHeight)&&(console.log("[daemon] simulator.metadata.update",{agentId:e,udid:n,from:{logicalWidth:l.logicalWidth,logicalHeight:l.logicalHeight},to:u}),l.logicalWidth=u.width,l.logicalHeight=u.height)}).catch(()=>{}));let d=await xa(n,e);d&&this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"sim_frame",agentId:e,image:d.toString("base64"),width:l.logicalWidth,height:l.logicalHeight}))}catch(d){console.error("[daemon] simulator.capture.error",{agentId:e,error:String(d)})}finally{l.capturing=!1}}},200),this.ws&&this.ws.readyState===E.OPEN){let d=(0,js.randomUUID)();this.ws.send(JSON.stringify({type:"session_started",agentId:e,sessionId:d})),this.ws.send(JSON.stringify({type:"agent_spawned",agentId:e,agentKey:"sim_ios",daemonId:this.daemonId}))}console.log("[daemon] simulator.started",{agentId:e,udid:n})}stop(e){let t=this.sessions.get(e);if(!t){for(let[n,s]of this.pendingUdids)if(s===e){this.pendingUdids.delete(n);break}return}t.frameInterval&&clearInterval(t.frameInterval),this.sessions.delete(e),this.pendingUdids.delete(t.udid),this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"exit",agentId:e,exitCode:0,signal:null}))}stopAll(){for(let e of[...this.sessions.keys()])this.stop(e);for(let[e,t]of this.installProc)t.kill("SIGTERM"),this.installProc.delete(e)}subscribe(e){let t=this.sessions.get(e);t&&(t.subscribed=!0)}unsubscribe(e){let t=this.sessions.get(e);t&&(t.subscribed=!1)}async handle(e){let t=this.sessions.get(e.agentId);if(e.type==="sim_subscribe"){t?this.subscribe(e.agentId):this.pendingSubscriptions.add(e.agentId);return}if(e.type==="sim_unsubscribe"){this.pendingSubscriptions.delete(e.agentId),t&&this.unsubscribe(e.agentId);return}if(e.type==="sim_healthcheck"){let{checks:n}=await Sr(e.agentId);this.sendSimHealth(e.agentId,n);return}if(e.type==="sim_install_run"){await this.handleSimInstallRun(e.agentId);return}if(e.type==="sim_install_cancel"){this.handleSimInstallCancel(e.agentId);return}if(!t){console.warn("[daemon] simulator.handle: no session",{agentId:e.agentId,type:e.type});return}try{switch(e.type){case"sim_tap":{await wt(t.udid,["ui","tap",String(e.x),String(e.y)]);break}case"sim_swipe":{await wt(t.udid,["ui","swipe",String(e.x1),String(e.y1),String(e.x2),String(e.y2),"--duration",String(e.duration??.5)]);break}case"sim_key":{await wt(t.udid,["ui","text",e.key]);break}case"sim_button":{console.log("[daemon] simulator.button.start",{agentId:e.agentId,button:e.button,udid:t.udid}),await wt(t.udid,["ui","button",e.button]),console.log("[daemon] simulator.button.done",{agentId:e.agentId,button:e.button});break}case"sim_get_source":{let n=await new Promise((s,i)=>{let o=(0,Ee.spawn)(Er,["ui","describe-all","--udid",t.udid],{timeout:15e3}),c="",a="";o.stdout.on("data",l=>{c+=l.toString("utf8")}),o.stderr.on("data",l=>{a+=l.toString("utf8")}),o.on("close",l=>{l!==0?i(new Error(a||`idb exited ${l}`)):s(c)}),o.on("error",l=>i(l))});this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"sim_source",agentId:e.agentId,source:n}));break}}}catch(n){console.error("[daemon] simulator.handle.error",{agentId:e.agentId,type:e.type,error:String(n)})}}sendError(e,t,n,s){this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"error",code:t,message:n,agentId:e,...s}))}sendSimHealth(e,t){this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"sim_health",agentId:e,checks:t}))}resolveSimInstallScript(){let e=process.env.BRIDGE_SIM_INSTALL_SCRIPT;if(e)return e;let t=St.default.join(vr.default.homedir(),".bridge/install-sim-prereqs.sh");if(ve.default.existsSync(t))return t;let n=St.default.join(__dirname,"../../../scripts/install-sim-prereqs.sh");return ve.default.existsSync(n)?n:null}async handleSimInstallRun(e){if(this.installProc.has(e)){this.sendInstallProgress(e,{step:"error",error:"already installing"});return}this.cancelledInstalls.delete(e);let t=this.resolveSimInstallScript();if(!t){this.sendInstallProgress(e,{step:"error",error:"install script not found"});return}try{ve.default.accessSync(t,ve.default.constants.F_OK|ve.default.constants.X_OK)}catch{this.sendInstallProgress(e,{step:"error",error:`install script not found at ${t}`});return}let n=(0,Ee.spawn)("bash",["-lc",t],{timeout:6e5});this.installProc.set(e,n);let s="pre_check",i="",o="";n.stdout?.on("data",c=>{i+=c.toString("utf8");let a;for(;(a=i.indexOf(`
|
|
32
|
+
`))!==-1;){let l=i.slice(0,a);i=i.slice(a+1),l&&(l.startsWith("STEP:")?(s=l.slice(5).trim(),this.sendInstallProgress(e,{step:s})):this.sendInstallProgress(e,{stream:"stdout",line:l}))}}),n.stderr?.on("data",c=>{o+=c.toString("utf8");let a;for(;(a=o.indexOf(`
|
|
33
|
+
`))!==-1;){let l=o.slice(0,a);o=o.slice(a+1),l&&this.sendInstallProgress(e,{stream:"stderr",line:l})}}),n.on("close",c=>{if(this.installProc.delete(e),i){let l=i;i="",l.startsWith("STEP:")?(s=l.slice(5).trim(),this.sendInstallProgress(e,{step:s})):this.sendInstallProgress(e,{stream:"stdout",line:l})}if(o){let l=o;o="",this.sendInstallProgress(e,{stream:"stderr",line:l})}let a=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!a&&(c===0?this.sendInstallProgress(e,{step:"done",exitCode:0}):this.sendInstallProgress(e,{step:"error",exitCode:c??void 0,error:`install script exited with code ${c}`}))}),n.on("error",c=>{this.installProc.delete(e);let a=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!a&&this.sendInstallProgress(e,{step:"error",error:String(c)})})}handleSimInstallCancel(e){let t=this.installProc.get(e);t&&(this.cancelledInstalls.add(e),t.kill("SIGTERM"),this.installProc.delete(e),this.sendInstallProgress(e,{step:"error",error:"cancelled by user"}))}sendInstallProgress(e,t){this.ws&&this.ws.readyState===E.OPEN&&this.ws.send(JSON.stringify({type:"sim_install_progress",agentId:e,...t}))}};xe();Ge();var Ve=_(require("fs")),xr=_(require("path")),Us=_(require("os")),Oa=2e5;function Ca(r){let e=xr.default.join(Us.default.homedir(),".claude","projects");if(Ve.default.existsSync(e))try{let t=Ve.default.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory());for(let n of t){let s=xr.default.join(e,n.name,`${r}.jsonl`);if(Ve.default.existsSync(s))return s}}catch{}}function Pa(r){try{let t=Ve.default.readFileSync(r,"utf-8").trim().split(`
|
|
34
|
+
`);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/Oa*100)),usedTokens:a}}catch{continue}}}catch{}return null}function Ir(r,e,t){let n,s=-1,i=()=>{if(n||(n=Ca(e)),!n)return;let a=Pa(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 Z=_(require("fs")),Ke=_(require("path")),Or=_(require("os")),Ws=300*60*1e3,Fs={free:10,pro:40,max_5x:200,max_20x:200};function Aa(){let r=Ke.default.join(Or.default.homedir(),".jerico","settings.json");try{if(!Z.default.existsSync(r))return"pro";let t=JSON.parse(Z.default.readFileSync(r,"utf-8")).claudeTier;if(typeof t=="string"&&t in Fs)return t}catch{}return"pro"}function Ta(){let r=Ke.default.join(Or.default.homedir(),".claude","projects");if(!Z.default.existsSync(r))return{prompts5h:0,resetAt:0};let t=Date.now()-Ws,n=1/0,s=0;try{let o=Z.default.readdirSync(r,{withFileTypes:!0}).filter(c=>c.isDirectory());for(let c of o){let a=Ke.default.join(r,c.name),l;try{l=Z.default.readdirSync(a).filter(d=>d.endsWith(".jsonl"))}catch{continue}for(let d of l){let u=Ke.default.join(a,d),f;try{if(Z.default.statSync(u).size>20*1024*1024)continue;f=Z.default.readFileSync(u,"utf-8")}catch{continue}for(let p of f.split(`
|
|
35
|
+
`)){let g=p.trim();if(g)try{let h=JSON.parse(g);if(h.type!=="user"||h.message?.role!=="user"||h.userType!==void 0&&h.userType!=="external")continue;let x=h.timestamp;if(typeof x!="string")continue;let S=Date.parse(x);if(isNaN(S)||S<t)continue;s++,S<n&&(n=S)}catch{continue}}}}}catch{}let i=isFinite(n)?n+Ws:0;return{prompts5h:s,resetAt:i}}function Hs(r){let e=()=>{let n=Aa(),s=Fs[n]??40,{prompts5h:i,resetAt:o}=Ta();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 Ie=_(require("os")),It=_(require("fs")),Pr=require("node:child_process");function qs(){let r=0,e=0;for(let t of Ie.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 Cr=qs();function Na(){let r=qs(),e=r.idle-Cr.idle,t=r.total-Cr.total;return Cr=r,t===0?0:Math.round((1-e/t)*100)}function Da(){let r=Ie.default.totalmem(),e=Ie.default.freemem(),t=0;try{let n=(0,Pr.spawnSync)("vm_stat",["-c","10"],{encoding:"utf-8",timeout:2e3,stdio:"pipe"});if(n.status===0&&n.stdout){let s=n.stdout.match(/page size of (\d+) bytes/),i=n.stdout.match(/Pages speculative:\s*(\d+)/),o=n.stdout.match(/Pages inactive:\s*(\d+)/);if(i&&o){let c=s?parseInt(s[1],10):4096;t=(parseInt(i[1],10)+parseInt(o[1],10))*c}}}catch{}return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:Math.round(t/1024/1024)}}function Ra(){if(process.platform==="darwin")return Da();let r=Ie.default.totalmem(),e=Ie.default.freemem();return{totalMb:Math.round(r/1024/1024),usedMb:Math.round((r-e)/1024/1024),cachedMb:0}}function ja(){try{let r=(0,Pr.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 La(){try{let r="/sys/class/power_supply",e=It.default.readdirSync(r).filter(o=>/^BAT/i.test(o));if(e.length===0)return;let t=`${r}/${e[0]}`,n=parseInt(It.default.readFileSync(`${t}/capacity`,"utf-8").trim(),10),s=It.default.readFileSync(`${t}/status`,"utf-8").trim().toLowerCase();return{percent:n,charging:s==="charging"||s==="full"}}catch{return}}function Gs(){let r=process.platform;if(r==="darwin")return ja();if(r==="linux")return La()}var Ma=1e4,$a=3;function Vs(r){let e=0,t=Gs(),n=setInterval(()=>{e++,e%$a===0&&(t=Gs());let s=Ra();r({cpu:Na(),ramUsedMb:s.usedMb,ramTotalMb:s.totalMb,ramCachedMb:s.cachedMb,battery:t})},Ma);return()=>clearInterval(n)}var Ot=_(require("fs")),Ct=_(require("path")),Ks=_(require("node-pty"));function Ba(){try{let r=require.resolve("node-pty"),e=Ct.default.resolve(Ct.default.dirname(r),"..");return Ct.default.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper")}catch{return}}function Js(){let r=Ba();if(!r||!Ot.default.existsSync(r))return!0;try{Ot.default.accessSync(r,Ot.default.constants.X_OK)}catch{return!1}try{Ks.spawn("/bin/sh",[],{name:"xterm-256color",cols:80,rows:24}).kill()}catch{return!1}return!0}var de=new Map,Ar,Pt;function Rr(){try{return(0,Xe.createHash)("sha256").update(W.default.hostname()+":"+W.default.userInfo().username+Ms()).digest("hex")}catch{return"unknown"}}var Je=[];function Ua(r){let e=Date.now(),t=e-3e4;for(;Je.length&&Je[0].ts<t;)Je.shift();return Je.push({agentKey:r,ts:e}),new Set(Je.map(s=>s.agentKey)).size>=2}var Wa=r=>r.replace(/[\r\n]+$/,"")+"\r",Nr=null,Fa=Hs(r=>{Nr=r}),Ha=Number(process.env.BRIDGE_KEEPALIVE_MS)||3e4,Ga=Number(process.env.BRIDGE_PONG_DEADLINE_MS)||5e3,qa=5e3,Va=400;function Ka(r){return r.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}function Ja(r,e=Va){return r.length<=e?r:`${r.slice(0,e)}...`}function Ya(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}function Qe(){let r=G.default.realpathSync(process.argv[1]??""),e=R.default.dirname(r);return[R.default.resolve(e,"../../mcp-server/dist/index.cjs"),R.default.resolve(e,"bridge-mcp.cjs"),R.default.resolve(process.cwd(),"node_modules/.bin/bridge-mcp")].find(n=>G.default.existsSync(n))??"bridge-mcp"}function za(r){try{let e=process.env.BRIDGE_MCP_URL,t=r.projectId||"workspace",n=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${t}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:Qe(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:t,BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},s=R.default.join(W.default.tmpdir(),`bridge-mcp-${r.agentId??t}.json`);return G.default.writeFileSync(s,JSON.stringify(n,null,2)+`
|
|
36
|
+
`,"utf-8"),console.log("[daemon] mcp.config.written",{tmpPath:s,transport:e?"http":"stdio"}),["--mcp-config",s]}catch(e){return console.warn("[daemon] mcp.config.build.failed",{error:String(e)}),[]}}var Xa={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",bridge_list_groups:"List all agent groups and their member agentIds",bridge_get_group_status:"Get agents in a group with status and last output line",bridge_dispatch_to_group:"Send a text message/command to every agent in a group",bridge_list_workspace_projects:"List all workspace projects with name, cwd, active run count",bridge_query_workspace:"Natural-language query about orchestration state",bridge_list_active_runs:"All active orchestration runs across workspace projects",bridge_peek_panel:"Read terminal output of any panel workspace-wide (no project boundary)",bridge_status_panel:"Get status of any panel in the workspace regardless of project"};function Oe(...r){return`
|
|
35
37
|
|
|
36
|
-
**Available MCP tools:** ${r.join(", ")}`}function
|
|
38
|
+
**Available MCP tools:** ${r.join(", ")}`}function Qa(...r){return`
|
|
37
39
|
|
|
38
40
|
## Tool reference (only call tools listed here)
|
|
39
41
|
|
|
40
42
|
| Tool | Purpose |
|
|
41
43
|
|------|---------|
|
|
42
|
-
${r.map(t=>`| \`${t}\` | ${
|
|
43
|
-
`)}`}var
|
|
44
|
+
${r.map(t=>`| \`${t}\` | ${Xa[t]} |`).join(`
|
|
45
|
+
`)}`}var Za={developer:`# Bridge Worker \u2014 Developer Role
|
|
44
46
|
|
|
45
47
|
You are a **Developer** worker in a multi-agent orchestration system called Bridge.
|
|
46
48
|
|
|
@@ -53,7 +55,7 @@ You are a **Developer** worker in a multi-agent orchestration system called Brid
|
|
|
53
55
|
- After making changes, check the runner agent (role:'runner' in bridge_list_agents) for build errors: bridge_get_agent_output(runnerAgentId)
|
|
54
56
|
- Trigger hot reload after file changes: bridge_send_input(runnerAgentId, "r")
|
|
55
57
|
|
|
56
|
-
${
|
|
58
|
+
${Oe("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
|
|
57
59
|
|
|
58
60
|
You are a **Quality-Obsessed Tech Lead** reviewing code changes in a multi-agent system called Bridge.
|
|
59
61
|
Your identity: Agile, pragmatic, anti-fragile. You ship with confidence or you send it back.
|
|
@@ -137,7 +139,7 @@ If a runner agent exists (bridge_list_agents \u2192 role:'runner'), call bridge_
|
|
|
137
139
|
- One \`bridge_fail_task\` per review cycle \u2014 consolidate all issues into a single message
|
|
138
140
|
- If unsure whether something is a bug or intentional design: flag it as a question, don't reject
|
|
139
141
|
|
|
140
|
-
${
|
|
142
|
+
${Oe("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
|
|
141
143
|
|
|
142
144
|
You are a **Planner** in Bridge. Your job: understand the project, listen to the user, then create a well-structured and verified execution plan.
|
|
143
145
|
|
|
@@ -227,7 +229,7 @@ Show the complete todo list with types and dependency chain. Then stop.
|
|
|
227
229
|
- To close a stale open todo that's already done: \`bridge_complete_task\` with its ID
|
|
228
230
|
- Todo titles must be specific: name the files, endpoints, components \u2014 no vague verbs
|
|
229
231
|
|
|
230
|
-
${
|
|
232
|
+
${Oe("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
|
|
231
233
|
|
|
232
234
|
You are an **Executor** worker in a multi-agent orchestration system called Bridge.
|
|
233
235
|
|
|
@@ -237,7 +239,7 @@ You are an **Executor** worker in a multi-agent orchestration system called Brid
|
|
|
237
239
|
- Capture and report all relevant output
|
|
238
240
|
- Call \`bridge_complete_task\` on success, \`bridge_fail_task\` with error details on failure
|
|
239
241
|
|
|
240
|
-
${
|
|
242
|
+
${Oe("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
|
|
241
243
|
|
|
242
244
|
You are a **Shell** worker in a multi-agent orchestration system called Bridge.
|
|
243
245
|
|
|
@@ -247,7 +249,7 @@ You are a **Shell** worker in a multi-agent orchestration system called Bridge.
|
|
|
247
249
|
- Call \`bridge_complete_task\` when the command exits cleanly
|
|
248
250
|
- Call \`bridge_fail_task\` with the error output if the command fails
|
|
249
251
|
|
|
250
|
-
${
|
|
252
|
+
${Oe("bridge_get_my_task","bridge_complete_task","bridge_fail_task")}`,orchestrator:`# Bridge Orchestrator
|
|
251
253
|
|
|
252
254
|
You are a **Bridge Orchestrator**. Your sole purpose is to decompose specs into todos, delegate them to worker agents, and report results. Nothing else.
|
|
253
255
|
|
|
@@ -359,7 +361,7 @@ Summarize: todos completed, failed, any blockers. List what workers did.
|
|
|
359
361
|
|
|
360
362
|
---
|
|
361
363
|
|
|
362
|
-
${
|
|
364
|
+
${Qa("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","bridge_list_groups","bridge_get_group_status","bridge_dispatch_to_group","bridge_list_workspace_projects","bridge_query_workspace","bridge_list_active_runs","bridge_peek_panel","bridge_status_panel")}`},ec=`# Bridge Worker \u2014 Reviewer Role (SCRIPTED TEST MODE)
|
|
363
365
|
|
|
364
366
|
You are a test-mode reviewer. DO NOT apply AI judgment. Apply the mechanical rule below.
|
|
365
367
|
|
|
@@ -378,15 +380,15 @@ You are a test-mode reviewer. DO NOT apply AI judgment. Apply the mechanical rul
|
|
|
378
380
|
- Decide solely based on (todo.retryCount ?? 0) > 0
|
|
379
381
|
- This is a signaling mechanic test, not a code quality review
|
|
380
382
|
|
|
381
|
-
${
|
|
382
|
-
`,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a}),["--append-system-prompt-file",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(a)}),[]}if(r==="qwen")return["--append-system-prompt",c];if(r==="aider")try{let a=
|
|
383
|
-
`,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a,agentKey:"aider"}),["--read",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,agentKey:"aider",error:String(a)}),[]}return r==="codex"?[]:[]}function
|
|
384
|
-
`,"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 Ta(r){try{let e=He(),t=`{BRIDGE_SERVER_URL=${Ge(r.serverUrl)},BRIDGE_TOKEN=${Ge(r.token)},BRIDGE_WORKSPACE_ID=${Ge(r.workspaceId)},BRIDGE_PROJECT_ID=${Ge(r.projectId||"workspace")},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Ge(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 Na(r){try{return W.default.statSync(r).isDirectory()}catch{return!1}}function br(r,e){try{return e(r)}catch{return!1}}function Da(r,e,t,n,s=Na){let i=n?.[r];if(i&&br(i,s))return{path:i,source:"local_override"};if(t){if(br(t,s))return{path:t,source:"daemon_override"};console.warn("[daemon] spawn.cwd.daemon_override_missing",{projectId:r,daemonLocalPath:t,hint:`Run: jerico link-project ${r} <local-path>`})}return e&&br(e,s)?{path:e,source:"server_project"}:(console.warn("[daemon] spawn.cwd.fallback_home",{projectId:r,serverCwd:e,localOverride:i,daemonLocalPath:t??void 0,hint:`Set projectPaths["${r}"] in ~/.jerico/settings.json`}),{path:F.default.homedir(),source:"fallback_home"})}function Ra(r){try{if(!r.cwd)return console.warn("[daemon] forge.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId||"workspace"}),!1;let e=He(),t=JSON.stringify({mcpServers:{bridge:{command:e,args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId||"workspace",BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}}),n={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,ke.spawnSync)("forge",["mcp","remove","--scope","local","bridge"],n);let s=(0,ke.spawnSync)("forge",["mcp","import",t,"--scope","local"],n);return s.status===0?(console.log("[daemon] forge.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId||"workspace"}),!0):(console.warn("[daemon] forge.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:s.status,stderr:(s.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] forge.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}function ja(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId||"workspace"}),!1;let e=He(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,ke.spawnSync)("qwen",["mcp","remove","--scope","project","bridge"],t);let n=(0,ke.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||"workspace"}`,"-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||"workspace"}),!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 St=[],Sr=!1,Cs=!1;function Ps(){return Sr}function Ts(r){if(Cs)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");if(Cs=!0,process.env.BRIDGE_TEST_SCRIPTED_REVIEW!=="1")try{let p=L.default.join(F.default.homedir(),".jerico","settings.json");W.default.existsSync(p)&&JSON.parse(W.default.readFileSync(p,"utf-8")).testScriptedReview===!0&&(process.env.BRIDGE_TEST_SCRIPTED_REVIEW="1",console.log("[daemon] scripted-review-mode enabled from ~/.jerico/settings.json"))}catch{}process.env.BRIDGE_TEST_SCRIPTED_REVIEW==="1"&&console.log("[daemon] scripted-review-mode ENABLED");let e=oe(),t=(0,qe.createHash)("sha256").update(e.token).digest("hex"),n=null,s=null,i=null,o=0,c=0,a=0n;function l(){s&&(clearTimeout(s),s=null);let p=Date.now(),g=process.hrtime.bigint();n=new C(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let h=n,f=(0,qe.randomUUID)();yr=f;let m=F.default.networkInterfaces(),k=Object.entries(m).flatMap(([E,b])=>(b||[]).filter(D=>!D.internal).map(D=>({iface:E,address:D.address,family:D.family}))),S=JSON.stringify(k);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"net.interfaces",interfaces:k,connectionId:f})),wt&&wt!==S&&console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"net.interfaces.changed",previous:wt,current:S,connectionId:f})),wt=S;let N=h.send.bind(h);h.send=function(E){if(h.readyState!==C.OPEN){let b="unknown";try{b=JSON.parse(E).type}catch{}console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.send.dropped",messageType:b,readyState:h.readyState,connectionId:f}));return}return N(E)},console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connecting",server:e.server,connectionId:f}));let y=null,v=0,w=null;h.on("open",()=>{Sr=!0,c=0,a=0n,console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connected",server:e.server,connectionId:f})),i=setInterval(()=>{h.readyState===C.OPEN&&(h.ping(),v=Date.now(),w&&clearTimeout(w),w=setTimeout(()=>{console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.heartbeat.timeout",connectionId:f})),h.terminate()},ya))},_a);let E=!Is();h.send(JSON.stringify({type:"ready",version:"1.1",name:e.name,spawnHelperBroken:E,liveAgentIds:r.getLiveAgentIds(),machineFingerprint:vr(),connectionId:f})),Ft(e.agentPaths).then(b=>{St=b,h.readyState===C.OPEN&&h.send(JSON.stringify({type:"agents",list:St}))}),y=xs(b=>{h.readyState===C.OPEN&&h.send(JSON.stringify({type:"system_metrics",daemonId:t,...b}))})}),h.on("message",E=>{let b;try{b=JSON.parse(E.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}La(b,h,r,e)}),h.on("pong",()=>{w&&(clearTimeout(w),w=null);let E=Date.now()-v;console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.heartbeat.pong",rttMs:E,connectionId:f}))}),h.on("close",(E,b)=>{Sr=!1,i&&(clearInterval(i),i=null),w&&(clearTimeout(w),w=null),y?.(),y=null,E===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;let D=Number((process.hrtime.bigint()-g)/1000000n);if(console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.closed",code:E,reason:b?.toString()||void 0,uptimeMs:D,connectionId:f})),s)return;c===0&&(a=process.hrtime.bigint()),c++;let Oe=Number((process.hrtime.bigint()-a)/1000000n);c>=10&&Oe<6e4&&(console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.reconnect.storm",reconnectCount:c,connectionId:f})),process.exit(1));let Et=Math.min(3e4,1e3*Math.pow(2,Math.min(c,5))),xr=Math.round(Et+Math.random()*500);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.reconnect.scheduled",delayMs:xr,reconnectCount:c,connectionId:f})),s=setTimeout(l,xr)}),h.on("error",E=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.error",message:E.message,code:E.code,connectionId:f}))})}function d(){i&&(clearInterval(i),i=null),r.stopLivenessCheck(),ma();for(let p of ce.values())p();r.killAll(),n?.close()}function u(p){console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.signal",signal:p,connectionId:yr})),d(),setTimeout(()=>process.exit(0),100)}process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),process.on("SIGHUP",()=>u("SIGHUP")),process.on("uncaughtException",p=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"daemon.uncaught",error:String(p),stack:p.stack,connectionId:yr})),r.killAll(),process.exit(1)}),l()}function La(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=St.find(y=>y.key===r.agentKey);if(!s){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let i=he.find(y=>y.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"&&(ce.get(r.agentId)?.(),ce.set(r.agentId,pr(r.agentId,r.sessionId,(y,v,w)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:y,usedPct:v,usedTokens:w,...wr}))})));else if(i?.assignSessionId){let y=crypto.randomUUID(),v=r.agentKey==="kimi"?"--session":r.agentKey==="forge"?"--conversation-id":"--session-id";o=[...i.spawnArgs??[],v,y],e.readyState===C.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:y})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:y})),r.agentKey==="claude"&&(ce.get(r.agentId)?.(),ce.set(r.agentId,pr(r.agentId,y,(w,E,b)=>{e.readyState===C.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:w,usedPct:E,usedTokens:b,...wr}))})))}else e.readyState===C.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let c,a=!1,l,d;if(r.workspaceId){let y=Ea(n.server),v=Da(r.projectId??"",r.cwd,r.daemonLocalPath,n.projectPaths),w=v.path;d=v.source;let E=hr(w);if(c={serverUrl:y,token:n.token,workspaceId:fs(r.workspaceId),projectId:r.projectId?ps(r.projectId):void 0,agentId:r.agentId?hs(r.agentId):void 0,cwd:w,projectEnv:E.env},r.agentKey==="claude"){let b=ka(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else if(r.agentKey==="codex"){let b=Ta(c);a=b.length>0,l="stdio",o=[...o,...b]}else if(r.agentKey==="qwen")a=ja(c),l=a?"stdio":void 0;else if(r.agentKey==="kimi"){let b=Pa(c);a=b.length>0,l=process.env.BRIDGE_MCP_URL?"http":"stdio",o=[...o,...b]}else r.agentKey==="forge"?(a=Ra(c),l=a?"stdio":void 0):(a=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"}));if(dr("phase2a.verified_at")&&(v.source==="daemon_override"||v.source==="server_project")){let b=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths/${r.daemonId}/verify`;fetch(b,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:"{}"}).catch(D=>{console.warn("[daemon] verify.patch_failed",{projectId:r.projectId,error:String(D)})})}if(dr("phase2a.auto_register")&&(v.source==="daemon_override"||v.source==="server_project"))try{let b=(0,ke.spawnSync)("git",["remote","get-url","origin"],{cwd:w,timeout:5e3,encoding:"utf-8"});if(b.status===0&&b.stdout&&b.stdout.trim()){let D=b.stdout.trim();r.projectId&&(n.projectPaths||(n.projectPaths={}),n.projectPaths[r.projectId]=w,ae(n));let Oe=`${y}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths`;fetch(Oe,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({daemonId:r.daemonId,localPath:w,repoUrl:D})}).catch(Et=>{console.warn("[daemon] auto_register.post_failed",{projectId:r.projectId,error:String(Et)})}),console.log("[daemon] auto_register.ok",{projectId:r.projectId,localPath:w,repoUrl:D})}}catch(b){console.log("[daemon] auto_register.skipped",{projectId:r.projectId,reason:String(b)})}}let u=Aa(r.agentKey,r.role,r.agentId,r.workspaceId,r.projectId,r.groupId);u.length>0&&(o=[...o,...u]);let p=Math.max(1,Math.min(500,r.cols)),g=Math.max(1,Math.min(500,r.rows)),h=Date.now(),f="",m=0,k=!1,S=!1;if(t.spawn(r.agentId,r.agentKey,s.binaryPath,o,p,g,y=>{m+=y.length;try{let v=Buffer.from(y,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!S&&Date.now()-h<3e4&&(/yolo agent/.test(v)||/●/.test(v)||/○/.test(v))){S=!0;let w=As(r.role);if(w){let E=w.replaceAll("{{PANEL_ID}}",r.agentId).replaceAll("{{WORKSPACE_ID}}",r.workspaceId??"unknown").replaceAll("{{PROJECT_ID}}",r.projectId??"none").replaceAll("{{GROUP_ID}}",r.groupId??"none"),b=ga(E),D=Buffer.from(b).toString("base64");t.write(r.agentId,D,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!f)try{let v=Buffer.from(y,"base64").toString("utf-8"),w=Sa(v).replace(/\x00/g,"").trim();if(w&&(f=va(w)),r.agentKey==="codex"&&!k&&Date.now()-h<2e4&&/included in your plan for free|let[’']s build together/i.test(w)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(w)){k=!0;let E=Buffer.from("y").toString("base64");t.write(r.agentId,E,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:y}))},(y,v)=>{let w=Date.now()-h,E=w<=ba;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:y,signal:v,uptimeMs:w,earlyExit:E,outputBytes:m,firstOutputSnippet:f||void 0}),E&&e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${y??"null"} signal=${v??"null"} snippet="${f||"no output"}"`})),e.readyState===C.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:y,signal:v}))},c))e.readyState===C.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:a,transport:a?l:void 0,projectId:c?.projectId,effectiveCwd:c?.cwd,cwdSource:d}));else{let v=t.getLastError(r.agentId)?.includes("posix_spawnp failed")&&pa(r.agentKey);e.readyState===C.OPEN&&(v?e.send(JSON.stringify({type:"error",code:"SPAWN_HELPER_BROKEN",message:"node-pty spawn-helper is not executable. Upgrade bridge-agent to v0.2.10+."})):e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`})))}e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agent_spawned",agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,role:r.role}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":ce.get(r.agentId)?.(),ce.delete(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"detect_agents":Ft(n.agentPaths).then(s=>{St=s,e.readyState===C.OPEN&&e.send(JSON.stringify({type:"agents",list:s}))});break;case"dir_list":{let s=F.default.homedir(),i=(r.path||"~").replace(/^~/,s),o=L.default.resolve(i);if(o!==s&&!o.startsWith(s+L.default.sep)){e.readyState===C.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let c=W.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===C.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:o,entries:c}))}catch(c){e.readyState===C.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}}}gt();var vt=R.default.join((0,xe.homedir)(),"Library","LaunchAgents");function Ma(){let r=[...process.env.npm_config_global_prefix?[R.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function Ds(){let r=ur();if((0,A.existsSync)(r))try{let{pid:e}=JSON.parse((0,A.readFileSync)(r,"utf8"));if(e&&process.kill(e,0))return;(0,A.unlinkSync)(r)}catch{try{(0,A.unlinkSync)(r)}catch{}}}function $a(){let r=ur();try{(0,A.mkdirSync)(R.default.dirname(r),{recursive:!0})}catch{}Ds();try{let e=(0,A.openSync)(r,"wx");return(0,A.writeSync)(e,JSON.stringify({pid:process.pid,startedAt:Date.now()})),(0,A.closeSync)(e),!0}catch{return!1}}function Rs(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(R.default.join((0,xe.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(R.default.join((0,xe.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,le.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(R.default.dirname(i))}catch{}let n=R.default.join((0,xe.homedir)(),".vscode","extensions");try{let s=(0,le.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
|
|
385
|
-
`);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=
|
|
383
|
+
${Oe("bridge_get_my_task","bridge_complete_task","bridge_fail_task","bridge_get_todo_context")}`;function zs(r){let e=process.env.BRIDGE_TEST_SCRIPTED_REVIEW,t=r==="reviewer"&&e==="1";return console.log("[daemon] getRoleSystemPrompt.called",{role:r,envFlag:e,returning:t?"SCRIPTED":"NORMAL"}),t?ec:Za[r]}function tc(r,e,t,n,s,i){if(!e)return[];let o=zs(e);if(!o)return[];let c=o.replaceAll("{{PANEL_ID}}",t).replaceAll("{{WORKSPACE_ID}}",n??"unknown").replaceAll("{{PROJECT_ID}}",s??"none").replaceAll("{{GROUP_ID}}",i??"none");if(r==="claude")try{let a=R.default.join(W.default.tmpdir(),`bridge-role-${t}.md`);return G.default.writeFileSync(a,c+`
|
|
384
|
+
`,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a}),["--append-system-prompt-file",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,error:String(a)}),[]}if(r==="qwen")return["--append-system-prompt",c];if(r==="aider")try{let a=R.default.join(W.default.tmpdir(),`bridge-role-${t}.md`);return G.default.writeFileSync(a,c+`
|
|
385
|
+
`,"utf-8"),console.log("[daemon] role.prompt.written",{agentId:t,role:e,tmpPath:a,agentKey:"aider"}),["--read",a]}catch(a){return console.warn("[daemon] role.prompt.write.failed",{agentId:t,role:e,agentKey:"aider",error:String(a)}),[]}return r==="codex"?[]:[]}function Ye(r){return`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function rc(r){try{let e=process.env.BRIDGE_MCP_URL,t=e?{mcpServers:{bridge:{type:"http",url:`${e}/mcp/${r.workspaceId}/${r.projectId||"workspace"}`,headers:{Authorization:`Bearer ${r.token}`,"x-panel-id":r.agentId??""}}}}:{mcpServers:{bridge:{command:Qe(),args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId||"workspace",BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}},n=R.default.join(W.default.tmpdir(),`bridge-mcp-kimi-${r.agentId??(r.projectId||"workspace")}.json`);return G.default.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
386
|
+
`,"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 nc(r){try{let e=Qe(),t=`{BRIDGE_SERVER_URL=${Ye(r.serverUrl)},BRIDGE_TOKEN=${Ye(r.token)},BRIDGE_WORKSPACE_ID=${Ye(r.workspaceId)},BRIDGE_PROJECT_ID=${Ye(r.projectId||"workspace")},HTTP_MODE="false"}`;return["-c",'mcp_servers.bridge.transport="stdio"',"-c",`mcp_servers.bridge.command=${Ye(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 sc(r){try{return G.default.statSync(r).isDirectory()}catch{return!1}}function Tr(r,e){try{return e(r)}catch{return!1}}function ic(r,e,t,n,s=sc){let i=n?.[r];if(i&&Tr(i,s))return{path:i,source:"local_override"};if(t){if(Tr(t,s))return{path:t,source:"daemon_override"};console.warn("[daemon] spawn.cwd.daemon_override_missing",{projectId:r,daemonLocalPath:t,hint:`Run: jerico link-project ${r} <local-path>`})}if(e&&Tr(e,s))return{path:e,source:"server_project"};let c=!r||r.trim()===""?"Missing projectId in spawn message \u2014 server-side bug, file issue at https://github.com/alperduzgun/jerico/issues":`Set projectPaths["${r}"] in ~/.jerico/settings.json`;return console.warn("[daemon] spawn.cwd.fallback_home",{projectId:r,serverCwd:e,localOverride:i,daemonLocalPath:t??void 0,hint:c}),{path:W.default.homedir(),source:"fallback_home"}}function oc(r){try{if(!r.cwd)return console.warn("[daemon] forge.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId||"workspace"}),!1;let e=Qe(),t=JSON.stringify({mcpServers:{bridge:{command:e,args:[],env:{BRIDGE_SERVER_URL:r.serverUrl,BRIDGE_TOKEN:r.token,BRIDGE_WORKSPACE_ID:r.workspaceId,BRIDGE_PROJECT_ID:r.projectId||"workspace",BRIDGE_PANEL_ID:r.agentId??"",HTTP_MODE:"false"}}}}),n={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"};(0,Ce.spawnSync)("forge",["mcp","remove","--scope","local","bridge"],n);let s=(0,Ce.spawnSync)("forge",["mcp","import",t,"--scope","local"],n);return s.status===0?(console.log("[daemon] forge.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId||"workspace"}),!0):(console.warn("[daemon] forge.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:s.status,stderr:(s.stderr??"").toString().slice(0,300)}),!1)}catch(e){return console.warn("[daemon] forge.mcp.setup.error",{error:String(e),projectId:r.projectId}),!1}}function ac(r){try{if(!r.cwd)return console.warn("[daemon] qwen.mcp.setup.skipped",{reason:"missing_cwd",projectId:r.projectId||"workspace"}),!1;let e=Qe(),t={cwd:r.cwd,encoding:"utf-8",timeout:5e3,stdio:"pipe"},n=R.default.resolve(r.cwd)===R.default.resolve(W.default.homedir()),s=n?"user":"project";n&&console.warn("[daemon] qwen.mcp.home_dir_fallback",{cwd:r.cwd,projectId:r.projectId||"workspace",scope:"user"}),(0,Ce.spawnSync)("qwen",["mcp","remove","--scope",s,"bridge"],t);let i=(0,Ce.spawnSync)("qwen",["mcp","add","--scope",s,"-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||"workspace"}`,"-e",`BRIDGE_PANEL_ID=${r.agentId??""}`,"-e","HTTP_MODE=false","bridge",e],t);return i.status===0?(console.log("[daemon] qwen.mcp.setup.ok",{cwd:r.cwd,projectId:r.projectId||"workspace"}),!0):(console.warn("[daemon] qwen.mcp.setup.failed",{cwd:r.cwd,projectId:r.projectId,status:i.status,stderr:(i.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=[],Dr=!1,Ys=!1;function Xs(){return Dr}function Qs(r){if(Ys)throw new Error("[daemon] startDaemonConnection called twice \u2014 only one connection manager allowed");if(Ys=!0,process.env.BRIDGE_TEST_SCRIPTED_REVIEW!=="1")try{let p=R.default.join(W.default.homedir(),".jerico","settings.json");G.default.existsSync(p)&&JSON.parse(G.default.readFileSync(p,"utf-8")).testScriptedReview===!0&&(process.env.BRIDGE_TEST_SCRIPTED_REVIEW="1",console.log("[daemon] scripted-review-mode enabled from ~/.jerico/settings.json"))}catch{}process.env.BRIDGE_TEST_SCRIPTED_REVIEW==="1"&&console.log("[daemon] scripted-review-mode ENABLED");let e=ce(),t=(0,Xe.createHash)("sha256").update(e.token).digest("hex"),n=new vt(t),s=null,i=null,o=null,c=0,a=0,l=0n;function d(){i&&(clearTimeout(i),i=null);let p=Date.now(),g=process.hrtime.bigint();s=new E(e.server,{headers:{Authorization:`Bearer ${e.token}`}});let h=s,m=(0,Xe.randomUUID)();Ar=m;let x=W.default.networkInterfaces(),S=Object.entries(x).flatMap(([v,y])=>(y||[]).filter(N=>!N.internal).map(N=>({iface:v,address:N.address,family:N.family}))),P=JSON.stringify(S);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"net.interfaces",interfaces:S,connectionId:m})),Pt&&Pt!==P&&console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"net.interfaces.changed",previous:Pt,current:P,connectionId:m})),Pt=P;let M=h.send.bind(h);h.send=function(v){if(h.readyState!==E.OPEN){let y="unknown";try{y=JSON.parse(v).type}catch{}console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.send.dropped",messageType:y,readyState:h.readyState,connectionId:m}));return}return M(v)},console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connecting",server:e.server,connectionId:m}));let w=null,k=0,b=null;h.on("open",()=>{Dr=!0,a=0,l=0n,console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.connected",server:e.server,connectionId:m})),o=setInterval(()=>{h.readyState===E.OPEN&&(h.ping(),k=Date.now(),b&&clearTimeout(b),b=setTimeout(()=>{console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.heartbeat.timeout",connectionId:m})),h.terminate()},Ga))},Ha);let v=!Js();h.send(JSON.stringify({type:"ready",version:"1.1",name:e.name,spawnHelperBroken:v,liveAgentIds:r.getLiveAgentIds(),machineFingerprint:Rr(),connectionId:m})),n.updateWs(h),Promise.all([Xt(e.agentPaths),wr()]).then(([y,N])=>{ze=N?[...y,N]:y,h.readyState===E.OPEN&&h.send(JSON.stringify({type:"agents",list:ze}))}),w=Vs(y=>{h.readyState===E.OPEN&&h.send(JSON.stringify({type:"system_metrics",daemonId:t,...y}))})}),h.on("message",v=>{let y;try{y=JSON.parse(v.toString())}catch{console.warn("[daemon] Invalid JSON from server, ignoring");return}cc(y,h,r,e,n)}),h.on("pong",()=>{b&&(clearTimeout(b),b=null);let v=Date.now()-k;console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.heartbeat.pong",rttMs:v,connectionId:m}))}),h.on("close",(v,y)=>{Dr=!1,o&&(clearInterval(o),o=null),b&&(clearTimeout(b),b=null),w?.(),w=null,v===1008?(c++,c>=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:c})):c=0;let N=Number((process.hrtime.bigint()-g)/1000000n);if(console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.closed",code:v,reason:y?.toString()||void 0,uptimeMs:N,connectionId:m})),i)return;a===0&&(l=process.hrtime.bigint()),a++;let Tt=Number((process.hrtime.bigint()-l)/1000000n);a>=10&&Tt<6e4&&(console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.reconnect.storm",reconnectCount:a,connectionId:m})),process.exit(1));let Nt=Math.min(3e4,1e3*Math.pow(2,Math.min(a,5))),Br=Math.round(Nt+Math.random()*500);console.log(JSON.stringify({ts:Date.now(),level:"info",event:"ws.reconnect.scheduled",delayMs:Br,reconnectCount:a,connectionId:m})),i=setTimeout(d,Br)}),h.on("error",v=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"ws.error",message:v.message,code:v.code,connectionId:m}))})}function u(){o&&(clearInterval(o),o=null),r.stopLivenessCheck(),Fa();for(let p of de.values())p();n.stopAll(),r.killAll(),s?.close()}function f(p){console.log(JSON.stringify({ts:Date.now(),level:"warn",event:"ws.signal",signal:p,connectionId:Ar})),u(),setTimeout(()=>process.exit(0),100)}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),process.on("SIGHUP",()=>f("SIGHUP")),process.on("uncaughtException",p=>{console.log(JSON.stringify({ts:Date.now(),level:"error",event:"daemon.uncaught",error:String(p),stack:p.stack,connectionId:Ar})),r.killAll(),process.exit(1)}),d()}function cc(r,e,t,n,s){switch(r.type){case"spawn":{if(console.log("[daemon] pty.spawn.start",{agentId:r.agentId,agentKey:r.agentKey,sessionId:r.sessionId,projectId:r.projectId,workspaceId:r.workspaceId,role:r.role}),r.agentKey==="sim_ios"){s.start(r.agentId);return}let i=ze.find(w=>w.key===r.agentKey);if(!i){e.readyState===E.OPEN&&e.send(JSON.stringify({type:"error",code:"AGENT_NOT_FOUND",message:`Agent '${r.agentKey}' is not installed on this machine`}));return}let o=pe.find(w=>w.key===r.agentKey),c=[];if(r.sessionId&&o?.resumeArgs)c=o.resumeArgs(r.sessionId),console.log("[daemon] pty.spawn.resume",{agentId:r.agentId,sessionId:r.sessionId}),r.agentKey==="claude"&&(de.get(r.agentId)?.(),de.set(r.agentId,Ir(r.agentId,r.sessionId,(w,k,b)=>{e.readyState===E.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:w,usedPct:k,usedTokens:b,...Nr}))})));else if(o?.assignSessionId){let w=crypto.randomUUID(),k=r.agentKey==="kimi"?"--session":r.agentKey==="forge"?"--conversation-id":"--session-id";c=[...o.spawnArgs??[],k,w],e.readyState===E.OPEN&&(e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:w})),console.log("[daemon] session.assigned",{agentId:r.agentId,sessionId:w})),r.agentKey==="claude"&&(de.get(r.agentId)?.(),de.set(r.agentId,Ir(r.agentId,w,(b,v,y)=>{e.readyState===E.OPEN&&e.send(JSON.stringify({type:"panel_token_usage",agentId:b,usedPct:v,usedTokens:y,...Nr}))})))}else e.readyState===E.OPEN&&e.send(JSON.stringify({type:"session_started",agentId:r.agentId,sessionId:crypto.randomUUID()}));let a,l=!1,d,u;if(r.workspaceId){let w=Ya(n.server),k=ic(r.projectId??"",r.cwd,r.daemonLocalPath,n.projectPaths),b=k.path;u=k.source;let v=kr(b);if(a={serverUrl:w,token:n.token,workspaceId:Os(r.workspaceId),projectId:r.projectId?Cs(r.projectId):void 0,agentId:r.agentId?Is(r.agentId):void 0,cwd:b,projectEnv:v.env},r.agentKey==="claude"){let y=za(a);l=y.length>0,d=process.env.BRIDGE_MCP_URL?"http":"stdio",c=[...c,...y]}else if(r.agentKey==="codex"){let y=nc(a);l=y.length>0,d="stdio",c=[...c,...y]}else if(r.agentKey==="qwen")l=ac(a),d=l?"stdio":void 0;else if(r.agentKey==="kimi"){let y=rc(a);l=y.length>0,d=process.env.BRIDGE_MCP_URL?"http":"stdio",c=[...c,...y]}else r.agentKey==="forge"?(l=oc(a),d=l?"stdio":void 0):(l=!1,console.log("[daemon] mcp.config.skipped",{agentId:r.agentId,agentKey:r.agentKey,reason:"unsupported_agent_path"}));if(br("phase2a.verified_at")&&(k.source==="daemon_override"||k.source==="server_project")){let y=`${w}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths/${r.daemonId}/verify`;fetch(y,{method:"PATCH",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:"{}"}).catch(N=>{console.warn("[daemon] verify.patch_failed",{projectId:r.projectId,error:String(N)})})}if(br("phase2a.auto_register")&&(k.source==="daemon_override"||k.source==="server_project"))try{let y=(0,Ce.spawnSync)("git",["remote","get-url","origin"],{cwd:b,timeout:5e3,encoding:"utf-8"});if(y.status===0&&y.stdout&&y.stdout.trim()){let N=y.stdout.trim();r.projectId&&(n.projectPaths||(n.projectPaths={}),n.projectPaths[r.projectId]=b,le(n));let Tt=`${w}/api/workspaces/${r.workspaceId}/projects/${r.projectId}/machine-paths`;fetch(Tt,{method:"POST",headers:{Authorization:`Bearer ${n.token}`,"Content-Type":"application/json"},body:JSON.stringify({daemonId:r.daemonId,localPath:b,repoUrl:N})}).catch(Nt=>{console.warn("[daemon] auto_register.post_failed",{projectId:r.projectId,error:String(Nt)})}),console.log("[daemon] auto_register.ok",{projectId:r.projectId,localPath:b,repoUrl:N})}}catch(y){console.log("[daemon] auto_register.skipped",{projectId:r.projectId,reason:String(y)})}}let f=tc(r.agentKey,r.role,r.agentId,r.workspaceId,r.projectId,r.groupId);f.length>0&&(c=[...c,...f]);let p=Math.max(1,Math.min(500,r.cols)),g=Math.max(1,Math.min(500,r.rows)),h=Date.now(),m="",x=0,S=!1,P=!1;if(t.spawn(r.agentId,r.agentKey,i.binaryPath,c,p,g,w=>{x+=w.length;try{let k=Buffer.from(w,"base64").toString("utf-8");if(r.agentKey==="kimi"&&r.role&&!P&&Date.now()-h<3e4&&(/yolo agent/.test(k)||/●/.test(k)||/○/.test(k))){P=!0;let b=zs(r.role);if(b){let v=b.replaceAll("{{PANEL_ID}}",r.agentId).replaceAll("{{WORKSPACE_ID}}",r.workspaceId??"unknown").replaceAll("{{PROJECT_ID}}",r.projectId??"none").replaceAll("{{GROUP_ID}}",r.groupId??"none"),y=Wa(v),N=Buffer.from(y).toString("base64");t.write(r.agentId,N,"orchestrator"),console.log("[daemon] kimi.role.injected",{agentId:r.agentId,role:r.role})}}}catch{}if(!m)try{let k=Buffer.from(w,"base64").toString("utf-8"),b=Ka(k).replace(/\x00/g,"").trim();if(b&&(m=Ja(b)),r.agentKey==="codex"&&!S&&Date.now()-h<2e4&&/included in your plan for free|let[’']s build together/i.test(b)&&/yes|no|\[y\/n\]|\(y\/n\)|y\/n/i.test(b)){S=!0;let v=Buffer.from("y").toString("base64");t.write(r.agentId,v,"orchestrator"),console.log("[daemon] codex.onboarding.auto_ack",{agentId:r.agentId})}}catch{}e.readyState===E.OPEN&&e.send(JSON.stringify({type:"output",agentId:r.agentId,data:w}))},(w,k)=>{let b=Date.now()-h,v=b<=qa;console.log("[daemon] pty.spawn.result",{agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,exitCode:w,signal:k,uptimeMs:b,earlyExit:v,outputBytes:x,firstOutputSnippet:m||void 0}),v&&e.readyState===E.OPEN&&e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Early exit: agent=${r.agentKey} code=${w??"null"} signal=${k??"null"} snippet="${m||"no output"}"`})),e.readyState===E.OPEN&&e.send(JSON.stringify({type:"exit",agentId:r.agentId,exitCode:w,signal:k}))},a))e.readyState===E.OPEN&&e.send(JSON.stringify({type:"mcp_status",agentId:r.agentId,mcpConfigured:l,transport:l?d:void 0,projectId:a?.projectId,effectiveCwd:a?.cwd,cwdSource:u}));else{let k=t.getLastError(r.agentId)?.includes("posix_spawnp failed")&&Ua(r.agentKey);e.readyState===E.OPEN&&(k?e.send(JSON.stringify({type:"error",code:"SPAWN_HELPER_BROKEN",message:"node-pty spawn-helper is not executable. Upgrade bridge-agent to v0.2.10+."})):e.send(JSON.stringify({type:"error",code:"SPAWN_FAILED",message:`Failed to spawn panel ${r.agentId}`})))}e.readyState===E.OPEN&&e.send(JSON.stringify({type:"agent_spawned",agentId:r.agentId,agentKey:r.agentKey,daemonId:r.daemonId,role:r.role}));break}case"input":t.write(r.agentId,r.data,r.source);break;case"kill":de.get(r.agentId)?.(),de.delete(r.agentId),s.stop(r.agentId),t.kill(r.agentId,r.force);break;case"resize":t.resize(r.agentId,r.cols,r.rows);break;case"sim_tap":case"sim_swipe":case"sim_key":case"sim_button":case"sim_get_source":case"sim_subscribe":case"sim_unsubscribe":case"sim_healthcheck":case"sim_install_run":case"sim_install_cancel":s.handle(r);break;case"detect_agents":Promise.all([Xt(n.agentPaths),wr()]).then(([i,o])=>{ze=o?[...i,o]:i,e.readyState===E.OPEN&&e.send(JSON.stringify({type:"agents",list:ze}))});break;case"dir_list":{let i=W.default.homedir(),o=(r.path||"~").replace(/^~/,i),c=R.default.resolve(o);if(c!==i&&!c.startsWith(i+R.default.sep)){e.readyState===E.OPEN&&e.send(JSON.stringify({type:"error",code:"INVALID_MSG",message:"Path outside home directory"}));return}try{let a=G.default.readdirSync(c,{withFileTypes:!0}).filter(l=>l.isDirectory()&&!l.name.startsWith(".")).map(l=>({name:l.name,path:R.default.join(c,l.name)})).sort((l,d)=>l.name.localeCompare(d.name));e.readyState===E.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:c,entries:a}))}catch(a){e.readyState===E.OPEN&&e.send(JSON.stringify({type:"dir_list_result",requestId:r.requestId,path:c,entries:[],error:a instanceof Error?a.message:"Cannot read directory"}))}break}default:{let i=r}}}Ge();var At=j.default.join((0,Pe.homedir)(),"Library","LaunchAgents");function lc(){let r=[...process.env.npm_config_global_prefix?[j.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of r)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}function ei(){let r=He();if((0,A.existsSync)(r))try{let{pid:e}=JSON.parse((0,A.readFileSync)(r,"utf8"));if(e&&process.kill(e,0))return;(0,A.unlinkSync)(r)}catch{try{(0,A.unlinkSync)(r)}catch{}}}function dc(){let r=He();try{(0,A.mkdirSync)(j.default.dirname(r),{recursive:!0})}catch{}ei();try{let e=(0,A.openSync)(r,"wx");return(0,A.writeSync)(e,JSON.stringify({pid:process.pid,startedAt:Date.now()})),(0,A.closeSync)(e),!0}catch{return!1}}function ti(){let r=["claude","codex","qwen","ollama","aider","python3","node","bun","sh"],e=new Set;e.add(j.default.join((0,Pe.homedir)(),".nvm","versions","node",`v${process.versions.node}`,"bin")),e.add(j.default.join((0,Pe.homedir)(),".local","bin")),e.add("/opt/homebrew/bin"),e.add("/usr/local/bin"),e.add("/usr/bin"),e.add("/bin");let t=process.env.PATH??"";for(let s of t.split(":"))s&&!s.startsWith("/dev")&&!s.startsWith("/tmp")&&e.add(s);for(let s of r)try{let i=(0,ue.execSync)(`which ${s} 2>/dev/null`,{stdio:"pipe"}).toString().trim();i&&i.startsWith("/")&&e.add(j.default.dirname(i))}catch{}let n=j.default.join((0,Pe.homedir)(),".vscode","extensions");try{let s=(0,ue.execSync)(`ls "${n}" 2>/dev/null`,{stdio:"pipe"}).toString().split(`
|
|
387
|
+
`);for(let i of s)if(i.startsWith("anthropic.claude-code-")){let o=j.default.join(n,i,"resources","native-binary");(0,A.existsSync)(o)&&e.add(o)}}catch{}return[...e].join(":")}function uc(r){try{(0,ue.execSync)(`mkdir -p "${At}"`,{stdio:"pipe"})}catch{}let e=ke(),t=j.default.join(At,e),{out:n,err:s}=kt(),i=ti(),o=process.env.BRIDGE_PROFILE||"",c=e.replace(".plist",""),a=o?` <key>BRIDGE_PROFILE</key>
|
|
386
388
|
<string>${o}</string>
|
|
387
|
-
`:"",l=
|
|
389
|
+
`:"",l=j.default.join((0,Pe.homedir)(),".bridge"),d=j.default.join(l,"bridge-agent-wrapper.sh"),u=`#!/bin/bash
|
|
388
390
|
exec "$(command -v node)" "${r}" start
|
|
389
|
-
`;try{(0,A.mkdirSync)(l,{recursive:!0}),(0,A.writeFileSync)(d,u,{mode:493})}catch{}let
|
|
391
|
+
`;try{(0,A.mkdirSync)(l,{recursive:!0}),(0,A.writeFileSync)(d,u,{mode:493})}catch{}let f=`<?xml version="1.0" encoding="UTF-8"?>
|
|
390
392
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
391
393
|
<plist version="1.0">
|
|
392
394
|
<dict>
|
|
@@ -415,6 +417,6 @@ exec "$(command -v node)" "${r}" start
|
|
|
415
417
|
${a} </dict>
|
|
416
418
|
</dict>
|
|
417
419
|
</plist>
|
|
418
|
-
`;try{return(0,A.writeFileSync)(t,
|
|
419
|
-
`)),
|
|
420
|
-
`)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function
|
|
420
|
+
`;try{return(0,A.writeFileSync)(t,f,"utf-8"),!0}catch(p){return console.warn("[bridge] launchd.plist.write.failed",{error:String(p)}),!1}}function hc(){let r=ke(),e=j.default.join(At,r);try{return(0,ue.execSync)(`launchctl kickstart -kp gui/$(id -u)/${r} 2>/dev/null; launchctl unload "${e}" 2>/dev/null; launchctl load "${e}"`,{stdio:"pipe"}),{ok:!0,permissionDenied:!1}}catch(t){let n=String(t);return{ok:!1,permissionDenied:n.includes("Permission denied")||n.includes("not allowed")||n.includes("bootstrap")}}}function pc(r){let{out:e,err:t}=kt();try{let n=(0,ue.spawn)(r,["start"],{detached:!0,stdio:"ignore",env:{...process.env,PATH:ti(),BRIDGE_DAEMON:"1"}});n.unref(),setTimeout(()=>{n.pid&&process.kill(n.pid,0)?(console.log("[bridge] daemon.pid",{pid:n.pid}),console.log("[bridge] background.ok",{log:e})):console.error("[bridge] background.failed \u2014 check: tail -f",{log:t})},2e3)}catch(n){console.error("[bridge] background.spawn.failed",{error:String(n)})}}function fc(){let r=parseInt(process.env.HEALTH_PORT??"3101",10),e=Date.now()+6e3,t=()=>{if(Date.now()>e){console.error("[bridge] health.verify.timeout \u2014 daemon may have crashed immediately");return}try{let s=require("node:http").get(`http://127.0.0.1:${r}/health`,i=>{i.statusCode===200?console.log("[bridge] health.verify.ok"):setTimeout(t,500)});s.on("error",()=>{setTimeout(t,500)}),s.setTimeout(1e3,()=>{s.destroy(),setTimeout(t,500)})}catch{setTimeout(t,500)}};setTimeout(t,1e3)}function gc(){ei();let r=new it;Qs(r),r.startLivenessCheck(6e4);let e=parseInt(process.env.HEALTH_PORT??"3101",10),t=(0,Zs.createServer)((n,s)=>{let i=Xs(),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. listening on 127.0.0.1:${e}`)}),t.on("error",n=>{console.error("[bridge] health.error",{error:n.message})})}function ri(){let r=process.env.BRIDGE_DAEMON==="1"||process.argv.includes("--daemon");if(!r&&!process.env.BRIDGE_PROFILE){let a=process.argv[1]??"";(a.includes("packages/daemon/dist")||a.includes("packages/daemon/src"))&&(console.warn("[bridge] WARNING: running monorepo daemon without --profile \u2014 will use prod config (~/.jerico/settings.json)."),console.warn("[bridge] If this is unintentional, stop and rerun with: node packages/daemon/dist/index.js --profile dev start"))}if(console.log("[bridge] Starting bridge-agent daemon..."),r){gc();return}dc()||(console.warn("[bridge] start.aborted.already.running"),process.exit(1));let e=lc(),t=uc(e),{ok:n,permissionDenied:s}=t?hc():{ok:!1,permissionDenied:!1},i=j.default.join(At,ke()),{out:o,err:c}=kt();if(n){console.log("[bridge] launchd.ok \u2014 managed, auto-restart enabled"),console.log("[bridge] logs: tail -f",{out:o,err:c}),fc(),process.exit(0);return}s&&(console.warn("[bridge] launchd.permission.denied"),console.warn("[bridge] \u2192 Auto-start on login requires:"),console.warn(`[bridge] sudo launchctl bootstrap gui/$(id -u) "${i}"`),console.warn(`[bridge] Falling back to background process...
|
|
421
|
+
`)),pc(e),process.exit(0)}var ni=_(require("https")),si=_(require("http"));xe();function mc(r){return(r??"").trim()}async function ii(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=mc(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 _c()),s||(console.error("[bridge] No token provided. Exiting."),process.exit(1)),await yc(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");le({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"),process.exit(0)}async function _c(){return new Promise(r=>{process.stdout.write("Token: ");let e="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",t=>{e+=t,e.includes(`
|
|
422
|
+
`)&&(process.stdin.pause(),r(e.trim()))}),process.stdin.resume()})}async function yc(r,e){return new Promise(t=>{let n=new URL("/api/tokens/validate",r),s=n.protocol==="https:",i=s?ni.default:si.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 oi=_(require("https")),ai=_(require("http")),jr=_(require("fs")),Lr=_(require("path")),ci=require("node:crypto");xe();function bc(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function li(r,e,t){let n=ce(),s=(0,ci.createHash)("sha256").update(n.token).digest("hex"),i=bc(n.server),o=Lr.default.resolve(t);Lr.default.isAbsolute(o)||(console.error("[bridge] link-project: path must be absolute"),process.exit(1)),jr.default.existsSync(o)||(console.error("[bridge] link-project: path does not exist:",o),process.exit(1)),jr.default.statSync(o).isDirectory()||(console.error("[bridge] link-project: path must be a directory:",o),process.exit(1));let a=new URL(`/api/workspaces/${r}/projects/${e}/machine-paths`,i),l=a.protocol==="https:",d=l?oi.default:ai.default;n.projectPaths={...n.projectPaths??{},[e]:o},le(n),console.log("[cli] link-project.local_json_written",{projectId:e,path:o});let u=JSON.stringify({daemonId:s,localPath:o,machineFingerprint:Rr()}),f=await new Promise((p,g)=>{let h=d.request({hostname:a.hostname,port:a.port||(l?443:80),path:a.pathname,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`,"Content-Length":Buffer.byteLength(u)}},m=>{let x="";m.on("data",S=>{x+=S}),m.on("end",()=>{if(m.statusCode===200)p(200);else{try{let S=JSON.parse(x);console.error("[bridge] link-project failed:",S.error??`HTTP ${m.statusCode}`)}catch{console.error("[bridge] link-project failed:",`HTTP ${m.statusCode}`)}p(m.statusCode??0)}})});h.on("error",m=>{g(m)}),h.write(u),h.end()});f===200?(console.log("[cli] link-project.server_success",{projectId:e}),console.log("[cli] link-project.success (dual-write)"),console.log(` workspace: ${r}`),console.log(` project: ${e}`),console.log(` daemon: ${s.slice(0,16)}\u2026`),console.log(` path: ${o}`),console.log("[cli] Next spawn for this project will use the linked path."),process.exit(0)):(console.warn("[cli] link-project.server_fail",{projectId:e,statusCode:f}),console.log("[cli] Local override still active \u2014 path will work on this machine"),process.exit(0))}xe();function wc(r){return r.replace(/^wss?:/,e=>e==="wss:"?"https:":"http:").replace(/\/ws(\/.*)?$/,"")}async function di(){let r=ce(),e=wc(r.server),t=await fetch(`${e}/api/admin/cleanup-orphans`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`,"Content-Type":"application/json"},body:"{}"});t.ok||(console.error(`[cli] cleanup-orphans: HTTP ${t.status}`),process.exit(1));let{deleted:n}=await t.json();console.log(`[cli] cleanup-orphans: deleted ${n} orphaned path ${n===1?"entry":"entries"}`),process.exit(0)}var Mr=require("node:child_process"),Ze=require("node:fs"),$r=_(require("path"));Ge();var ui=require("node:os"),Sc=$r.default.join((0,ui.homedir)(),"Library","LaunchAgents");function hi(){let r=ke(),e=r.replace(".plist",""),t=$r.default.join(Sc,r);try{(0,Mr.execSync)(`launchctl bootout gui/$(id -u)/${e}`,{stdio:"pipe"}),console.log("[bridge] launchd.stopped \u2014 daemon unloaded")}catch{try{(0,Ze.existsSync)(t)?((0,Mr.execSync)(`launchctl unload "${t}"`,{stdio:"pipe"}),console.log("[bridge] launchd.unloaded \u2014 daemon stopped")):console.warn("[bridge] launchd.stop.failed \u2014 plist not found, daemon may not be running via launchd")}catch{console.warn("[bridge] launchd.stop.failed \u2014 daemon may not be running via launchd"),console.warn(`[bridge] Manual: launchctl bootout gui/$(id -u)/${e}`)}}let n=He();if((0,Ze.existsSync)(n))try{(0,Ze.unlinkSync)(n),console.log("[bridge] lock.cleaned")}catch{}}var ee=new en;ee.name("bridge-agent").description("Bridge local agent \u2014 connects your AI tools to Jerico").version("0.4.2").option("--profile <name>","Config profile name (e.g. dev). Isolates config, lock, and fingerprint from the default prod profile.").hook("preAction",r=>{let e=r.opts().profile;e&&(process.env.BRIDGE_PROFILE=e)});ee.command("start").description("Start the bridge-agent daemon").option("--health-port <port>","Health check HTTP port (default: 3101, or 3101+offset per profile)").action(r=>{r.healthPort&&(process.env.HEALTH_PORT=r.healthPort),ri()});ee.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=>{ii(r.server,!r.browser,r.token)});ee.command("link-project <workspace-id> <project-id> <local-path>").description("Link a local directory to a project for this machine (Issue #152)").action((r,e,t)=>{li(r,e,t)});ee.command("cleanup-orphans").description("Remove orphaned daemon_project_paths rows for this user").action(()=>{di()});ee.command("status").description("Show connection status").action(async()=>{try{let{loadConfig:r}=await Promise.resolve().then(()=>(xe(),Bs)),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")}});ee.command("stop").description("Stop the bridge-agent daemon").action(()=>{hi()});ee.parse();
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# install-sim-prereqs.sh — Idempotent iOS Simulator prerequisites installer
|
|
3
|
+
# Usage: ./install-sim-prereqs.sh
|
|
4
|
+
# Exits 0 when all prerequisites are satisfied.
|
|
5
|
+
|
|
6
|
+
set -euo pipefail
|
|
7
|
+
|
|
8
|
+
STEP="pre_check"
|
|
9
|
+
INSTALL_TIMEOUT=1800 # 30 minutes for xcode-select GUI polling
|
|
10
|
+
POLL_INTERVAL=5 # seconds
|
|
11
|
+
IDB_PATH="${HOME}/.local/bin/idb"
|
|
12
|
+
|
|
13
|
+
# ── Helpers ──────────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
log_step() {
|
|
16
|
+
STEP="$1"
|
|
17
|
+
echo "STEP:${STEP}"
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
log_info() {
|
|
21
|
+
echo "[info] $*"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
log_error() {
|
|
25
|
+
echo "[error] $*" >&2
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
has_xcrun() {
|
|
29
|
+
xcode-select -p >/dev/null 2>&1
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
has_brew() {
|
|
33
|
+
command -v brew >/dev/null 2>&1
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
has_idb_companion() {
|
|
37
|
+
command -v idb-companion >/dev/null 2>&1
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
has_fb_idb() {
|
|
41
|
+
test -x "$IDB_PATH"
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
has_booted_simulator() {
|
|
45
|
+
local out
|
|
46
|
+
out=$(xcrun simctl list devices booted --json 2>/dev/null) || return 1
|
|
47
|
+
echo "$out" | grep -q '"state" *: *"Booted"'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
# ── Step 1: Xcode CLI tools ──────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
log_step "xcode_install"
|
|
53
|
+
|
|
54
|
+
if ! has_xcrun; then
|
|
55
|
+
log_info "Xcode CLI tools not found. Launching installer GUI..."
|
|
56
|
+
xcode-select --install || true
|
|
57
|
+
|
|
58
|
+
log_info "Polling for xcode-select -p (max ${INSTALL_TIMEOUT}s)..."
|
|
59
|
+
waited=0
|
|
60
|
+
while ! has_xcrun; do
|
|
61
|
+
sleep "$POLL_INTERVAL"
|
|
62
|
+
waited=$((waited + POLL_INTERVAL))
|
|
63
|
+
if [[ $waited -ge $INSTALL_TIMEOUT ]]; then
|
|
64
|
+
log_error "Timed out waiting for Xcode CLI tools install. If you cancelled the GUI, please re-run."
|
|
65
|
+
exit 1
|
|
66
|
+
fi
|
|
67
|
+
done
|
|
68
|
+
log_info "Xcode CLI tools detected."
|
|
69
|
+
else
|
|
70
|
+
log_info "Xcode CLI tools already present."
|
|
71
|
+
fi
|
|
72
|
+
|
|
73
|
+
# ── Step 2: Homebrew ─────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
log_step "brew_check"
|
|
76
|
+
|
|
77
|
+
if ! has_brew; then
|
|
78
|
+
log_error "Homebrew is not installed. Please install it first: https://brew.sh"
|
|
79
|
+
exit 11
|
|
80
|
+
fi
|
|
81
|
+
log_info "Homebrew OK."
|
|
82
|
+
|
|
83
|
+
# ── Step 3: idb-companion (native) ───────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
log_step "idb_install"
|
|
86
|
+
|
|
87
|
+
if ! has_idb_companion; then
|
|
88
|
+
log_info "Installing idb-companion via Homebrew..."
|
|
89
|
+
brew install facebook/fb/idb-companion
|
|
90
|
+
else
|
|
91
|
+
log_info "idb-companion already present."
|
|
92
|
+
fi
|
|
93
|
+
|
|
94
|
+
# ── Step 4: fb-idb (Python CLI) ──────────────────────────────────────────────
|
|
95
|
+
|
|
96
|
+
if ! has_fb_idb; then
|
|
97
|
+
log_info "Installing fb-idb via pip3..."
|
|
98
|
+
pip3 install --user fb-idb
|
|
99
|
+
if ! has_fb_idb; then
|
|
100
|
+
USER_BASE="$(python3 -m site --user-base 2>/dev/null || true)"
|
|
101
|
+
if [[ -n "$USER_BASE" && -x "${USER_BASE}/bin/idb" ]]; then
|
|
102
|
+
mkdir -p "$(dirname "$IDB_PATH")"
|
|
103
|
+
ln -sf "${USER_BASE}/bin/idb" "$IDB_PATH"
|
|
104
|
+
log_info "Symlinked idb from ${USER_BASE}/bin/idb to $IDB_PATH"
|
|
105
|
+
fi
|
|
106
|
+
fi
|
|
107
|
+
# Ensure ~/.local/bin is on PATH for future shells
|
|
108
|
+
if ! grep -q "${HOME}/.local/bin" "${HOME}/.zshrc" 2>/dev/null; then
|
|
109
|
+
echo 'export PATH="${HOME}/.local/bin:${PATH}"' >> "${HOME}/.zshrc"
|
|
110
|
+
log_info "Added ~/.local/bin to ~/.zshrc"
|
|
111
|
+
fi
|
|
112
|
+
if [[ -f "${HOME}/.bash_profile" ]] && ! grep -q "${HOME}/.local/bin" "${HOME}/.bash_profile" 2>/dev/null; then
|
|
113
|
+
echo 'export PATH="${HOME}/.local/bin:${PATH}"' >> "${HOME}/.bash_profile"
|
|
114
|
+
log_info "Added ~/.local/bin to ~/.bash_profile"
|
|
115
|
+
fi
|
|
116
|
+
else
|
|
117
|
+
log_info "fb-idb already present."
|
|
118
|
+
fi
|
|
119
|
+
|
|
120
|
+
# ── Step 5: Boot a default simulator ─────────────────────────────────────────
|
|
121
|
+
|
|
122
|
+
log_step "sim_boot"
|
|
123
|
+
|
|
124
|
+
if has_booted_simulator; then
|
|
125
|
+
log_info "Simulator already booted."
|
|
126
|
+
else
|
|
127
|
+
log_info "No booted simulator found. Attempting to boot iPhone 15..."
|
|
128
|
+
# Find the first available iPhone 15 device
|
|
129
|
+
udid=""
|
|
130
|
+
udid=$(xcrun simctl list devices available --json 2>/dev/null \
|
|
131
|
+
| python3 -c "
|
|
132
|
+
import sys, json
|
|
133
|
+
data = json.load(sys.stdin)
|
|
134
|
+
for runtime, devices in data.get('devices', {}).items():
|
|
135
|
+
for d in devices:
|
|
136
|
+
if 'iPhone 15' in d.get('name', '') and d.get('isAvailable', True):
|
|
137
|
+
print(d['udid'])
|
|
138
|
+
raise SystemExit
|
|
139
|
+
" 2>/dev/null || true)
|
|
140
|
+
|
|
141
|
+
if [[ -z "${udid:-}" ]]; then
|
|
142
|
+
log_info "No iPhone 15 found; trying any available iPhone..."
|
|
143
|
+
udid=$(xcrun simctl list devices available --json 2>/dev/null \
|
|
144
|
+
| python3 -c "
|
|
145
|
+
import sys, json
|
|
146
|
+
data = json.load(sys.stdin)
|
|
147
|
+
for runtime, devices in data.get('devices', {}).items():
|
|
148
|
+
for d in devices:
|
|
149
|
+
if 'iPhone' in d.get('name', '') and d.get('isAvailable', True):
|
|
150
|
+
print(d['udid'])
|
|
151
|
+
raise SystemExit
|
|
152
|
+
" 2>/dev/null || true)
|
|
153
|
+
fi
|
|
154
|
+
|
|
155
|
+
if [[ -n "${udid:-}" ]]; then
|
|
156
|
+
xcrun simctl boot "$udid" || true
|
|
157
|
+
log_info "Booted simulator $udid"
|
|
158
|
+
else
|
|
159
|
+
log_info "No simulator device found to boot. Please create one in Xcode → Window → Devices and Simulators."
|
|
160
|
+
fi
|
|
161
|
+
fi
|
|
162
|
+
|
|
163
|
+
if ! has_fb_idb; then
|
|
164
|
+
log_error "idb installed but not at expected path $IDB_PATH"
|
|
165
|
+
exit 12
|
|
166
|
+
fi
|
|
167
|
+
|
|
168
|
+
log_step "done"
|
|
169
|
+
log_info "All prerequisites satisfied."
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bridge-agent",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
4
4
|
"description": "Bridge local agent — connects your AI tools to Jerico",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"dist/",
|
|
13
|
+
"dist/scripts/",
|
|
14
|
+
"scripts/install-sim-prereqs.sh",
|
|
13
15
|
"scripts/postinstall.mjs",
|
|
14
16
|
"README.md",
|
|
15
17
|
"LICENSE"
|
package/scripts/postinstall.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { chmodSync, readdirSync, statSync } from 'fs'
|
|
1
|
+
import { chmodSync, readdirSync, statSync, copyFileSync, mkdirSync, existsSync } from 'fs'
|
|
2
2
|
import { fileURLToPath } from 'url'
|
|
3
3
|
import { dirname, resolve, join } from 'path'
|
|
4
|
+
import os from 'os'
|
|
4
5
|
|
|
5
6
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
6
7
|
|
|
@@ -51,3 +52,22 @@ try {
|
|
|
51
52
|
} catch (err) {
|
|
52
53
|
console.warn('[bridge-agent] postinstall: could not chmod bridge-mcp:', err.message)
|
|
53
54
|
}
|
|
55
|
+
|
|
56
|
+
// Ensure install-sim-prereqs.sh is executable and copied to ~/.bridge/
|
|
57
|
+
try {
|
|
58
|
+
const bundledScript = resolve(__dirname, '../dist/scripts/install-sim-prereqs.sh')
|
|
59
|
+
if (existsSync(bundledScript)) {
|
|
60
|
+
chmodSync(bundledScript, 0o755)
|
|
61
|
+
console.log('[bridge-agent] postinstall: install-sim-prereqs.sh chmod +x')
|
|
62
|
+
const bridgeDir = join(os.homedir(), '.bridge')
|
|
63
|
+
mkdirSync(bridgeDir, { recursive: true })
|
|
64
|
+
const dest = join(bridgeDir, 'install-sim-prereqs.sh')
|
|
65
|
+
copyFileSync(bundledScript, dest)
|
|
66
|
+
chmodSync(dest, 0o755)
|
|
67
|
+
console.log('[bridge-agent] postinstall: install-sim-prereqs.sh →', dest)
|
|
68
|
+
} else {
|
|
69
|
+
console.log('[bridge-agent] postinstall: install-sim-prereqs.sh not bundled — skipping')
|
|
70
|
+
}
|
|
71
|
+
} catch (err) {
|
|
72
|
+
console.warn('[bridge-agent] postinstall: could not copy install-sim-prereqs.sh:', err.message)
|
|
73
|
+
}
|