@director.run/cli 0.0.43 → 0.0.44

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.
Files changed (2) hide show
  1. package/dist/cli.js +3 -3
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -544,7 +544,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
544
544
  `)+w,p=J+1,J=D.indexOf(`
545
545
  `,p)}while(J!==-1);return B+=D.slice(p),B}var{stdout:tP,stderr:rP}=nP,Eu=Symbol("GENERATOR"),zD=Symbol("STYLER"),BJ=Symbol("IS_EMPTY"),eP=["ansi","ansi","ansi256","ansi16m"],UD=Object.create(null),XH1=(D,F={})=>{if(F.level&&!(Number.isInteger(F.level)&&F.level>=0&&F.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let w=tP?tP.level:0;D.level=F.level===void 0?w:F.level};var EH1=(D)=>{let F=(...w)=>w.join(" ");return XH1(F,D),Object.setPrototypeOf(F,YJ.prototype),F};function YJ(D){return EH1(D)}Object.setPrototypeOf(YJ.prototype,Function.prototype);for(let[D,F]of Object.entries(a4))UD[D]={get(){let w=vQ(this,Ku(F.open,F.close,this[zD]),this[BJ]);return Object.defineProperty(this,D,{value:w}),w}};UD.visible={get(){let D=vQ(this,this[zD],!0);return Object.defineProperty(this,"visible",{value:D}),D}};var Wu=(D,F,w,...J)=>{if(D==="rgb"){if(F==="ansi16m")return a4[w].ansi16m(...J);if(F==="ansi256")return a4[w].ansi256(a4.rgbToAnsi256(...J));return a4[w].ansi(a4.rgbToAnsi(...J))}if(D==="hex")return Wu("rgb",F,w,...a4.hexToRgb(...J));return a4[w][D](...J)},WH1=["rgb","hex","ansi256"];for(let D of WH1){UD[D]={get(){let{level:w}=this;return function(...J){let p=Ku(Wu(D,eP[w],"color",...J),a4.color.close,this[zD]);return vQ(this,p,this[BJ])}}};let F="bg"+D[0].toUpperCase()+D.slice(1);UD[F]={get(){let{level:w}=this;return function(...J){let p=Ku(Wu(D,eP[w],"bgColor",...J),a4.bgColor.close,this[zD]);return vQ(this,p,this[BJ])}}}}var KH1=Object.defineProperties(()=>{},{...UD,level:{enumerable:!0,get(){return this[Eu].level},set(D){this[Eu].level=D}}}),Ku=(D,F,w)=>{let J,p;if(w===void 0)J=D,p=F;else J=w.openAll+D,p=F+w.closeAll;return{open:D,close:F,openAll:J,closeAll:p,parent:w}},vQ=(D,F,w)=>{let J=(...p)=>VH1(J,p.length===1?""+p[0]:p.join(" "));return Object.setPrototypeOf(J,KH1),J[Eu]=D,J[zD]=F,J[BJ]=w,J},VH1=(D,F)=>{if(D.level<=0||!F)return D[BJ]?"":F;let w=D[zD];if(w===void 0)return F;let{openAll:J,closeAll:p}=w;if(F.includes("\x1B"))while(w!==void 0)F=oP(F,w.close,w.open),w=w.parent;let B=F.indexOf(`
546
546
  `);if(B!==-1)F=sP(F,p,J,B);return J+F+p};Object.defineProperties(YJ.prototype,UD);var HH1=YJ(),GB0=YJ({level:rP?rP.level:0});var x1=HH1;var Jx=z1(wx(),1),O8=Gu("#0099F7"),z5=Gu("#F11712"),QJ=Gu("#00FF00"),Hu=(D)=>x1.yellow(D);function Gu(D){let F=zH1(D);return(w)=>`\x1B[38;5;${F}m${w}${Jx.default.reset("")}`}function zH1(D){let F=parseInt(D.slice(1),16),w=Math.floor(F/65536)%256,J=Math.floor(F/256)%256,p=F%256;return 16+36*Math.round(w/255*5)+6*Math.round(J/255*5)+Math.round(p/255*5)}function G2(D){return x1.white.bold(D)}var uu=" ".repeat(2);function Yx(D){let F=[];if(D._enableDebugCommands)F.push(Hu("\uD83D\uDEA7 debug commands appear in yellow \uD83D\uDEA7")),F.push("");if(F.push(D.description().trim()),F.push(""),F.push(ZD("usage")),F.push(uu+XJ([D.parent?D.parent.name():"",D.name(),Xx("command"),"[subcommand]","[flags]"])),F.push(""),D.parent)F.push(ZD(`${D.name()} commands`));else F.push(ZD("core commands"));D.commands.toSorted((J,p)=>Number(!!J.commands.length)-Number(!!p.commands.length)).forEach((J)=>{if(J.commands.length)F.push(""),F.push(ZD(J.name())),J.commands.forEach((p)=>{F.push(px(p))});else F.push(px(J))}),F.push("");let w=[D._helpOption,...D.options].filter((J)=>J!==void 0);if(w.length)F.push(ZD("flags")),w.forEach((J)=>{F.push(XJ([uu,J.flags,Qx(J.description,J.flags.length)]))}),F.push("");if(D.examples)F.push(ZD("examples")),F.push(" "+D.examples.trim()),F.push("");return F.push(""),F.join(`
547
- `)}var ZD=(D)=>{return G2(D.toLocaleUpperCase())},px=(D)=>{let F=D.registeredArguments.map((B)=>B.required?Xx(B.name()):Bx(B.name())).filter((B)=>B!=="").join(" "),w=XJ([XJ([D.parent&&D.parent.parent?D.parent?.name():void 0,D.name()]),F,D.options.length?Bx("options"):""]),J=D.description()||z5("TODO"),p=XJ([uu,w,Qx(J,w.length)]);return D._debug?Hu(p):p},Qx=(D,F)=>{return" ".repeat(Math.max(0,45-F))+D},Xx=(D)=>["<",D,">"].join(""),Bx=(D)=>["[",D,"]"].join(""),XJ=(D)=>D.filter(Boolean).join(" ");class U5 extends Qu{debug=!0;examples="";constructor(D){super(D);this.helpCommand(!1)}showDebugCommands(D){return this._enableDebugCommands=D,this}debugCommand(D,F){if(this._enableDebugCommands){let w=super.command(D,F);return w._enableDebugCommands=!0,w._debug=!0,w}else return new Qu(D)}helpInformation(D){return Yx(this)}addExamples(D){this.examples=D}addCommand(D,F){return D._enableDebugCommands=this._enableDebugCommands,D._debug=this._debug,super.addCommand(D,F)}}function L8({flags:D,description:F,defaultValue:w,choices:J,mandatory:p}){let B=new yP(D,F);return p&&B.makeOptionMandatory(),w&&B.default(w),J&&B.choices(J),B}var K9={name:"@director.run/cli",type:"module",version:"0.0.43",files:["dist","README.md"],bin:{director:"./dist/cli.js"},license:"MIT",repository:{type:"git",url:"https://github.com/director-run/director"},description:"The easiest way to manage and deploy MCP servers",author:"The Working Company <hello@director.run>",homepage:"https://director.run",scripts:{lint:"biome check .",format:"biome format --write .",clean:"rm -rf .turbo dist/*",test:"bun run vitest --fileParallelism=false",cli:"NODE_ENV=development bun run bin/cli.ts",typecheck:"tsc --noEmit",build:"bun build --production --target=node bin/cli.ts --outdir dist",release:"bun publish --access public --omit=peer",prepare:"bun run build",dev:"bun --watch bin/cli.ts"},peerDependencies:{typescript:"^5"},devDependencies:{"@director.run/gateway":"workspace:*","@director.run/mcp":"workspace:*","@director.run/utilities":"workspace:*","@inquirer/prompts":"^7.5.2","@types/update-notifier":"^6.0.8",boxen:"^8.0.1",chalk:"^5.4.1","cli-table3":"^0.6.5",commander:"^13.1.0",semver:"^7.7.2",superjson:"^2.2.2","type-fest":"^4.40.0","update-notifier":"^7.3.1","@segment/analytics-node":"^2.3.0","node-machine-id":"^1.1.12"}};import kQ from"node:process";function Nu({onlyFirst:D=!1}={}){let w=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(w,D?void 0:"g")}var ZH1=Nu();function Z5(D){if(typeof D!=="string")throw new TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(ZH1,"")}function Ex(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function Wx(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function Kx(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function $H1(D){if(!Number.isSafeInteger(D))throw new TypeError(`Expected a code point, got \`${typeof D}\`.`)}function Vx(D,{ambiguousAsWide:F=!1}={}){if($H1(D),Wx(D)||Kx(D)||F&&Ex(D))return 2;return 1}var ux=z1(Gx(),1),MH1=new Intl.Segmenter,qH1=/^\p{Default_Ignorable_Code_Point}$/u;function k2(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:w=!0,countAnsiEscapeCodes:J=!1}=F;if(!J)D=Z5(D);if(D.length===0)return 0;let p=0,B={ambiguousAsWide:!w};for(let{segment:Y}of MH1.segment(D)){let Q=Y.codePointAt(0);if(Q<=31||Q>=127&&Q<=159)continue;if(Q>=8203&&Q<=8207||Q===65279)continue;if(Q>=768&&Q<=879||Q>=6832&&Q<=6911||Q>=7616&&Q<=7679||Q>=8400&&Q<=8447||Q>=65056&&Q<=65071)continue;if(Q>=55296&&Q<=57343)continue;if(Q>=65024&&Q<=65039)continue;if(qH1.test(Y))continue;if(ux.default().test(Y)){p+=2;continue}p+=Vx(Q,B)}return p}function dQ(D){let F=0;for(let w of D.split(`
547
+ `)}var ZD=(D)=>{return G2(D.toLocaleUpperCase())},px=(D)=>{let F=D.registeredArguments.map((B)=>B.required?Xx(B.name()):Bx(B.name())).filter((B)=>B!=="").join(" "),w=XJ([XJ([D.parent&&D.parent.parent?D.parent?.name():void 0,D.name()]),F,D.options.length?Bx("options"):""]),J=D.description()||z5("TODO"),p=XJ([uu,w,Qx(J,w.length)]);return D._debug?Hu(p):p},Qx=(D,F)=>{return" ".repeat(Math.max(0,45-F))+D},Xx=(D)=>["<",D,">"].join(""),Bx=(D)=>["[",D,"]"].join(""),XJ=(D)=>D.filter(Boolean).join(" ");class U5 extends Qu{debug=!0;examples="";constructor(D){super(D);this.helpCommand(!1)}showDebugCommands(D){return this._enableDebugCommands=D,this}debugCommand(D,F){if(this._enableDebugCommands){let w=super.command(D,F);return w._enableDebugCommands=!0,w._debug=!0,w}else return new Qu(D)}helpInformation(D){return Yx(this)}addExamples(D){this.examples=D}addCommand(D,F){return D._enableDebugCommands=this._enableDebugCommands,D._debug=this._debug,super.addCommand(D,F)}}function L8({flags:D,description:F,defaultValue:w,choices:J,mandatory:p}){let B=new yP(D,F);return p&&B.makeOptionMandatory(),w&&B.default(w),J&&B.choices(J),B}var K9={name:"@director.run/cli",type:"module",version:"0.0.44",files:["dist","README.md"],bin:{director:"./dist/cli.js"},license:"MIT",repository:{type:"git",url:"https://github.com/director-run/director"},description:"The easiest way to manage and deploy MCP servers",author:"The Working Company <hello@director.run>",homepage:"https://director.run",scripts:{lint:"biome check .",format:"biome format --write .",clean:"rm -rf .turbo dist/*",test:"bun run vitest --fileParallelism=false",cli:"NODE_ENV=development bun run bin/cli.ts",typecheck:"tsc --noEmit",build:"bun build --production --target=node bin/cli.ts --outdir dist",release:"bun publish --access public --omit=peer",prepare:"bun run build",dev:"bun --watch bin/cli.ts"},peerDependencies:{typescript:"^5"},devDependencies:{"@director.run/gateway":"workspace:*","@director.run/mcp":"workspace:*","@director.run/utilities":"workspace:*","@inquirer/prompts":"^7.5.2","@types/update-notifier":"^6.0.8",boxen:"^8.0.1",chalk:"^5.4.1","cli-table3":"^0.6.5",commander:"^13.1.0",semver:"^7.7.2",superjson:"^2.2.2","type-fest":"^4.40.0","update-notifier":"^7.3.1","@segment/analytics-node":"^2.3.0","node-machine-id":"^1.1.12"}};import kQ from"node:process";function Nu({onlyFirst:D=!1}={}){let w=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");return new RegExp(w,D?void 0:"g")}var ZH1=Nu();function Z5(D){if(typeof D!=="string")throw new TypeError(`Expected a \`string\`, got \`${typeof D}\``);return D.replace(ZH1,"")}function Ex(D){return D===161||D===164||D===167||D===168||D===170||D===173||D===174||D>=176&&D<=180||D>=182&&D<=186||D>=188&&D<=191||D===198||D===208||D===215||D===216||D>=222&&D<=225||D===230||D>=232&&D<=234||D===236||D===237||D===240||D===242||D===243||D>=247&&D<=250||D===252||D===254||D===257||D===273||D===275||D===283||D===294||D===295||D===299||D>=305&&D<=307||D===312||D>=319&&D<=322||D===324||D>=328&&D<=331||D===333||D===338||D===339||D===358||D===359||D===363||D===462||D===464||D===466||D===468||D===470||D===472||D===474||D===476||D===593||D===609||D===708||D===711||D>=713&&D<=715||D===717||D===720||D>=728&&D<=731||D===733||D===735||D>=768&&D<=879||D>=913&&D<=929||D>=931&&D<=937||D>=945&&D<=961||D>=963&&D<=969||D===1025||D>=1040&&D<=1103||D===1105||D===8208||D>=8211&&D<=8214||D===8216||D===8217||D===8220||D===8221||D>=8224&&D<=8226||D>=8228&&D<=8231||D===8240||D===8242||D===8243||D===8245||D===8251||D===8254||D===8308||D===8319||D>=8321&&D<=8324||D===8364||D===8451||D===8453||D===8457||D===8467||D===8470||D===8481||D===8482||D===8486||D===8491||D===8531||D===8532||D>=8539&&D<=8542||D>=8544&&D<=8555||D>=8560&&D<=8569||D===8585||D>=8592&&D<=8601||D===8632||D===8633||D===8658||D===8660||D===8679||D===8704||D===8706||D===8707||D===8711||D===8712||D===8715||D===8719||D===8721||D===8725||D===8730||D>=8733&&D<=8736||D===8739||D===8741||D>=8743&&D<=8748||D===8750||D>=8756&&D<=8759||D===8764||D===8765||D===8776||D===8780||D===8786||D===8800||D===8801||D>=8804&&D<=8807||D===8810||D===8811||D===8814||D===8815||D===8834||D===8835||D===8838||D===8839||D===8853||D===8857||D===8869||D===8895||D===8978||D>=9312&&D<=9449||D>=9451&&D<=9547||D>=9552&&D<=9587||D>=9600&&D<=9615||D>=9618&&D<=9621||D===9632||D===9633||D>=9635&&D<=9641||D===9650||D===9651||D===9654||D===9655||D===9660||D===9661||D===9664||D===9665||D>=9670&&D<=9672||D===9675||D>=9678&&D<=9681||D>=9698&&D<=9701||D===9711||D===9733||D===9734||D===9737||D===9742||D===9743||D===9756||D===9758||D===9792||D===9794||D===9824||D===9825||D>=9827&&D<=9829||D>=9831&&D<=9834||D===9836||D===9837||D===9839||D===9886||D===9887||D===9919||D>=9926&&D<=9933||D>=9935&&D<=9939||D>=9941&&D<=9953||D===9955||D===9960||D===9961||D>=9963&&D<=9969||D===9972||D>=9974&&D<=9977||D===9979||D===9980||D===9982||D===9983||D===10045||D>=10102&&D<=10111||D>=11094&&D<=11097||D>=12872&&D<=12879||D>=57344&&D<=63743||D>=65024&&D<=65039||D===65533||D>=127232&&D<=127242||D>=127248&&D<=127277||D>=127280&&D<=127337||D>=127344&&D<=127373||D===127375||D===127376||D>=127387&&D<=127404||D>=917760&&D<=917999||D>=983040&&D<=1048573||D>=1048576&&D<=1114109}function Wx(D){return D===12288||D>=65281&&D<=65376||D>=65504&&D<=65510}function Kx(D){return D>=4352&&D<=4447||D===8986||D===8987||D===9001||D===9002||D>=9193&&D<=9196||D===9200||D===9203||D===9725||D===9726||D===9748||D===9749||D>=9776&&D<=9783||D>=9800&&D<=9811||D===9855||D>=9866&&D<=9871||D===9875||D===9889||D===9898||D===9899||D===9917||D===9918||D===9924||D===9925||D===9934||D===9940||D===9962||D===9970||D===9971||D===9973||D===9978||D===9981||D===9989||D===9994||D===9995||D===10024||D===10060||D===10062||D>=10067&&D<=10069||D===10071||D>=10133&&D<=10135||D===10160||D===10175||D===11035||D===11036||D===11088||D===11093||D>=11904&&D<=11929||D>=11931&&D<=12019||D>=12032&&D<=12245||D>=12272&&D<=12287||D>=12289&&D<=12350||D>=12353&&D<=12438||D>=12441&&D<=12543||D>=12549&&D<=12591||D>=12593&&D<=12686||D>=12688&&D<=12773||D>=12783&&D<=12830||D>=12832&&D<=12871||D>=12880&&D<=42124||D>=42128&&D<=42182||D>=43360&&D<=43388||D>=44032&&D<=55203||D>=63744&&D<=64255||D>=65040&&D<=65049||D>=65072&&D<=65106||D>=65108&&D<=65126||D>=65128&&D<=65131||D>=94176&&D<=94180||D===94192||D===94193||D>=94208&&D<=100343||D>=100352&&D<=101589||D>=101631&&D<=101640||D>=110576&&D<=110579||D>=110581&&D<=110587||D===110589||D===110590||D>=110592&&D<=110882||D===110898||D>=110928&&D<=110930||D===110933||D>=110948&&D<=110951||D>=110960&&D<=111355||D>=119552&&D<=119638||D>=119648&&D<=119670||D===126980||D===127183||D===127374||D>=127377&&D<=127386||D>=127488&&D<=127490||D>=127504&&D<=127547||D>=127552&&D<=127560||D===127568||D===127569||D>=127584&&D<=127589||D>=127744&&D<=127776||D>=127789&&D<=127797||D>=127799&&D<=127868||D>=127870&&D<=127891||D>=127904&&D<=127946||D>=127951&&D<=127955||D>=127968&&D<=127984||D===127988||D>=127992&&D<=128062||D===128064||D>=128066&&D<=128252||D>=128255&&D<=128317||D>=128331&&D<=128334||D>=128336&&D<=128359||D===128378||D===128405||D===128406||D===128420||D>=128507&&D<=128591||D>=128640&&D<=128709||D===128716||D>=128720&&D<=128722||D>=128725&&D<=128727||D>=128732&&D<=128735||D===128747||D===128748||D>=128756&&D<=128764||D>=128992&&D<=129003||D===129008||D>=129292&&D<=129338||D>=129340&&D<=129349||D>=129351&&D<=129535||D>=129648&&D<=129660||D>=129664&&D<=129673||D>=129679&&D<=129734||D>=129742&&D<=129756||D>=129759&&D<=129769||D>=129776&&D<=129784||D>=131072&&D<=196605||D>=196608&&D<=262141}function $H1(D){if(!Number.isSafeInteger(D))throw new TypeError(`Expected a code point, got \`${typeof D}\`.`)}function Vx(D,{ambiguousAsWide:F=!1}={}){if($H1(D),Wx(D)||Kx(D)||F&&Ex(D))return 2;return 1}var ux=z1(Gx(),1),MH1=new Intl.Segmenter,qH1=/^\p{Default_Ignorable_Code_Point}$/u;function k2(D,F={}){if(typeof D!=="string"||D.length===0)return 0;let{ambiguousIsNarrow:w=!0,countAnsiEscapeCodes:J=!1}=F;if(!J)D=Z5(D);if(D.length===0)return 0;let p=0,B={ambiguousAsWide:!w};for(let{segment:Y}of MH1.segment(D)){let Q=Y.codePointAt(0);if(Q<=31||Q>=127&&Q<=159)continue;if(Q>=8203&&Q<=8207||Q===65279)continue;if(Q>=768&&Q<=879||Q>=6832&&Q<=6911||Q>=7616&&Q<=7679||Q>=8400&&Q<=8447||Q>=65056&&Q<=65071)continue;if(Q>=55296&&Q<=57343)continue;if(Q>=65024&&Q<=65039)continue;if(qH1.test(Y))continue;if(ux.default().test(Y)){p+=2;continue}p+=Vx(Q,B)}return p}function dQ(D){let F=0;for(let w of D.split(`
548
548
  `))F=Math.max(F,k2(w));return F}var cx=z1(Uu(),1);var CH1=/[\p{Lu}]/u,OH1=/[\p{Ll}]/u,Ux=/^[\p{Lu}](?![\p{Lu}])/gu,Mx=/([\p{Alpha}\p{N}_]|$)/u,Zu=/[_.\- ]+/,LH1=new RegExp("^"+Zu.source),Zx=new RegExp(Zu.source+Mx.source,"gu"),$x=new RegExp("\\d+"+Mx.source,"gu"),TH1=(D,F,w,J)=>{let p=!1,B=!1,Y=!1,Q=!1;for(let X=0;X<D.length;X++){let W=D[X];if(Q=X>2?D[X-3]==="-":!0,p&&CH1.test(W))D=D.slice(0,X)+"-"+D.slice(X),p=!1,Y=B,B=!0,X++;else if(B&&Y&&OH1.test(W)&&(!Q||J))D=D.slice(0,X-1)+"-"+D.slice(X-1),Y=B,B=!1,p=!0;else p=F(W)===W&&w(W)!==W,Y=B,B=w(W)===W&&F(W)!==W}return D},RH1=(D,F)=>{return Ux.lastIndex=0,D.replaceAll(Ux,(w)=>F(w))},PH1=(D,F)=>{return Zx.lastIndex=0,$x.lastIndex=0,D.replaceAll($x,(w,J,p)=>["_","-"].includes(D.charAt(p+w.length))?w:F(w)).replaceAll(Zx,(w,J)=>F(J))};function $u(D,F){if(!(typeof D==="string"||Array.isArray(D)))throw new TypeError("Expected the input to be `string | string[]`");if(F={pascalCase:!1,preserveConsecutiveUppercase:!1,...F},Array.isArray(D))D=D.map((B)=>B.trim()).filter((B)=>B.length).join("-");else D=D.trim();if(D.length===0)return"";let w=F.locale===!1?(B)=>B.toLowerCase():(B)=>B.toLocaleLowerCase(F.locale),J=F.locale===!1?(B)=>B.toUpperCase():(B)=>B.toLocaleUpperCase(F.locale);if(D.length===1){if(Zu.test(D))return"";return F.pascalCase?J(D):w(D)}if(D!==w(D))D=TH1(D,w,J,F.preserveConsecutiveUppercase);if(D=D.replace(LH1,""),D=F.preserveConsecutiveUppercase?RH1(D,w):w(D),F.pascalCase)D=J(D.charAt(0))+D.slice(1);return PH1(D,J)}var Ou=z1(Ix(),1);var Sx=(D=0)=>(F)=>`\x1B[${F+D}m`,dx=(D=0)=>(F)=>`\x1B[${38+D};5;${F}m`,_x=(D=0)=>(F,w,J)=>`\x1B[${38+D};2;${F};${w};${J}m`,j0={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},nB0=Object.keys(j0.modifier),fH1=Object.keys(j0.color),mH1=Object.keys(j0.bgColor),oB0=[...fH1,...mH1];function kH1(){let D=new Map;for(let[F,w]of Object.entries(j0)){for(let[J,p]of Object.entries(w))j0[J]={open:`\x1B[${p[0]}m`,close:`\x1B[${p[1]}m`},w[J]=j0[J],D.set(p[0],p[1]);Object.defineProperty(j0,F,{value:w,enumerable:!1})}return Object.defineProperty(j0,"codes",{value:D,enumerable:!1}),j0.color.close="\x1B[39m",j0.bgColor.close="\x1B[49m",j0.color.ansi=Sx(),j0.color.ansi256=dx(),j0.color.ansi16m=_x(),j0.bgColor.ansi=Sx(10),j0.bgColor.ansi256=dx(10),j0.bgColor.ansi16m=_x(10),Object.defineProperties(j0,{rgbToAnsi256:{value:(F,w,J)=>{if(F===w&&w===J){if(F<8)return 16;if(F>248)return 231;return Math.round((F-8)/247*24)+232}return 16+36*Math.round(F/255*5)+6*Math.round(w/255*5)+Math.round(J/255*5)},enumerable:!1},hexToRgb:{value:(F)=>{let w=/[a-f\d]{6}|[a-f\d]{3}/i.exec(F.toString(16));if(!w)return[0,0,0];let[J]=w;if(J.length===3)J=[...J].map((B)=>B+B).join("");let p=Number.parseInt(J,16);return[p>>16&255,p>>8&255,p&255]},enumerable:!1},hexToAnsi256:{value:(F)=>j0.rgbToAnsi256(...j0.hexToRgb(F)),enumerable:!1},ansi256ToAnsi:{value:(F)=>{if(F<8)return 30+F;if(F<16)return 90+(F-8);let w,J,p;if(F>=232)w=((F-232)*10+8)/255,J=w,p=w;else{F-=16;let Q=F%36;w=Math.floor(F/36)/5,J=Math.floor(Q/6)/5,p=Q%6/5}let B=Math.max(w,J,p)*2;if(B===0)return 30;let Y=30+(Math.round(p)<<2|Math.round(J)<<1|Math.round(w));if(B===2)Y+=60;return Y},enumerable:!1},rgbToAnsi:{value:(F,w,J)=>j0.ansi256ToAnsi(j0.rgbToAnsi256(F,w,J)),enumerable:!1},hexToAnsi:{value:(F)=>j0.ansi256ToAnsi(j0.hexToAnsi256(F)),enumerable:!1}}),j0}var bH1=kH1(),jx=bH1;var fQ=new Set(["\x1B","›"]),hH1=39,Cu="\x07",kx="[",yH1="]",bx="m",jQ=`${yH1}8;;`,fx=(D)=>`${fQ.values().next().value}${kx}${D}${bx}`,mx=(D)=>`${fQ.values().next().value}${jQ}${D}${Cu}`,iH1=(D)=>D.split(" ").map((F)=>k2(F)),Au=(D,F,w)=>{let J=[...F],p=!1,B=!1,Y=k2(Z5(D.at(-1)));for(let[Q,X]of J.entries()){let W=k2(X);if(Y+W<=w)D[D.length-1]+=X;else D.push(X),Y=0;if(fQ.has(X))p=!0,B=J.slice(Q+1,Q+1+jQ.length).join("")===jQ;if(p){if(B){if(X===Cu)p=!1,B=!1}else if(X===bx)p=!1;continue}if(Y+=W,Y===w&&Q<J.length-1)D.push(""),Y=0}if(!Y&&D.at(-1).length>0&&D.length>1)D[D.length-2]+=D.pop()},cH1=(D)=>{let F=D.split(" "),w=F.length;while(w>0){if(k2(F[w-1])>0)break;w--}if(w===F.length)return D;return F.slice(0,w).join(" ")+F.slice(w).join("")},lH1=(D,F,w={})=>{if(w.trim!==!1&&D.trim()==="")return"";let J="",p,B,Y=iH1(D),Q=[""];for(let[H,N]of D.split(" ").entries()){if(w.trim!==!1)Q[Q.length-1]=Q.at(-1).trimStart();let u=k2(Q.at(-1));if(H!==0){if(u>=F&&(w.wordWrap===!1||w.trim===!1))Q.push(""),u=0;if(u>0||w.trim===!1)Q[Q.length-1]+=" ",u++}if(w.hard&&Y[H]>F){let G=F-u,U=1+Math.floor((Y[H]-G-1)/F);if(Math.floor((Y[H]-1)/F)<U)Q.push("");Au(Q,N,F);continue}if(u+Y[H]>F&&u>0&&Y[H]>0){if(w.wordWrap===!1&&u<F){Au(Q,N,F);continue}Q.push("")}if(u+Y[H]>F&&w.wordWrap===!1){Au(Q,N,F);continue}Q[Q.length-1]+=N}if(w.trim!==!1)Q=Q.map((H)=>cH1(H));let X=Q.join(`
549
549
  `),W=[...X],K=0;for(let[H,N]of W.entries()){if(J+=N,fQ.has(N)){let{groups:G}=new RegExp(`(?:\\${kx}(?<code>\\d+)m|\\${jQ}(?<uri>.*)${Cu})`).exec(X.slice(K))||{groups:{}};if(G.code!==void 0){let U=Number.parseFloat(G.code);p=U===hH1?void 0:U}else if(G.uri!==void 0)B=G.uri.length===0?void 0:G.uri}let u=jx.codes.get(Number(p));if(W[H+1]===`
550
550
  `){if(B)J+=mx("");if(p&&u)J+=fx(u)}else if(N===`
@@ -600,7 +600,7 @@ data: ${JSON.stringify(D)}
600
600
  `;break;case"id":Q=Z.includes("\x00")?void 0:Z;break;case"retry":/^\d+$/.test(Z)?J(parseInt(Z,10)):w(new Qq(`Invalid \`retry\` value: "${Z}"`,{type:"invalid-retry",value:Z,line:C}));break;default:w(new Qq(`Unknown field "${U.length>20?`${U.slice(0,20)}…`:U}"`,{type:"unknown-field",field:U,value:Z,line:C}));break}}function u(){X.length>0&&F({id:Q,event:W||void 0,data:X.endsWith(`
601
601
  `)?X.slice(0,-1):X}),Q=void 0,X="",W=""}function G(U={}){B&&U.consume&&H(B),Y=!0,Q=void 0,X="",W="",B=""}return{feed:K,reset:G}}function sc1(D){let F=[],w="",J=0;for(;J<D.length;){let p=D.indexOf("\r",J),B=D.indexOf(`
602
602
  `,J),Y=-1;if(p!==-1&&B!==-1?Y=Math.min(p,B):p!==-1?Y=p:B!==-1&&(Y=B),Y===-1){w=D.slice(J);break}else{let Q=D.slice(J,Y);F.push(Q),J=Y+1,D[J-1]==="\r"&&D[J]===`
603
- `&&J++}}return[F,w]}class Xq extends Event{constructor(D,F){var w,J;super(D),this.code=(w=F==null?void 0:F.code)!=null?w:void 0,this.message=(J=F==null?void 0:F.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](D,F,w){return w(us(this),F)}[Symbol.for("Deno.customInspect")](D,F){return D(us(this),F)}}function tc1(D){let F=globalThis.DOMException;return typeof F=="function"?new F(D,"SyntaxError"):new SyntaxError(D)}function Eq(D){return D instanceof Error?"errors"in D&&Array.isArray(D.errors)?D.errors.map(Eq).join(", "):("cause"in D)&&D.cause instanceof Error?`${D}: ${Eq(D.cause)}`:D.message:`${D}`}function us(D){return{type:D.type,message:D.message,code:D.code,defaultPrevented:D.defaultPrevented,cancelable:D.cancelable,timeStamp:D.timeStamp}}var zs=(D)=>{throw TypeError(D)},zq=(D,F,w)=>F.has(D)||zs("Cannot "+w),o1=(D,F,w)=>(zq(D,F,"read from private field"),w?w.call(D):F.get(D)),Z2=(D,F,w)=>F.has(D)?zs("Cannot add the same private member more than once"):F instanceof WeakSet?F.add(D):F.set(D,w),m0=(D,F,w,J)=>(zq(D,F,"write to private field"),F.set(D,w),w),I3=(D,F,w)=>(zq(D,F,"access private method"),w),k6,z7,vF,ZK,$K,AB,dF,CB,v9,IF,_F,SF,MB,B8,Wq,Kq,Vq,Ns,Hq,Gq,qB,uq,Nq;class I9 extends EventTarget{constructor(D,F){var w,J;super(),Z2(this,B8),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Z2(this,k6),Z2(this,z7),Z2(this,vF),Z2(this,ZK),Z2(this,$K),Z2(this,AB),Z2(this,dF),Z2(this,CB,null),Z2(this,v9),Z2(this,IF),Z2(this,_F,null),Z2(this,SF,null),Z2(this,MB,null),Z2(this,Kq,async(p)=>{var B;o1(this,IF).reset();let{body:Y,redirected:Q,status:X,headers:W}=p;if(X===204){I3(this,B8,qB).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Q?m0(this,vF,new URL(p.url)):m0(this,vF,void 0),X!==200){I3(this,B8,qB).call(this,`Non-200 status code (${X})`,X);return}if(!(W.get("content-type")||"").startsWith("text/event-stream")){I3(this,B8,qB).call(this,'Invalid content type, expected "text/event-stream"',X);return}if(o1(this,k6)===this.CLOSED)return;m0(this,k6,this.OPEN);let K=new Event("open");if((B=o1(this,MB))==null||B.call(this,K),this.dispatchEvent(K),typeof Y!="object"||!Y||!("getReader"in Y)){I3(this,B8,qB).call(this,"Invalid response body, expected a web ReadableStream",X),this.close();return}let H=new TextDecoder,N=Y.getReader(),u=!0;do{let{done:G,value:U}=await N.read();U&&o1(this,IF).feed(H.decode(U,{stream:!G})),G&&(u=!1,o1(this,IF).reset(),I3(this,B8,uq).call(this))}while(u)}),Z2(this,Vq,(p)=>{m0(this,v9,void 0),!(p.name==="AbortError"||p.type==="aborted")&&I3(this,B8,uq).call(this,Eq(p))}),Z2(this,Hq,(p)=>{typeof p.id=="string"&&m0(this,CB,p.id);let B=new MessageEvent(p.event||"message",{data:p.data,origin:o1(this,vF)?o1(this,vF).origin:o1(this,z7).origin,lastEventId:p.id||""});o1(this,SF)&&(!p.event||p.event==="message")&&o1(this,SF).call(this,B),this.dispatchEvent(B)}),Z2(this,Gq,(p)=>{m0(this,AB,p)}),Z2(this,Nq,()=>{m0(this,dF,void 0),o1(this,k6)===this.CONNECTING&&I3(this,B8,Wq).call(this)});try{if(D instanceof URL)m0(this,z7,D);else if(typeof D=="string")m0(this,z7,new URL(D,rc1()));else throw new Error("Invalid URL")}catch{throw tc1("An invalid or illegal string was specified")}m0(this,IF,UK({onEvent:o1(this,Hq),onRetry:o1(this,Gq)})),m0(this,k6,this.CONNECTING),m0(this,AB,3000),m0(this,$K,(w=F==null?void 0:F.fetch)!=null?w:globalThis.fetch),m0(this,ZK,(J=F==null?void 0:F.withCredentials)!=null?J:!1),I3(this,B8,Wq).call(this)}get readyState(){return o1(this,k6)}get url(){return o1(this,z7).href}get withCredentials(){return o1(this,ZK)}get onerror(){return o1(this,_F)}set onerror(D){m0(this,_F,D)}get onmessage(){return o1(this,SF)}set onmessage(D){m0(this,SF,D)}get onopen(){return o1(this,MB)}set onopen(D){m0(this,MB,D)}addEventListener(D,F,w){let J=F;super.addEventListener(D,J,w)}removeEventListener(D,F,w){let J=F;super.removeEventListener(D,J,w)}close(){o1(this,dF)&&clearTimeout(o1(this,dF)),o1(this,k6)!==this.CLOSED&&(o1(this,v9)&&o1(this,v9).abort(),m0(this,k6,this.CLOSED),m0(this,v9,void 0))}}k6=new WeakMap,z7=new WeakMap,vF=new WeakMap,ZK=new WeakMap,$K=new WeakMap,AB=new WeakMap,dF=new WeakMap,CB=new WeakMap,v9=new WeakMap,IF=new WeakMap,_F=new WeakMap,SF=new WeakMap,MB=new WeakMap,B8=new WeakSet,Wq=function(){m0(this,k6,this.CONNECTING),m0(this,v9,new AbortController),o1(this,$K)(o1(this,z7),I3(this,B8,Ns).call(this)).then(o1(this,Kq)).catch(o1(this,Vq))},Kq=new WeakMap,Vq=new WeakMap,Ns=function(){var D;let F={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...o1(this,CB)?{"Last-Event-ID":o1(this,CB)}:void 0},cache:"no-store",signal:(D=o1(this,v9))==null?void 0:D.signal};return"window"in globalThis&&(F.credentials=this.withCredentials?"include":"same-origin"),F},Hq=new WeakMap,Gq=new WeakMap,qB=function(D,F){var w;o1(this,k6)!==this.CLOSED&&m0(this,k6,this.CLOSED);let J=new Xq("error",{code:F,message:D});(w=o1(this,_F))==null||w.call(this,J),this.dispatchEvent(J)},uq=function(D,F){var w;if(o1(this,k6)===this.CLOSED)return;m0(this,k6,this.CONNECTING);let J=new Xq("error",{code:F,message:D});(w=o1(this,_F))==null||w.call(this,J),this.dispatchEvent(J),m0(this,dF,setTimeout(o1(this,Nq),o1(this,AB)))},Nq=new WeakMap,I9.CONNECTING=0,I9.OPEN=1,I9.CLOSED=2;function rc1(){let D="document"in globalThis?globalThis.document:void 0;return D&&typeof D=="object"&&"baseURI"in D&&typeof D.baseURI=="string"?D.baseURI:void 0}var m01=z1(dJ(),1);var MK={name:"@director.run/mcp",private:!0,type:"module",version:"0.0.1",exports:{"./*":"./src/*.ts"},scripts:{lint:"biome check .",format:"biome format --write .",clean:"rm -rf node_modules .turbo dist/*",typecheck:"tsc --noEmit",test:"vitest"},devDependencies:{"@types/bun":"latest","type-fest":"^4.40.0",typescript:"^5.8.3",vitest:"^3.1.1"},dependencies:{"@modelcontextprotocol/sdk":"1.11.4",zod:"^3.25.64"}};var Uq=q1("proxy/handlers/promptsHandler");function Us(D,F){let w=new Map;D.setRequestHandler(WZ,async(J)=>{let{name:p}=J.params,B=w.get(p);if(!B)throw new Error(`Unknown prompt: ${p}`);try{return await B.request({method:"prompts/get",params:{name:p,arguments:J.params.arguments||{},_meta:J.params._meta||{progressToken:void 0}}},Gp)}catch(Y){throw Uq.error({error:Y,clientName:B.name,promptName:p,proxyId:D.id},"Error getting prompt from client"),Y}}),D.setRequestHandler(EZ,async(J)=>{let p=[];w.clear();for(let B of F)try{let Y=await B.request({method:"prompts/list",params:{cursor:J.params?.cursor,_meta:J.params?._meta||{progressToken:void 0}}},Hp);if(Y.prompts){let Q=Y.prompts.map((X)=>{return w.set(X.name,B),{...X,description:`[${B.name}] ${X.description||""}`}});p.push(...Q)}}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound){Uq.warn({clientName:B.name,proxyId:D.id},"Target does not support prompts/list");continue}else{Uq.warn({error:Y,clientName:B.name,proxyId:D.id},"Could not fetch prompts from client. Continuing with other clients.");continue}}return{prompts:p,nextCursor:J.params?.cursor}})}var Zs=q1("proxy/handlers/resourceTemplatesHandler");function $s(D,F){D.setRequestHandler(QZ,async(w)=>{let J=[];for(let p of F)try{let B=await p.request({method:"resources/templates/list",params:{cursor:w.params?.cursor,_meta:w.params?._meta||{progressToken:void 0}}},Kp);if(B.resourceTemplates){let Y=B.resourceTemplates.map((Q)=>({...Q,name:`[${p.name}] ${Q.name||""}`,description:Q.description?`[${p.name}] ${Q.description}`:void 0}));J.push(...Y)}}catch(B){if(B instanceof g0&&B.code===B2.MethodNotFound){Zs.warn({clientName:p.name,proxyId:D.id},"Target does not support resources/templates/list");continue}Zs.error({error:B,clientName:p.name,proxyId:D.id},"Error fetching resource templates from client");continue}return{resourceTemplates:J,nextCursor:w.params?.cursor}})}var qK=q1("proxy/handlers/resourcesHandler");function Ms(D,F){let w=new Map;D.setRequestHandler(YZ,async(J)=>{let p=[];w.clear();for(let B of F)try{let Y=await B.request({method:"resources/list",params:{cursor:J.params?.cursor,_meta:J.params?._meta}},Wp);if(Y.resources){let Q=Y.resources.map((X)=>{return w.set(X.uri,B),{...X,name:`[${B.name}] ${X.name||""}`}});p.push(...Q)}}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound)qK.warn({clientName:B.name,proxyId:D.id},"Target does not support resources/list");else qK.warn({error:Y,clientName:B.name,proxyId:D.id},"Could not fetch resources from client. Continuing with other clients.")}return{resources:p,nextCursor:void 0}}),D.setRequestHandler(XZ,async(J)=>{let{uri:p}=J.params,B=w.get(p);if(!B)throw new Error(`Unknown resource: ${p}`);try{return await B.request({method:"resources/read",params:{uri:p,_meta:J.params._meta}},Vp)}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound)qK.warn({clientName:B.name,uri:p,proxyId:D.id},"Target does not support resources/read");throw qK.error({error:Y,clientName:B.name,uri:p,proxyId:D.id},"Error reading resource from client"),Y}})}var Zq=q1("proxy/handlers/toolsHandler");function qs(D,F){let w=new Map;D.setRequestHandler(KZ,async(J)=>{let p=[];w.clear();for(let B of F)try{let Y=await B.request({method:"tools/list",params:{_meta:J.params?._meta}},up);if(Y.tools){let Q=Y.tools.map((X)=>{return w.set(X.name,B),{...X,description:`[${B.name}] ${X.description||""}`}});p.push(...Q)}}catch(Y){Zq.warn({error:Y,clientName:B.name,proxyId:D.id},"Could not fetch tools from client. Continuing with other clients.");continue}return{tools:p}}),D.setRequestHandler(VZ,async(J)=>{let{name:p}=J.params,B=w.get(p);if(!B)throw new Error(`Unknown tool: ${p}`);try{return await B.request({method:"tools/call",params:{name:p,arguments:J.params.arguments||{},_meta:J.params._meta}},hh)}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound)throw Zq.warn({clientName:B.name,toolName:p,proxyId:D.id},"Target does not support tools/call"),Y;throw Zq.error({error:Y,clientName:B.name,toolName:p,proxyId:D.id},"Error calling tool on client"),Y}})}var c11=z1(i11(),1);class VA extends $B{constructor(D,F){var w;super(F);this._clientInfo=D,this._cachedToolOutputValidators=new Map,this._capabilities=(w=F===null||F===void 0?void 0:F.capabilities)!==null&&w!==void 0?w:{},this._ajv=new c11.Ajv({strict:!1,validateFormats:!0})}registerCapabilities(D){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zK(this._capabilities,D)}assertCapability(D,F){var w;if(!((w=this._serverCapabilities)===null||w===void 0?void 0:w[D]))throw new Error(`Server does not support ${D} (required for ${F})`)}async connect(D,F){if(await super.connect(D),D.sessionId!==void 0)return;try{let w=await this.request({method:"initialize",params:{protocolVersion:s5,capabilities:this._capabilities,clientInfo:this._clientInfo}},BZ,F);if(w===void 0)throw new Error(`Server sent invalid initialize result: ${w}`);if(!hE.includes(w.protocolVersion))throw new Error(`Server's protocol version is not supported: ${w.protocolVersion}`);this._serverCapabilities=w.capabilities,this._serverVersion=w.serverInfo,this._instructions=w.instructions,await this.notification({method:"notifications/initialized"})}catch(w){throw this.close(),w}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(D){var F,w,J,p,B;switch(D){case"logging/setLevel":if(!((F=this._serverCapabilities)===null||F===void 0?void 0:F.logging))throw new Error(`Server does not support logging (required for ${D})`);break;case"prompts/get":case"prompts/list":if(!((w=this._serverCapabilities)===null||w===void 0?void 0:w.prompts))throw new Error(`Server does not support prompts (required for ${D})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((J=this._serverCapabilities)===null||J===void 0?void 0:J.resources))throw new Error(`Server does not support resources (required for ${D})`);if(D==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${D})`);break;case"tools/call":case"tools/list":if(!((p=this._serverCapabilities)===null||p===void 0?void 0:p.tools))throw new Error(`Server does not support tools (required for ${D})`);break;case"completion/complete":if(!((B=this._serverCapabilities)===null||B===void 0?void 0:B.completions))throw new Error(`Server does not support completions (required for ${D})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(D){var F;switch(D){case"notifications/roots/list_changed":if(!((F=this._capabilities.roots)===null||F===void 0?void 0:F.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${D})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(D){switch(D){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${D})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${D})`);break;case"ping":break}}async ping(D){return this.request({method:"ping"},R3,D)}async complete(D,F){return this.request({method:"completion/complete",params:D},GZ,F)}async setLoggingLevel(D,F){return this.request({method:"logging/setLevel",params:{level:D}},R3,F)}async getPrompt(D,F){return this.request({method:"prompts/get",params:D},Gp,F)}async listPrompts(D,F){return this.request({method:"prompts/list",params:D},Hp,F)}async listResources(D,F){return this.request({method:"resources/list",params:D},Wp,F)}async listResourceTemplates(D,F){return this.request({method:"resources/templates/list",params:D},Kp,F)}async readResource(D,F){return this.request({method:"resources/read",params:D},Vp,F)}async subscribeResource(D,F){return this.request({method:"resources/subscribe",params:D},R3,F)}async unsubscribeResource(D,F){return this.request({method:"resources/unsubscribe",params:D},R3,F)}async callTool(D,F=DW,w){let J=await this.request({method:"tools/call",params:D},F,w),p=this.getToolOutputValidator(D.name);if(p){if(!J.structuredContent&&!J.isError)throw new g0(B2.InvalidRequest,`Tool ${D.name} has an output schema but did not return structured content`);if(J.structuredContent)try{if(!p(J.structuredContent))throw new g0(B2.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(p.errors)}`)}catch(B){if(B instanceof g0)throw B;throw new g0(B2.InvalidParams,`Failed to validate structured content: ${B instanceof Error?B.message:String(B)}`)}}return J}cacheToolOutputSchemas(D){this._cachedToolOutputValidators.clear();for(let F of D)if(F.outputSchema)try{let w=this._ajv.compile(F.outputSchema);this._cachedToolOutputValidators.set(F.name,w)}catch(w){console.warn(`Failed to compile output schema for tool ${F.name}: ${w}`)}}getToolOutputValidator(D){return this._cachedToolOutputValidators.get(D)}async listTools(D,F){let w=await this.request({method:"tools/list",params:D},up,F);return this.cacheToolOutputSchemas(w.tools),w}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var HA;HA=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((D)=>D.webcrypto);async function yr1(D){return(await HA).getRandomValues(new Uint8Array(D))}async function ir1(D){let w="",J=await yr1(D);for(let p=0;p<D;p++){let B=J[p]%66;w+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[B]}return w}async function cr1(D){return await ir1(D)}async function lr1(D){let F=await(await HA).subtle.digest("SHA-256",new TextEncoder().encode(D));return btoa(String.fromCharCode(...new Uint8Array(F))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function GA(D){if(!D)D=43;if(D<43||D>128)throw`Expected a length between 43 and 128. Received ${D}.`;let F=await cr1(D),w=await lr1(F);return{code_verifier:F,code_challenge:w}}var l11=A.object({issuer:A.string(),authorization_endpoint:A.string(),token_endpoint:A.string(),registration_endpoint:A.string().optional(),scopes_supported:A.array(A.string()).optional(),response_types_supported:A.array(A.string()),response_modes_supported:A.array(A.string()).optional(),grant_types_supported:A.array(A.string()).optional(),token_endpoint_auth_methods_supported:A.array(A.string()).optional(),token_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),service_documentation:A.string().optional(),revocation_endpoint:A.string().optional(),revocation_endpoint_auth_methods_supported:A.array(A.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),introspection_endpoint:A.string().optional(),introspection_endpoint_auth_methods_supported:A.array(A.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),code_challenge_methods_supported:A.array(A.string()).optional()}).passthrough(),uA=A.object({access_token:A.string(),token_type:A.string(),expires_in:A.number().optional(),scope:A.string().optional(),refresh_token:A.string().optional()}).strip(),ZM0=A.object({error:A.string(),error_description:A.string().optional(),error_uri:A.string().optional()}),gr1=A.object({redirect_uris:A.array(A.string()).refine((D)=>D.every((F)=>URL.canParse(F)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:A.string().optional(),grant_types:A.array(A.string()).optional(),response_types:A.array(A.string()).optional(),client_name:A.string().optional(),client_uri:A.string().optional(),logo_uri:A.string().optional(),scope:A.string().optional(),contacts:A.array(A.string()).optional(),tos_uri:A.string().optional(),policy_uri:A.string().optional(),jwks_uri:A.string().optional(),jwks:A.any().optional(),software_id:A.string().optional(),software_version:A.string().optional()}).strip(),ar1=A.object({client_id:A.string(),client_secret:A.string().optional(),client_id_issued_at:A.number().optional(),client_secret_expires_at:A.number().optional()}).strip(),g11=gr1.merge(ar1),$M0=A.object({error:A.string(),error_description:A.string().optional()}).strip(),MM0=A.object({token:A.string(),token_type_hint:A.string().optional()}).strip();class B4 extends Error{constructor(D){super(D!==null&&D!==void 0?D:"Unauthorized")}}async function k9(D,{serverUrl:F,authorizationCode:w,scope:J}){let p=await nr1(F),B=await Promise.resolve(D.clientInformation());if(!B){if(w!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!D.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let W=await rr1(F,{metadata:p,clientMetadata:D.clientMetadata});await D.saveClientInformation(W),B=W}if(w!==void 0){let W=await D.codeVerifier(),K=await sr1(F,{metadata:p,clientInformation:B,authorizationCode:w,codeVerifier:W,redirectUri:D.redirectUrl});return await D.saveTokens(K),"AUTHORIZED"}let Y=await D.tokens();if(Y===null||Y===void 0?void 0:Y.refresh_token)try{let W=await tr1(F,{metadata:p,clientInformation:B,refreshToken:Y.refresh_token});return await D.saveTokens(W),"AUTHORIZED"}catch(W){console.error("Could not refresh OAuth tokens:",W)}let{authorizationUrl:Q,codeVerifier:X}=await or1(F,{metadata:p,clientInformation:B,redirectUrl:D.redirectUrl,scope:J||D.clientMetadata.scope});return await D.saveCodeVerifier(X),await D.redirectToAuthorization(Q),"REDIRECT"}async function nr1(D,F){var w;let J=new URL("/.well-known/oauth-authorization-server",D),p;try{p=await fetch(J,{headers:{"MCP-Protocol-Version":(w=F===null||F===void 0?void 0:F.protocolVersion)!==null&&w!==void 0?w:s5}})}catch(B){if(B instanceof TypeError)p=await fetch(J);else throw B}if(p.status===404)return;if(!p.ok)throw new Error(`HTTP ${p.status} trying to load well-known OAuth metadata`);return l11.parse(await p.json())}async function or1(D,{metadata:F,clientInformation:w,redirectUrl:J,scope:p}){let Q;if(F){if(Q=new URL(F.authorization_endpoint),!F.response_types_supported.includes("code"))throw new Error("Incompatible auth server: does not support response type code");if(!F.code_challenge_methods_supported||!F.code_challenge_methods_supported.includes("S256"))throw new Error("Incompatible auth server: does not support code challenge method S256")}else Q=new URL("/authorize",D);let X=await GA(),W=X.code_verifier,K=X.code_challenge;if(Q.searchParams.set("response_type","code"),Q.searchParams.set("client_id",w.client_id),Q.searchParams.set("code_challenge",K),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",String(J)),p)Q.searchParams.set("scope",p);return{authorizationUrl:Q,codeVerifier:W}}async function sr1(D,{metadata:F,clientInformation:w,authorizationCode:J,codeVerifier:p,redirectUri:B}){let Q;if(F){if(Q=new URL(F.token_endpoint),F.grant_types_supported&&!F.grant_types_supported.includes("authorization_code"))throw new Error("Incompatible auth server: does not support grant type authorization_code")}else Q=new URL("/token",D);let X=new URLSearchParams({grant_type:"authorization_code",client_id:w.client_id,code:J,code_verifier:p,redirect_uri:String(B)});if(w.client_secret)X.set("client_secret",w.client_secret);let W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X});if(!W.ok)throw new Error(`Token exchange failed: HTTP ${W.status}`);return uA.parse(await W.json())}async function tr1(D,{metadata:F,clientInformation:w,refreshToken:J}){let B;if(F){if(B=new URL(F.token_endpoint),F.grant_types_supported&&!F.grant_types_supported.includes("refresh_token"))throw new Error("Incompatible auth server: does not support grant type refresh_token")}else B=new URL("/token",D);let Y=new URLSearchParams({grant_type:"refresh_token",client_id:w.client_id,refresh_token:J});if(w.client_secret)Y.set("client_secret",w.client_secret);let Q=await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});if(!Q.ok)throw new Error(`Token refresh failed: HTTP ${Q.status}`);return uA.parse(await Q.json())}async function rr1(D,{metadata:F,clientMetadata:w}){let J;if(F){if(!F.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");J=new URL(F.registration_endpoint)}else J=new URL("/register",D);let p=await fetch(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!p.ok)throw new Error(`Dynamic client registration failed: HTTP ${p.status}`);return g11.parse(await p.json())}class a11 extends Error{constructor(D,F,w){super(`SSE error: ${F}`);this.code=D,this.event=w}}class NA{constructor(D,F){this._url=D,this._eventSourceInit=F===null||F===void 0?void 0:F.eventSourceInit,this._requestInit=F===null||F===void 0?void 0:F.requestInit,this._authProvider=F===null||F===void 0?void 0:F.authProvider}async _authThenStart(){var D;if(!this._authProvider)throw new B4("No auth provider");let F;try{F=await k9(this._authProvider,{serverUrl:this._url})}catch(w){throw(D=this.onerror)===null||D===void 0||D.call(this,w),w}if(F!=="AUTHORIZED")throw new B4;return await this._startOrAuth()}async _commonHeaders(){let D={};if(this._authProvider){let F=await this._authProvider.tokens();if(F)D.Authorization=`Bearer ${F.access_token}`}return D}_startOrAuth(){return new Promise((D,F)=>{var w;this._eventSource=new I9(this._url.href,(w=this._eventSourceInit)!==null&&w!==void 0?w:{fetch:(J,p)=>this._commonHeaders().then((B)=>fetch(J,{...p,headers:{...B,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{var p;if(J.code===401&&this._authProvider){this._authThenStart().then(D,F);return}let B=new a11(J.code,J.message,J);F(B),(p=this.onerror)===null||p===void 0||p.call(this,B)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{var p;let B=J;try{if(this._endpoint=new URL(B.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Y){F(Y),(p=this.onerror)===null||p===void 0||p.call(this,Y),this.close();return}D()}),this._eventSource.onmessage=(J)=>{var p,B;let Y=J,Q;try{Q=J4.parse(JSON.parse(Y.data))}catch(X){(p=this.onerror)===null||p===void 0||p.call(this,X);return}(B=this.onmessage)===null||B===void 0||B.call(this,Q)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(D){if(!this._authProvider)throw new B4("No auth provider");if(await k9(this._authProvider,{serverUrl:this._url,authorizationCode:D})!=="AUTHORIZED")throw new B4("Failed to authorize")}async close(){var D,F,w;(D=this._abortController)===null||D===void 0||D.abort(),(F=this._eventSource)===null||F===void 0||F.close(),(w=this.onclose)===null||w===void 0||w.call(this)}async send(D){var F,w,J;if(!this._endpoint)throw new Error("Not connected");try{let p=await this._commonHeaders(),B=new Headers({...p,...(F=this._requestInit)===null||F===void 0?void 0:F.headers});B.set("content-type","application/json");let Y={...this._requestInit,method:"POST",headers:B,body:JSON.stringify(D),signal:(w=this._abortController)===null||w===void 0?void 0:w.signal},Q=await fetch(this._endpoint,Y);if(!Q.ok){if(Q.status===401&&this._authProvider){if(await k9(this._authProvider,{serverUrl:this._url})!=="AUTHORIZED")throw new B4;return this.send(D)}let X=await Q.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${Q.status}): ${X}`)}}catch(p){throw(J=this.onerror)===null||J===void 0||J.call(this,p),p}}}var j01=z1(_01(),1);import YV from"node:process";import{PassThrough as Re1}from"node:stream";var Pe1=YV.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function xe1(){let D={};for(let F of Pe1){let w=YV.env[F];if(w===void 0)continue;if(w.startsWith("()"))continue;D[F]=w}return D}class LA{constructor(D){if(this._abortController=new AbortController,this._readBuffer=new Ap,this._stderrStream=null,this._serverParams=D,D.stderr==="pipe"||D.stderr==="overlapped")this._stderrStream=new Re1}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((D,F)=>{var w,J,p,B,Y,Q;if(this._process=j01.default(this._serverParams.command,(w=this._serverParams.args)!==null&&w!==void 0?w:[],{env:(J=this._serverParams.env)!==null&&J!==void 0?J:xe1(),stdio:["pipe","pipe",(p=this._serverParams.stderr)!==null&&p!==void 0?p:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:YV.platform==="win32"&&ve1(),cwd:this._serverParams.cwd}),this._process.on("error",(X)=>{var W,K;if(X.name==="AbortError"){(W=this.onclose)===null||W===void 0||W.call(this);return}F(X),(K=this.onerror)===null||K===void 0||K.call(this,X)}),this._process.on("spawn",()=>{D()}),this._process.on("close",(X)=>{var W;this._process=void 0,(W=this.onclose)===null||W===void 0||W.call(this)}),(B=this._process.stdin)===null||B===void 0||B.on("error",(X)=>{var W;(W=this.onerror)===null||W===void 0||W.call(this,X)}),(Y=this._process.stdout)===null||Y===void 0||Y.on("data",(X)=>{this._readBuffer.append(X),this.processReadBuffer()}),(Q=this._process.stdout)===null||Q===void 0||Q.on("error",(X)=>{var W;(W=this.onerror)===null||W===void 0||W.call(this,X)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){var D,F;if(this._stderrStream)return this._stderrStream;return(F=(D=this._process)===null||D===void 0?void 0:D.stderr)!==null&&F!==void 0?F:null}processReadBuffer(){var D,F;while(!0)try{let w=this._readBuffer.readMessage();if(w===null)break;(D=this.onmessage)===null||D===void 0||D.call(this,w)}catch(w){(F=this.onerror)===null||F===void 0||F.call(this,w)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(D){return new Promise((F)=>{var w;if(!((w=this._process)===null||w===void 0?void 0:w.stdin))throw new Error("Not connected");let J=zW(D);if(this._process.stdin.write(J))F();else this._process.stdin.once("drain",F)})}}function ve1(){return"type"in YV}class TA extends TransformStream{constructor({onError:D,onRetry:F,onComment:w}={}){let J;super({start(p){J=UK({onEvent:(B)=>{p.enqueue(B)},onError(B){D==="terminate"?p.error(B):typeof D=="function"&&D(B)},onRetry:F,onComment:w})},transform(p){J.feed(p)}})}}var Ie1={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class QV extends Error{constructor(D,F){super(`Streamable HTTP error: ${F}`);this.code=D}}class RA{constructor(D,F){var w;this._url=D,this._requestInit=F===null||F===void 0?void 0:F.requestInit,this._authProvider=F===null||F===void 0?void 0:F.authProvider,this._sessionId=F===null||F===void 0?void 0:F.sessionId,this._reconnectionOptions=(w=F===null||F===void 0?void 0:F.reconnectionOptions)!==null&&w!==void 0?w:Ie1}async _authThenStart(){var D;if(!this._authProvider)throw new B4("No auth provider");let F;try{F=await k9(this._authProvider,{serverUrl:this._url})}catch(w){throw(D=this.onerror)===null||D===void 0||D.call(this,w),w}if(F!=="AUTHORIZED")throw new B4;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var D;let F={};if(this._authProvider){let w=await this._authProvider.tokens();if(w)F.Authorization=`Bearer ${w.access_token}`}if(this._sessionId)F["mcp-session-id"]=this._sessionId;return new Headers({...F,...(D=this._requestInit)===null||D===void 0?void 0:D.headers})}async _startOrAuthSse(D){var F,w;let{resumptionToken:J}=D;try{let p=await this._commonHeaders();if(p.set("Accept","text/event-stream"),J)p.set("last-event-id",J);let B=await fetch(this._url,{method:"GET",headers:p,signal:(F=this._abortController)===null||F===void 0?void 0:F.signal});if(!B.ok){if(B.status===401&&this._authProvider)return await this._authThenStart();if(B.status===405)return;throw new QV(B.status,`Failed to open SSE stream: ${B.statusText}`)}this._handleSseStream(B.body,D)}catch(p){throw(w=this.onerror)===null||w===void 0||w.call(this,p),p}}_getNextReconnectionDelay(D){let F=this._reconnectionOptions.initialReconnectionDelay,w=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(F*Math.pow(w,D),J)}_scheduleReconnection(D,F=0){var w;let J=this._reconnectionOptions.maxRetries;if(J>0&&F>=J){(w=this.onerror)===null||w===void 0||w.call(this,new Error(`Maximum reconnection attempts (${J}) exceeded.`));return}let p=this._getNextReconnectionDelay(F);setTimeout(()=>{this._startOrAuthSse(D).catch((B)=>{var Y;(Y=this.onerror)===null||Y===void 0||Y.call(this,new Error(`Failed to reconnect SSE stream: ${B instanceof Error?B.message:String(B)}`)),this._scheduleReconnection(D,F+1)})},p)}_handleSseStream(D,F){if(!D)return;let{onresumptiontoken:w,replayMessageId:J}=F,p;(async()=>{var Y,Q,X,W;try{let K=D.pipeThrough(new TextDecoderStream).pipeThrough(new TA).getReader();while(!0){let{value:H,done:N}=await K.read();if(N)break;if(H.id)p=H.id,w===null||w===void 0||w(H.id);if(!H.event||H.event==="message")try{let u=J4.parse(JSON.parse(H.data));if(J!==void 0&&T3(u))u.id=J;(Y=this.onmessage)===null||Y===void 0||Y.call(this,u)}catch(u){(Q=this.onerror)===null||Q===void 0||Q.call(this,u)}}}catch(K){if((X=this.onerror)===null||X===void 0||X.call(this,new Error(`SSE stream disconnected: ${K}`)),this._abortController&&!this._abortController.signal.aborted){if(p!==void 0)try{this._scheduleReconnection({resumptionToken:p,onresumptiontoken:w,replayMessageId:J},0)}catch(H){(W=this.onerror)===null||W===void 0||W.call(this,new Error(`Failed to reconnect: ${H instanceof Error?H.message:String(H)}`))}}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(D){if(!this._authProvider)throw new B4("No auth provider");if(await k9(this._authProvider,{serverUrl:this._url,authorizationCode:D})!=="AUTHORIZED")throw new B4("Failed to authorize")}async close(){var D,F;(D=this._abortController)===null||D===void 0||D.abort(),(F=this.onclose)===null||F===void 0||F.call(this)}async send(D,F){var w,J,p;try{let{resumptionToken:B,onresumptiontoken:Y}=F||{};if(B){this._startOrAuthSse({resumptionToken:B,replayMessageId:t5(D)?D.id:void 0}).catch((G)=>{var U;return(U=this.onerror)===null||U===void 0?void 0:U.call(this,G)});return}let Q=await this._commonHeaders();Q.set("content-type","application/json"),Q.set("accept","application/json, text/event-stream");let X={...this._requestInit,method:"POST",headers:Q,body:JSON.stringify(D),signal:(w=this._abortController)===null||w===void 0?void 0:w.signal},W=await fetch(this._url,X),K=W.headers.get("mcp-session-id");if(K)this._sessionId=K;if(!W.ok){if(W.status===401&&this._authProvider){if(await k9(this._authProvider,{serverUrl:this._url})!=="AUTHORIZED")throw new B4;return this.send(D)}let G=await W.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${W.status}): ${G}`)}if(W.status===202){if(_h(D))this._startOrAuthSse({resumptionToken:void 0}).catch((G)=>{var U;return(U=this.onerror)===null||U===void 0?void 0:U.call(this,G)});return}let N=(Array.isArray(D)?D:[D]).filter((G)=>("method"in G)&&("id"in G)&&G.id!==void 0).length>0,u=W.headers.get("content-type");if(N)if(u===null||u===void 0?void 0:u.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:Y});else if(u===null||u===void 0?void 0:u.includes("application/json")){let G=await W.json(),U=Array.isArray(G)?G.map((Z)=>J4.parse(Z)):[J4.parse(G)];for(let Z of U)(J=this.onmessage)===null||J===void 0||J.call(this,Z)}else throw new QV(-1,`Unexpected content type: ${u}`)}catch(B){throw(p=this.onerror)===null||p===void 0||p.call(this,B),B}}get sessionId(){return this._sessionId}async terminateSession(){var D,F;if(!this._sessionId)return;try{let w=await this._commonHeaders(),J={...this._requestInit,method:"DELETE",headers:w,signal:(D=this._abortController)===null||D===void 0?void 0:D.signal},p=await fetch(this._url,J);if(!p.ok&&p.status!==405)throw new QV(p.status,`Failed to terminate session: ${p.statusText}`);this._sessionId=void 0}catch(w){throw(F=this.onerror)===null||F===void 0||F.call(this,w),w}}}class aB{constructor(){this._messageQueue=[]}static createLinkedPair(){let D=new aB,F=new aB;return D._otherTransport=F,F._otherTransport=D,[D,F]}async start(){var D;while(this._messageQueue.length>0){let F=this._messageQueue.shift();(D=this.onmessage)===null||D===void 0||D.call(this,F.message,F.extra)}}async close(){var D;let F=this._otherTransport;this._otherTransport=void 0,await(F===null||F===void 0?void 0:F.close()),(D=this.onclose)===null||D===void 0||D.call(this)}async send(D,F){if(!this._otherTransport)throw new Error("Not connected");if(this._otherTransport.onmessage)this._otherTransport.onmessage(D,{authInfo:F===null||F===void 0?void 0:F.authInfo});else this._otherTransport._messageQueue.push({message:D,extra:{authInfo:F===null||F===void 0?void 0:F.authInfo}})}}var Wq0=q1("SimpleClient");class s8 extends VA{name;constructor(D){super({name:D,version:MK.version},{capabilities:{prompts:{},resources:{subscribe:!0},tools:{}}});this.name=D}toPlainObject(){return{name:this.name}}async connectToHTTP(D,F){try{await this.connect(new RA(new URL(D),{requestInit:{headers:F}}))}catch(w){try{await this.connect(new NA(new URL(D),{requestInit:{headers:F}}))}catch(J){throw new O1("CONNECTION_REFUSED",`[${this.name}] failed to connect to ${D}`,{targetName:this.name,url:D,error:J})}}}async connectToStdio(D,F,w){try{await this.connect(new LA({command:D,args:F,env:w}))}catch(J){if(J instanceof Error&&J.code==="ENOENT")throw new O1("CONNECTION_REFUSED",`[${this.name}] command not found: '${D}'. Please make sure it is installed and available in your $PATH.`,{targetName:this.name,command:D,args:F,env:w});else if(J instanceof g0)throw new O1("CONNECTION_REFUSED",`[${this.name}] failed to run '${[D,...F].join(" ")}'. Please check the logs for more details.`,{targetName:this.name,command:D,args:F,env:w});else throw J}}static async createAndConnectToServer(D){let[F,w]=aB.createLinkedPair(),J=new s8("test client");return await Promise.all([J.connect(F),D.connect(w)]),J}static async createAndConnectToHTTP(D){let F=new s8("test streamable client");return await F.connectToHTTP(D),F}static async createAndConnectToStdio(D,F,w){let J=new s8("test client");return await J.connectToStdio(D,F,w),J}}var f01=q1("mcp/proxy-target");class XV extends s8{attributes;status="disconnected";constructor(D){super(D.name.toLocaleLowerCase());this.attributes=D}async smartConnect({throwOnError:D}={throwOnError:!1}){let{name:F,transport:w}=this.attributes;try{if(f01.info({message:`connecting to target ${F}`,transport:w}),w.type==="http")await this.connectToHTTP(w.url,w.headers);else await this.connectToStdio(w.command,w.args??[],{...process.env,...w?.env||{}})}catch(J){if(f01.error({message:`failed to connect to target ${F}`,error:J}),D)throw J}}}global.EventSource=I9;var Se1=q1("ProxyServer");class nF extends Bq{targets;attributes;constructor(D){super({name:D.name,version:MK.version},{capabilities:{prompts:{},resources:{subscribe:!0},tools:{listChanged:!0}}});this.targets=[],this.attributes=D;for(let F of this.attributes.servers){let w=new XV(F);this.targets.push(w)}qs(this,this.targets),Us(this,this.targets),Ms(this,this.targets),$s(this,this.targets)}async connectTargets({throwOnError:D}={throwOnError:!1}){for(let F of this.targets)await F.smartConnect({throwOnError:D})}async addTarget(D,F={throwOnError:!1}){if(this.targets.find((p)=>p.name.toLocaleLowerCase()===D.name.toLocaleLowerCase()))throw new O1("BAD_REQUEST",`Target ${D.name} already exists`);let J=new XV(D);await J.smartConnect({throwOnError:F.throwOnError}),this.attributes.servers.push(D),this.targets.push(J)}async removeTarget(D){let F=this.targets.find((w)=>w.name.toLocaleLowerCase()===D.toLocaleLowerCase());if(!F)throw new O1("BAD_REQUEST",`Target ${D} does not exists`);await F.close(),this.attributes.servers=this.attributes.servers.filter((w)=>w.name.toLocaleLowerCase()!==D.toLocaleLowerCase()),m01.default.remove(this.targets,(w)=>w.name===D)}update(D){let{name:F,description:w}=D;if(F)this.attributes.name=F;if(w&&w!==this.attributes.description)this.attributes.description=w}toPlainObject(){return this.attributes}get id(){return this.attributes.id}async close(){Se1.info({message:"shutting down",proxyId:this.id}),await Promise.all(this.targets.map((D)=>D.close())),await super.close()}}async function _e1(D){let F=new F$;await D.connect(F),process.on("SIGINT",async()=>{await F.close(),await D.close(),process.exit(0)})}async function k01(D){try{let F=new nF({id:"http2stdio",name:"http2stdio",servers:[{name:"director-http",transport:{type:"http",url:D}}]});await F.connectTargets({throwOnError:!0}),await _e1(F)}catch(F){console.error(F),process.exit(1)}}function c6(D,F){return new URL(F,D).toString()}class PA{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(D,F){this.keyToValue.set(D,F),this.valueToKey.set(F,D)}getByKey(D){return this.keyToValue.get(D)}getByValue(D){return this.valueToKey.get(D)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}}class nB{constructor(D){this.generateIdentifier=D,this.kv=new PA}register(D,F){if(this.kv.getByValue(D))return;if(!F)F=this.generateIdentifier(D);this.kv.set(F,D)}clear(){this.kv.clear()}getIdentifier(D){return this.kv.getByValue(D)}getValue(D){return this.kv.getByKey(D)}}class xA extends nB{constructor(){super((D)=>D.name);this.classToAllowedProps=new Map}register(D,F){if(typeof F==="object"){if(F.allowProps)this.classToAllowedProps.set(D,F.allowProps);super.register(D,F.identifier)}else super.register(D,F)}getAllowedProps(D){return this.classToAllowedProps.get(D)}}function je1(D){if("values"in Object)return Object.values(D);let F=[];for(let w in D)if(D.hasOwnProperty(w))F.push(D[w]);return F}function b01(D,F){let w=je1(D);if("find"in w)return w.find(F);let J=w;for(let p=0;p<J.length;p++){let B=J[p];if(F(B))return B}return}function C7(D,F){Object.entries(D).forEach(([w,J])=>F(J,w))}function oF(D,F){return D.indexOf(F)!==-1}function vA(D,F){for(let w=0;w<D.length;w++){let J=D[w];if(F(J))return J}return}class IA{constructor(){this.transfomers={}}register(D){this.transfomers[D.name]=D}findApplicable(D){return b01(this.transfomers,(F)=>F.isApplicable(D))}findByName(D){return this.transfomers[D]}}var fe1=(D)=>Object.prototype.toString.call(D).slice(8,-1),SA=(D)=>typeof D==="undefined",me1=(D)=>D===null,O7=(D)=>{if(typeof D!=="object"||D===null)return!1;if(D===Object.prototype)return!1;if(Object.getPrototypeOf(D)===null)return!0;return Object.getPrototypeOf(D)===Object.prototype},EV=(D)=>O7(D)&&Object.keys(D).length===0,K8=(D)=>Array.isArray(D),ke1=(D)=>typeof D==="string",be1=(D)=>typeof D==="number"&&!isNaN(D),he1=(D)=>typeof D==="boolean",h01=(D)=>D instanceof RegExp,b9=(D)=>D instanceof Map,h9=(D)=>D instanceof Set,dA=(D)=>fe1(D)==="Symbol",y01=(D)=>D instanceof Date&&!isNaN(D.valueOf()),i01=(D)=>D instanceof Error,_A=(D)=>typeof D==="number"&&isNaN(D),c01=(D)=>he1(D)||me1(D)||SA(D)||be1(D)||ke1(D)||dA(D),l01=(D)=>typeof D==="bigint",g01=(D)=>D===1/0||D===-1/0,a01=(D)=>ArrayBuffer.isView(D)&&!(D instanceof DataView),n01=(D)=>D instanceof URL;var jA=(D)=>D.replace(/\./g,"\\."),WV=(D)=>D.map(String).map(jA).join("."),sF=(D)=>{let F=[],w="";for(let p=0;p<D.length;p++){let B=D.charAt(p);if(B==="\\"&&D.charAt(p+1)==="."){w+=".",p++;continue}if(B==="."){F.push(w),w="";continue}w+=B}let J=w;return F.push(J),F};function t8(D,F,w,J){return{isApplicable:D,annotation:F,transform:w,untransform:J}}var o01=[t8(SA,"undefined",()=>null,()=>{return}),t8(l01,"bigint",(D)=>D.toString(),(D)=>{if(typeof BigInt!=="undefined")return BigInt(D);return console.error("Please add a BigInt polyfill."),D}),t8(y01,"Date",(D)=>D.toISOString(),(D)=>new Date(D)),t8(i01,"Error",(D,F)=>{let w={name:D.name,message:D.message};return F.allowedErrorProps.forEach((J)=>{w[J]=D[J]}),w},(D,F)=>{let w=new Error(D.message);return w.name=D.name,w.stack=D.stack,F.allowedErrorProps.forEach((J)=>{w[J]=D[J]}),w}),t8(h01,"regexp",(D)=>""+D,(D)=>{let F=D.slice(1,D.lastIndexOf("/")),w=D.slice(D.lastIndexOf("/")+1);return new RegExp(F,w)}),t8(h9,"set",(D)=>[...D.values()],(D)=>new Set(D)),t8(b9,"map",(D)=>[...D.entries()],(D)=>new Map(D)),t8((D)=>_A(D)||g01(D),"number",(D)=>{if(_A(D))return"NaN";if(D>0)return"Infinity";else return"-Infinity"},Number),t8((D)=>D===0&&1/D===-1/0,"number",()=>{return"-0"},Number),t8(n01,"URL",(D)=>D.toString(),(D)=>new URL(D))];function KV(D,F,w,J){return{isApplicable:D,annotation:F,transform:w,untransform:J}}var s01=KV((D,F)=>{if(dA(D))return!!F.symbolRegistry.getIdentifier(D);return!1},(D,F)=>{return["symbol",F.symbolRegistry.getIdentifier(D)]},(D)=>D.description,(D,F,w)=>{let J=w.symbolRegistry.getValue(F[1]);if(!J)throw new Error("Trying to deserialize unknown symbol");return J}),ye1=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((D,F)=>{return D[F.name]=F,D},{}),t01=KV(a01,(D)=>["typed-array",D.constructor.name],(D)=>[...D],(D,F)=>{let w=ye1[F[1]];if(!w)throw new Error("Trying to deserialize unknown typed array");return new w(D)});function fA(D,F){if(D?.constructor)return!!F.classRegistry.getIdentifier(D.constructor);return!1}var r01=KV(fA,(D,F)=>{return["class",F.classRegistry.getIdentifier(D.constructor)]},(D,F)=>{let w=F.classRegistry.getAllowedProps(D.constructor);if(!w)return{...D};let J={};return w.forEach((p)=>{J[p]=D[p]}),J},(D,F,w)=>{let J=w.classRegistry.getValue(F[1]);if(!J)throw new Error(`Trying to deserialize unknown class '${F[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(J.prototype),D)}),e01=KV((D,F)=>{return!!F.customTransformerRegistry.findApplicable(D)},(D,F)=>{return["custom",F.customTransformerRegistry.findApplicable(D).name]},(D,F)=>{return F.customTransformerRegistry.findApplicable(D).serialize(D)},(D,F,w)=>{let J=w.customTransformerRegistry.findByName(F[1]);if(!J)throw new Error("Trying to deserialize unknown custom value");return J.deserialize(D)}),ie1=[r01,s01,e01,t01],mA=(D,F)=>{let w=vA(ie1,(p)=>p.isApplicable(D,F));if(w)return{value:w.transform(D,F),type:w.annotation(D,F)};let J=vA(o01,(p)=>p.isApplicable(D,F));if(J)return{value:J.transform(D,F),type:J.annotation};return},D21={};o01.forEach((D)=>{D21[D.annotation]=D});var F21=(D,F,w)=>{if(K8(F))switch(F[0]){case"symbol":return s01.untransform(D,F,w);case"class":return r01.untransform(D,F,w);case"custom":return e01.untransform(D,F,w);case"typed-array":return t01.untransform(D,F,w);default:throw new Error("Unknown transformation: "+F)}else{let J=D21[F];if(!J)throw new Error("Unknown transformation: "+F);return J.untransform(D,w)}};var tF=(D,F)=>{if(F>D.size)throw new Error("index out of bounds");let w=D.keys();while(F>0)w.next(),F--;return w.next().value};function w21(D){if(oF(D,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(oF(D,"prototype"))throw new Error("prototype is not allowed as a property");if(oF(D,"constructor"))throw new Error("constructor is not allowed as a property")}var J21=(D,F)=>{w21(F);for(let w=0;w<F.length;w++){let J=F[w];if(h9(D))D=tF(D,+J);else if(b9(D)){let p=+J,B=+F[++w]===0?"key":"value",Y=tF(D,p);switch(B){case"key":D=Y;break;case"value":D=D.get(Y);break}}else D=D[J]}return D},VV=(D,F,w)=>{if(w21(F),F.length===0)return w(D);let J=D;for(let B=0;B<F.length-1;B++){let Y=F[B];if(K8(J)){let Q=+Y;J=J[Q]}else if(O7(J))J=J[Y];else if(h9(J)){let Q=+Y;J=tF(J,Q)}else if(b9(J)){if(B===F.length-2)break;let X=+Y,W=+F[++B]===0?"key":"value",K=tF(J,X);switch(W){case"key":J=K;break;case"value":J=J.get(K);break}}}let p=F[F.length-1];if(K8(J))J[+p]=w(J[+p]);else if(O7(J))J[p]=w(J[p]);if(h9(J)){let B=tF(J,+p),Y=w(B);if(B!==Y)J.delete(B),J.add(Y)}if(b9(J)){let B=+F[F.length-2],Y=tF(J,B);switch(+p===0?"key":"value"){case"key":{let X=w(Y);if(J.set(X,J.get(Y)),X!==Y)J.delete(Y);break}case"value":{J.set(Y,w(J.get(Y)));break}}}return D};function kA(D,F,w=[]){if(!D)return;if(!K8(D)){C7(D,(B,Y)=>kA(B,F,[...w,...sF(Y)]));return}let[J,p]=D;if(p)C7(p,(B,Y)=>{kA(B,F,[...w,...sF(Y)])});F(J,w)}function p21(D,F,w){return kA(F,(J,p)=>{D=VV(D,p,(B)=>F21(B,J,w))}),D}function B21(D,F){function w(J,p){let B=J21(D,sF(p));J.map(sF).forEach((Y)=>{D=VV(D,Y,()=>B)})}if(K8(F)){let[J,p]=F;if(J.forEach((B)=>{D=VV(D,sF(B),()=>D)}),p)C7(p,w)}else C7(F,w);return D}var ce1=(D,F)=>O7(D)||K8(D)||b9(D)||h9(D)||fA(D,F);function le1(D,F,w){let J=w.get(D);if(J)J.push(F);else w.set(D,[F])}function Y21(D,F){let w={},J=void 0;if(D.forEach((p)=>{if(p.length<=1)return;if(!F)p=p.map((Q)=>Q.map(String)).sort((Q,X)=>Q.length-X.length);let[B,...Y]=p;if(B.length===0)J=Y.map(WV);else w[WV(B)]=Y.map(WV)}),J)if(EV(w))return[J];else return[J,w];else return EV(w)?void 0:w}var bA=(D,F,w,J,p=[],B=[],Y=new Map)=>{let Q=c01(D);if(!Q){le1(D,p,F);let u=Y.get(D);if(u)return J?{transformedValue:null}:u}if(!ce1(D,w)){let u=mA(D,w),G=u?{transformedValue:u.value,annotations:[u.type]}:{transformedValue:D};if(!Q)Y.set(D,G);return G}if(oF(B,D))return{transformedValue:null};let X=mA(D,w),W=X?.value??D,K=K8(W)?[]:{},H={};C7(W,(u,G)=>{if(G==="__proto__"||G==="constructor"||G==="prototype")throw new Error(`Detected property ${G}. This is a prototype pollution risk, please remove it from your object.`);let U=bA(u,F,w,J,[...p,G],[...B,D],Y);if(K[G]=U.transformedValue,K8(U.annotations))H[G]=U.annotations;else if(O7(U.annotations))C7(U.annotations,(Z,C)=>{H[jA(G)+"."+C]=Z})});let N=EV(H)?{transformedValue:K,annotations:X?[X.type]:void 0}:{transformedValue:K,annotations:X?[X.type,H]:H};if(!Q)Y.set(D,N);return N};function HV(D){return Object.prototype.toString.call(D).slice(8,-1)}function hA(D){return HV(D)==="Array"}function Q21(D){if(HV(D)!=="Object")return!1;let F=Object.getPrototypeOf(D);return!!F&&F.constructor===Object&&F===Object.prototype}function ge1(D){return HV(D)==="Null"}function ae1(D,F,w,J,p){return(B)=>D(B)||F(B)||!!w&&w(B)||!!J&&J(B)||!!p&&p(B)}function ne1(D){return HV(D)==="Undefined"}var XA0=ae1(ge1,ne1);function oe1(D,F,w,J,p){let B={}.propertyIsEnumerable.call(J,F)?"enumerable":"nonenumerable";if(B==="enumerable")D[F]=w;if(p&&B==="nonenumerable")Object.defineProperty(D,F,{value:w,enumerable:!1,writable:!0,configurable:!0})}function GV(D,F={}){if(hA(D))return D.map((p)=>GV(p,F));if(!Q21(D))return D;let w=Object.getOwnPropertyNames(D),J=Object.getOwnPropertySymbols(D);return[...w,...J].reduce((p,B)=>{if(hA(F.props)&&!F.props.includes(B))return p;let Y=D[B],Q=GV(Y,F);return oe1(p,B,Q,D,F.nonenumerable),p},{})}class f1{constructor({dedupe:D=!1}={}){this.classRegistry=new xA,this.symbolRegistry=new nB((F)=>F.description??""),this.customTransformerRegistry=new IA,this.allowedErrorProps=[],this.dedupe=D}serialize(D){let F=new Map,w=bA(D,F,this,this.dedupe),J={json:w.transformedValue};if(w.annotations)J.meta={...J.meta,values:w.annotations};let p=Y21(F,this.dedupe);if(p)J.meta={...J.meta,referentialEqualities:p};return J}deserialize(D){let{json:F,meta:w}=D,J=GV(F);if(w?.values)J=p21(J,w.values,this);if(w?.referentialEqualities)J=B21(J,w.referentialEqualities);return J}stringify(D){return JSON.stringify(this.serialize(D))}parse(D){return this.deserialize(JSON.parse(D))}registerClass(D,F){this.classRegistry.register(D,F)}registerSymbol(D,F){this.symbolRegistry.register(D,F)}registerCustom(D,F){this.customTransformerRegistry.register({name:F,...D})}allowErrorProps(...D){this.allowedErrorProps.push(...D)}}f1.defaultInstance=new f1;f1.serialize=f1.defaultInstance.serialize.bind(f1.defaultInstance);f1.deserialize=f1.defaultInstance.deserialize.bind(f1.defaultInstance);f1.stringify=f1.defaultInstance.stringify.bind(f1.defaultInstance);f1.parse=f1.defaultInstance.parse.bind(f1.defaultInstance);f1.registerClass=f1.defaultInstance.registerClass.bind(f1.defaultInstance);f1.registerSymbol=f1.defaultInstance.registerSymbol.bind(f1.defaultInstance);f1.registerCustom=f1.defaultInstance.registerCustom.bind(f1.defaultInstance);f1.allowErrorProps=f1.defaultInstance.allowErrorProps.bind(f1.defaultInstance);var{serialize:zA0,deserialize:UA0,stringify:ZA0,parse:$A0,registerClass:MA0,registerCustom:qA0,registerSymbol:AA0,allowErrorProps:CA0}=f1;function X21(D){let F=c6(D,"/trpc");return dE({links:[oD({url:F,transformer:f1,async fetch(w,J){return fetch(w,J).catch((p)=>{if(p.code==="ConnectionRefused")throw new Error(`Could not connect to the gateway service on ${D}. Is it running?`);throw p})}})]})}var uV=q1("trpc"),se1=async({path:D,type:F,next:w,input:J})=>{if(D==="health")return w();let p=Date.now();uV.trace({path:D,type:F,input:J},"trpc request received");try{let B=await w(),Y=Date.now()-p;if(B.ok)uV.trace({path:D,type:F,duration:Y},"trpc request successful");else uV.error({path:D,type:F,duration:Y,error:B.error},"trpc request failed");return B}catch(B){let Y=Date.now()-p;throw uV.error({path:D,type:F,duration:Y,error:B instanceof Error?B.message:"Unknown error"},"trpc request failed"),B}},yA=iU.context().create({transformer:f1,errorFormatter:({shape:D})=>{return{...D,data:{...D.data}}}}),te1=yA.procedure.use(se1),v0={router:yA.router,procedure:te1,middleware:yA.middleware};function E21(D,F){return dE({links:[oD({url:D,transformer:f1,async fetch(w,J){return fetch(w,{...J,headers:{...F?.headers,...J?.headers}}).catch((p)=>{if(p.code==="ConnectionRefused")throw new Error(`Could not connect to the service on ${D}. Is it running?`);throw p})}})]})}function NV(D,F={}){let w=c6(D,"/trpc");return E21(w,F.apiKey?{headers:{"x-api-key":F.apiKey}}:void 0)}var I2=X21(Q0.GATEWAY_URL),T4=NV(Q0.REGISTRY_API_URL,{apiKey:Q0.REGISTRY_API_KEY});var C21=z1(dJ(),1);import AV from"node:process";import z21 from"node:process";import $V from"node:process";var re1=(D,F,w,J)=>{if(w==="length"||w==="prototype")return;if(w==="arguments"||w==="caller")return;let p=Object.getOwnPropertyDescriptor(D,w),B=Object.getOwnPropertyDescriptor(F,w);if(!ee1(p,B)&&J)return;Object.defineProperty(D,w,B)},ee1=function(D,F){return D===void 0||D.configurable||D.writable===F.writable&&D.enumerable===F.enumerable&&D.configurable===F.configurable&&(D.writable||D.value===F.value)},D10=(D,F)=>{let w=Object.getPrototypeOf(F);if(w===Object.getPrototypeOf(D))return;Object.setPrototypeOf(D,w)},F10=(D,F)=>`/* Wrapped ${D}*/
603
+ `&&J++}}return[F,w]}class Xq extends Event{constructor(D,F){var w,J;super(D),this.code=(w=F==null?void 0:F.code)!=null?w:void 0,this.message=(J=F==null?void 0:F.message)!=null?J:void 0}[Symbol.for("nodejs.util.inspect.custom")](D,F,w){return w(us(this),F)}[Symbol.for("Deno.customInspect")](D,F){return D(us(this),F)}}function tc1(D){let F=globalThis.DOMException;return typeof F=="function"?new F(D,"SyntaxError"):new SyntaxError(D)}function Eq(D){return D instanceof Error?"errors"in D&&Array.isArray(D.errors)?D.errors.map(Eq).join(", "):("cause"in D)&&D.cause instanceof Error?`${D}: ${Eq(D.cause)}`:D.message:`${D}`}function us(D){return{type:D.type,message:D.message,code:D.code,defaultPrevented:D.defaultPrevented,cancelable:D.cancelable,timeStamp:D.timeStamp}}var zs=(D)=>{throw TypeError(D)},zq=(D,F,w)=>F.has(D)||zs("Cannot "+w),o1=(D,F,w)=>(zq(D,F,"read from private field"),w?w.call(D):F.get(D)),Z2=(D,F,w)=>F.has(D)?zs("Cannot add the same private member more than once"):F instanceof WeakSet?F.add(D):F.set(D,w),m0=(D,F,w,J)=>(zq(D,F,"write to private field"),F.set(D,w),w),I3=(D,F,w)=>(zq(D,F,"access private method"),w),k6,z7,vF,ZK,$K,AB,dF,CB,v9,IF,_F,SF,MB,B8,Wq,Kq,Vq,Ns,Hq,Gq,qB,uq,Nq;class I9 extends EventTarget{constructor(D,F){var w,J;super(),Z2(this,B8),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Z2(this,k6),Z2(this,z7),Z2(this,vF),Z2(this,ZK),Z2(this,$K),Z2(this,AB),Z2(this,dF),Z2(this,CB,null),Z2(this,v9),Z2(this,IF),Z2(this,_F,null),Z2(this,SF,null),Z2(this,MB,null),Z2(this,Kq,async(p)=>{var B;o1(this,IF).reset();let{body:Y,redirected:Q,status:X,headers:W}=p;if(X===204){I3(this,B8,qB).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(Q?m0(this,vF,new URL(p.url)):m0(this,vF,void 0),X!==200){I3(this,B8,qB).call(this,`Non-200 status code (${X})`,X);return}if(!(W.get("content-type")||"").startsWith("text/event-stream")){I3(this,B8,qB).call(this,'Invalid content type, expected "text/event-stream"',X);return}if(o1(this,k6)===this.CLOSED)return;m0(this,k6,this.OPEN);let K=new Event("open");if((B=o1(this,MB))==null||B.call(this,K),this.dispatchEvent(K),typeof Y!="object"||!Y||!("getReader"in Y)){I3(this,B8,qB).call(this,"Invalid response body, expected a web ReadableStream",X),this.close();return}let H=new TextDecoder,N=Y.getReader(),u=!0;do{let{done:G,value:U}=await N.read();U&&o1(this,IF).feed(H.decode(U,{stream:!G})),G&&(u=!1,o1(this,IF).reset(),I3(this,B8,uq).call(this))}while(u)}),Z2(this,Vq,(p)=>{m0(this,v9,void 0),!(p.name==="AbortError"||p.type==="aborted")&&I3(this,B8,uq).call(this,Eq(p))}),Z2(this,Hq,(p)=>{typeof p.id=="string"&&m0(this,CB,p.id);let B=new MessageEvent(p.event||"message",{data:p.data,origin:o1(this,vF)?o1(this,vF).origin:o1(this,z7).origin,lastEventId:p.id||""});o1(this,SF)&&(!p.event||p.event==="message")&&o1(this,SF).call(this,B),this.dispatchEvent(B)}),Z2(this,Gq,(p)=>{m0(this,AB,p)}),Z2(this,Nq,()=>{m0(this,dF,void 0),o1(this,k6)===this.CONNECTING&&I3(this,B8,Wq).call(this)});try{if(D instanceof URL)m0(this,z7,D);else if(typeof D=="string")m0(this,z7,new URL(D,rc1()));else throw new Error("Invalid URL")}catch{throw tc1("An invalid or illegal string was specified")}m0(this,IF,UK({onEvent:o1(this,Hq),onRetry:o1(this,Gq)})),m0(this,k6,this.CONNECTING),m0(this,AB,3000),m0(this,$K,(w=F==null?void 0:F.fetch)!=null?w:globalThis.fetch),m0(this,ZK,(J=F==null?void 0:F.withCredentials)!=null?J:!1),I3(this,B8,Wq).call(this)}get readyState(){return o1(this,k6)}get url(){return o1(this,z7).href}get withCredentials(){return o1(this,ZK)}get onerror(){return o1(this,_F)}set onerror(D){m0(this,_F,D)}get onmessage(){return o1(this,SF)}set onmessage(D){m0(this,SF,D)}get onopen(){return o1(this,MB)}set onopen(D){m0(this,MB,D)}addEventListener(D,F,w){let J=F;super.addEventListener(D,J,w)}removeEventListener(D,F,w){let J=F;super.removeEventListener(D,J,w)}close(){o1(this,dF)&&clearTimeout(o1(this,dF)),o1(this,k6)!==this.CLOSED&&(o1(this,v9)&&o1(this,v9).abort(),m0(this,k6,this.CLOSED),m0(this,v9,void 0))}}k6=new WeakMap,z7=new WeakMap,vF=new WeakMap,ZK=new WeakMap,$K=new WeakMap,AB=new WeakMap,dF=new WeakMap,CB=new WeakMap,v9=new WeakMap,IF=new WeakMap,_F=new WeakMap,SF=new WeakMap,MB=new WeakMap,B8=new WeakSet,Wq=function(){m0(this,k6,this.CONNECTING),m0(this,v9,new AbortController),o1(this,$K)(o1(this,z7),I3(this,B8,Ns).call(this)).then(o1(this,Kq)).catch(o1(this,Vq))},Kq=new WeakMap,Vq=new WeakMap,Ns=function(){var D;let F={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...o1(this,CB)?{"Last-Event-ID":o1(this,CB)}:void 0},cache:"no-store",signal:(D=o1(this,v9))==null?void 0:D.signal};return"window"in globalThis&&(F.credentials=this.withCredentials?"include":"same-origin"),F},Hq=new WeakMap,Gq=new WeakMap,qB=function(D,F){var w;o1(this,k6)!==this.CLOSED&&m0(this,k6,this.CLOSED);let J=new Xq("error",{code:F,message:D});(w=o1(this,_F))==null||w.call(this,J),this.dispatchEvent(J)},uq=function(D,F){var w;if(o1(this,k6)===this.CLOSED)return;m0(this,k6,this.CONNECTING);let J=new Xq("error",{code:F,message:D});(w=o1(this,_F))==null||w.call(this,J),this.dispatchEvent(J),m0(this,dF,setTimeout(o1(this,Nq),o1(this,AB)))},Nq=new WeakMap,I9.CONNECTING=0,I9.OPEN=1,I9.CLOSED=2;function rc1(){let D="document"in globalThis?globalThis.document:void 0;return D&&typeof D=="object"&&"baseURI"in D&&typeof D.baseURI=="string"?D.baseURI:void 0}var m01=z1(dJ(),1);var MK={name:"@director.run/mcp",private:!0,type:"module",version:"0.0.1",exports:{"./*":"./src/*.ts"},scripts:{lint:"biome check .",format:"biome format --write .",clean:"rm -rf node_modules .turbo dist/*",typecheck:"tsc --noEmit",test:"vitest"},devDependencies:{"@types/bun":"latest","type-fest":"^4.40.0",typescript:"^5.8.3",vitest:"^3.1.1"},dependencies:{"@modelcontextprotocol/sdk":"1.11.4",zod:"^3.25.64"}};var Uq=q1("proxy/handlers/promptsHandler");function Us(D,F){let w=new Map;D.setRequestHandler(WZ,async(J)=>{let{name:p}=J.params,B=w.get(p);if(!B)throw new Error(`Unknown prompt: ${p}`);try{return await B.request({method:"prompts/get",params:{name:p,arguments:J.params.arguments||{},_meta:J.params._meta||{progressToken:void 0}}},Gp)}catch(Y){throw Uq.error({error:Y,clientName:B.name,promptName:p,proxyId:D.id},"Error getting prompt from client"),Y}}),D.setRequestHandler(EZ,async(J)=>{let p=[];w.clear();for(let B of F)try{let Y=await B.request({method:"prompts/list",params:{cursor:J.params?.cursor,_meta:J.params?._meta||{progressToken:void 0}}},Hp);if(Y.prompts){let Q=Y.prompts.map((X)=>{return w.set(X.name,B),{...X,description:`[${B.name}] ${X.description||""}`}});p.push(...Q)}}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound){Uq.warn({clientName:B.name,proxyId:D.id},"Target does not support prompts/list");continue}else{Uq.warn({error:Y,clientName:B.name,proxyId:D.id},"Could not fetch prompts from client. Continuing with other clients.");continue}}return{prompts:p,nextCursor:J.params?.cursor}})}var Zs=q1("proxy/handlers/resourceTemplatesHandler");function $s(D,F){D.setRequestHandler(QZ,async(w)=>{let J=[];for(let p of F)try{let B=await p.request({method:"resources/templates/list",params:{cursor:w.params?.cursor,_meta:w.params?._meta||{progressToken:void 0}}},Kp);if(B.resourceTemplates){let Y=B.resourceTemplates.map((Q)=>({...Q,name:`[${p.name}] ${Q.name||""}`,description:Q.description?`[${p.name}] ${Q.description}`:void 0}));J.push(...Y)}}catch(B){if(B instanceof g0&&B.code===B2.MethodNotFound){Zs.warn({clientName:p.name,proxyId:D.id},"Target does not support resources/templates/list");continue}Zs.error({error:B,clientName:p.name,proxyId:D.id},"Error fetching resource templates from client");continue}return{resourceTemplates:J,nextCursor:w.params?.cursor}})}var qK=q1("proxy/handlers/resourcesHandler");function Ms(D,F){let w=new Map;D.setRequestHandler(YZ,async(J)=>{let p=[];w.clear();for(let B of F)try{let Y=await B.request({method:"resources/list",params:{cursor:J.params?.cursor,_meta:J.params?._meta}},Wp);if(Y.resources){let Q=Y.resources.map((X)=>{return w.set(X.uri,B),{...X,name:`[${B.name}] ${X.name||""}`}});p.push(...Q)}}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound)qK.warn({clientName:B.name,proxyId:D.id},"Target does not support resources/list");else qK.warn({error:Y,clientName:B.name,proxyId:D.id},"Could not fetch resources from client. Continuing with other clients.")}return{resources:p,nextCursor:void 0}}),D.setRequestHandler(XZ,async(J)=>{let{uri:p}=J.params,B=w.get(p);if(!B)throw new Error(`Unknown resource: ${p}`);try{return await B.request({method:"resources/read",params:{uri:p,_meta:J.params._meta}},Vp)}catch(Y){if(Y instanceof g0&&Y.code===B2.MethodNotFound)qK.warn({clientName:B.name,uri:p,proxyId:D.id},"Target does not support resources/read");throw qK.error({error:Y,clientName:B.name,uri:p,proxyId:D.id},"Error reading resource from client"),Y}})}var Zq=q1("proxy/handlers/toolsHandler");function qs(D,F){let w=new Map,J=new Map;D.setRequestHandler(KZ,async(p)=>{let B=[];w.clear(),J.clear();for(let Y of F)try{let Q=await Y.request({method:"tools/list",params:{_meta:p.params?._meta}},up);if(Q.tools){let X=Q.tools.map((W)=>{let K=Y.attributes.add_prefix===!0,H=K?`${Y.name}__${W.name}`:W.name;if(w.set(H,Y),K)J.set(H,W.name);return{...W,name:H,description:`[${Y.name}] ${W.description||""}`}});B.push(...X)}}catch(Q){Zq.warn({error:Q,clientName:Y.name,proxyId:D.id},"Could not fetch tools from client. Continuing with other clients.");continue}return{tools:B}}),D.setRequestHandler(VZ,async(p)=>{let{name:B}=p.params,Y=w.get(B);if(!Y)throw new Error(`Unknown tool: ${B}`);let Q=J.get(B)||B;try{return await Y.request({method:"tools/call",params:{name:Q,arguments:p.params.arguments||{},_meta:p.params._meta}},hh)}catch(X){if(X instanceof g0&&X.code===B2.MethodNotFound)throw Zq.warn({clientName:Y.name,toolName:B,proxyId:D.id},"Target does not support tools/call"),X;throw Zq.error({error:X,clientName:Y.name,toolName:B,proxyId:D.id},"Error calling tool on client"),X}})}var c11=z1(i11(),1);class VA extends $B{constructor(D,F){var w;super(F);this._clientInfo=D,this._cachedToolOutputValidators=new Map,this._capabilities=(w=F===null||F===void 0?void 0:F.capabilities)!==null&&w!==void 0?w:{},this._ajv=new c11.Ajv({strict:!1,validateFormats:!0})}registerCapabilities(D){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zK(this._capabilities,D)}assertCapability(D,F){var w;if(!((w=this._serverCapabilities)===null||w===void 0?void 0:w[D]))throw new Error(`Server does not support ${D} (required for ${F})`)}async connect(D,F){if(await super.connect(D),D.sessionId!==void 0)return;try{let w=await this.request({method:"initialize",params:{protocolVersion:s5,capabilities:this._capabilities,clientInfo:this._clientInfo}},BZ,F);if(w===void 0)throw new Error(`Server sent invalid initialize result: ${w}`);if(!hE.includes(w.protocolVersion))throw new Error(`Server's protocol version is not supported: ${w.protocolVersion}`);this._serverCapabilities=w.capabilities,this._serverVersion=w.serverInfo,this._instructions=w.instructions,await this.notification({method:"notifications/initialized"})}catch(w){throw this.close(),w}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(D){var F,w,J,p,B;switch(D){case"logging/setLevel":if(!((F=this._serverCapabilities)===null||F===void 0?void 0:F.logging))throw new Error(`Server does not support logging (required for ${D})`);break;case"prompts/get":case"prompts/list":if(!((w=this._serverCapabilities)===null||w===void 0?void 0:w.prompts))throw new Error(`Server does not support prompts (required for ${D})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((J=this._serverCapabilities)===null||J===void 0?void 0:J.resources))throw new Error(`Server does not support resources (required for ${D})`);if(D==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${D})`);break;case"tools/call":case"tools/list":if(!((p=this._serverCapabilities)===null||p===void 0?void 0:p.tools))throw new Error(`Server does not support tools (required for ${D})`);break;case"completion/complete":if(!((B=this._serverCapabilities)===null||B===void 0?void 0:B.completions))throw new Error(`Server does not support completions (required for ${D})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(D){var F;switch(D){case"notifications/roots/list_changed":if(!((F=this._capabilities.roots)===null||F===void 0?void 0:F.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${D})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(D){switch(D){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${D})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${D})`);break;case"ping":break}}async ping(D){return this.request({method:"ping"},R3,D)}async complete(D,F){return this.request({method:"completion/complete",params:D},GZ,F)}async setLoggingLevel(D,F){return this.request({method:"logging/setLevel",params:{level:D}},R3,F)}async getPrompt(D,F){return this.request({method:"prompts/get",params:D},Gp,F)}async listPrompts(D,F){return this.request({method:"prompts/list",params:D},Hp,F)}async listResources(D,F){return this.request({method:"resources/list",params:D},Wp,F)}async listResourceTemplates(D,F){return this.request({method:"resources/templates/list",params:D},Kp,F)}async readResource(D,F){return this.request({method:"resources/read",params:D},Vp,F)}async subscribeResource(D,F){return this.request({method:"resources/subscribe",params:D},R3,F)}async unsubscribeResource(D,F){return this.request({method:"resources/unsubscribe",params:D},R3,F)}async callTool(D,F=DW,w){let J=await this.request({method:"tools/call",params:D},F,w),p=this.getToolOutputValidator(D.name);if(p){if(!J.structuredContent&&!J.isError)throw new g0(B2.InvalidRequest,`Tool ${D.name} has an output schema but did not return structured content`);if(J.structuredContent)try{if(!p(J.structuredContent))throw new g0(B2.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(p.errors)}`)}catch(B){if(B instanceof g0)throw B;throw new g0(B2.InvalidParams,`Failed to validate structured content: ${B instanceof Error?B.message:String(B)}`)}}return J}cacheToolOutputSchemas(D){this._cachedToolOutputValidators.clear();for(let F of D)if(F.outputSchema)try{let w=this._ajv.compile(F.outputSchema);this._cachedToolOutputValidators.set(F.name,w)}catch(w){console.warn(`Failed to compile output schema for tool ${F.name}: ${w}`)}}getToolOutputValidator(D){return this._cachedToolOutputValidators.get(D)}async listTools(D,F){let w=await this.request({method:"tools/list",params:D},up,F);return this.cacheToolOutputSchemas(w.tools),w}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var HA;HA=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((D)=>D.webcrypto);async function yr1(D){return(await HA).getRandomValues(new Uint8Array(D))}async function ir1(D){let w="",J=await yr1(D);for(let p=0;p<D;p++){let B=J[p]%66;w+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[B]}return w}async function cr1(D){return await ir1(D)}async function lr1(D){let F=await(await HA).subtle.digest("SHA-256",new TextEncoder().encode(D));return btoa(String.fromCharCode(...new Uint8Array(F))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function GA(D){if(!D)D=43;if(D<43||D>128)throw`Expected a length between 43 and 128. Received ${D}.`;let F=await cr1(D),w=await lr1(F);return{code_verifier:F,code_challenge:w}}var l11=A.object({issuer:A.string(),authorization_endpoint:A.string(),token_endpoint:A.string(),registration_endpoint:A.string().optional(),scopes_supported:A.array(A.string()).optional(),response_types_supported:A.array(A.string()),response_modes_supported:A.array(A.string()).optional(),grant_types_supported:A.array(A.string()).optional(),token_endpoint_auth_methods_supported:A.array(A.string()).optional(),token_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),service_documentation:A.string().optional(),revocation_endpoint:A.string().optional(),revocation_endpoint_auth_methods_supported:A.array(A.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),introspection_endpoint:A.string().optional(),introspection_endpoint_auth_methods_supported:A.array(A.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:A.array(A.string()).optional(),code_challenge_methods_supported:A.array(A.string()).optional()}).passthrough(),uA=A.object({access_token:A.string(),token_type:A.string(),expires_in:A.number().optional(),scope:A.string().optional(),refresh_token:A.string().optional()}).strip(),ZM0=A.object({error:A.string(),error_description:A.string().optional(),error_uri:A.string().optional()}),gr1=A.object({redirect_uris:A.array(A.string()).refine((D)=>D.every((F)=>URL.canParse(F)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:A.string().optional(),grant_types:A.array(A.string()).optional(),response_types:A.array(A.string()).optional(),client_name:A.string().optional(),client_uri:A.string().optional(),logo_uri:A.string().optional(),scope:A.string().optional(),contacts:A.array(A.string()).optional(),tos_uri:A.string().optional(),policy_uri:A.string().optional(),jwks_uri:A.string().optional(),jwks:A.any().optional(),software_id:A.string().optional(),software_version:A.string().optional()}).strip(),ar1=A.object({client_id:A.string(),client_secret:A.string().optional(),client_id_issued_at:A.number().optional(),client_secret_expires_at:A.number().optional()}).strip(),g11=gr1.merge(ar1),$M0=A.object({error:A.string(),error_description:A.string().optional()}).strip(),MM0=A.object({token:A.string(),token_type_hint:A.string().optional()}).strip();class B4 extends Error{constructor(D){super(D!==null&&D!==void 0?D:"Unauthorized")}}async function k9(D,{serverUrl:F,authorizationCode:w,scope:J}){let p=await nr1(F),B=await Promise.resolve(D.clientInformation());if(!B){if(w!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!D.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let W=await rr1(F,{metadata:p,clientMetadata:D.clientMetadata});await D.saveClientInformation(W),B=W}if(w!==void 0){let W=await D.codeVerifier(),K=await sr1(F,{metadata:p,clientInformation:B,authorizationCode:w,codeVerifier:W,redirectUri:D.redirectUrl});return await D.saveTokens(K),"AUTHORIZED"}let Y=await D.tokens();if(Y===null||Y===void 0?void 0:Y.refresh_token)try{let W=await tr1(F,{metadata:p,clientInformation:B,refreshToken:Y.refresh_token});return await D.saveTokens(W),"AUTHORIZED"}catch(W){console.error("Could not refresh OAuth tokens:",W)}let{authorizationUrl:Q,codeVerifier:X}=await or1(F,{metadata:p,clientInformation:B,redirectUrl:D.redirectUrl,scope:J||D.clientMetadata.scope});return await D.saveCodeVerifier(X),await D.redirectToAuthorization(Q),"REDIRECT"}async function nr1(D,F){var w;let J=new URL("/.well-known/oauth-authorization-server",D),p;try{p=await fetch(J,{headers:{"MCP-Protocol-Version":(w=F===null||F===void 0?void 0:F.protocolVersion)!==null&&w!==void 0?w:s5}})}catch(B){if(B instanceof TypeError)p=await fetch(J);else throw B}if(p.status===404)return;if(!p.ok)throw new Error(`HTTP ${p.status} trying to load well-known OAuth metadata`);return l11.parse(await p.json())}async function or1(D,{metadata:F,clientInformation:w,redirectUrl:J,scope:p}){let Q;if(F){if(Q=new URL(F.authorization_endpoint),!F.response_types_supported.includes("code"))throw new Error("Incompatible auth server: does not support response type code");if(!F.code_challenge_methods_supported||!F.code_challenge_methods_supported.includes("S256"))throw new Error("Incompatible auth server: does not support code challenge method S256")}else Q=new URL("/authorize",D);let X=await GA(),W=X.code_verifier,K=X.code_challenge;if(Q.searchParams.set("response_type","code"),Q.searchParams.set("client_id",w.client_id),Q.searchParams.set("code_challenge",K),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",String(J)),p)Q.searchParams.set("scope",p);return{authorizationUrl:Q,codeVerifier:W}}async function sr1(D,{metadata:F,clientInformation:w,authorizationCode:J,codeVerifier:p,redirectUri:B}){let Q;if(F){if(Q=new URL(F.token_endpoint),F.grant_types_supported&&!F.grant_types_supported.includes("authorization_code"))throw new Error("Incompatible auth server: does not support grant type authorization_code")}else Q=new URL("/token",D);let X=new URLSearchParams({grant_type:"authorization_code",client_id:w.client_id,code:J,code_verifier:p,redirect_uri:String(B)});if(w.client_secret)X.set("client_secret",w.client_secret);let W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X});if(!W.ok)throw new Error(`Token exchange failed: HTTP ${W.status}`);return uA.parse(await W.json())}async function tr1(D,{metadata:F,clientInformation:w,refreshToken:J}){let B;if(F){if(B=new URL(F.token_endpoint),F.grant_types_supported&&!F.grant_types_supported.includes("refresh_token"))throw new Error("Incompatible auth server: does not support grant type refresh_token")}else B=new URL("/token",D);let Y=new URLSearchParams({grant_type:"refresh_token",client_id:w.client_id,refresh_token:J});if(w.client_secret)Y.set("client_secret",w.client_secret);let Q=await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});if(!Q.ok)throw new Error(`Token refresh failed: HTTP ${Q.status}`);return uA.parse(await Q.json())}async function rr1(D,{metadata:F,clientMetadata:w}){let J;if(F){if(!F.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");J=new URL(F.registration_endpoint)}else J=new URL("/register",D);let p=await fetch(J,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!p.ok)throw new Error(`Dynamic client registration failed: HTTP ${p.status}`);return g11.parse(await p.json())}class a11 extends Error{constructor(D,F,w){super(`SSE error: ${F}`);this.code=D,this.event=w}}class NA{constructor(D,F){this._url=D,this._eventSourceInit=F===null||F===void 0?void 0:F.eventSourceInit,this._requestInit=F===null||F===void 0?void 0:F.requestInit,this._authProvider=F===null||F===void 0?void 0:F.authProvider}async _authThenStart(){var D;if(!this._authProvider)throw new B4("No auth provider");let F;try{F=await k9(this._authProvider,{serverUrl:this._url})}catch(w){throw(D=this.onerror)===null||D===void 0||D.call(this,w),w}if(F!=="AUTHORIZED")throw new B4;return await this._startOrAuth()}async _commonHeaders(){let D={};if(this._authProvider){let F=await this._authProvider.tokens();if(F)D.Authorization=`Bearer ${F.access_token}`}return D}_startOrAuth(){return new Promise((D,F)=>{var w;this._eventSource=new I9(this._url.href,(w=this._eventSourceInit)!==null&&w!==void 0?w:{fetch:(J,p)=>this._commonHeaders().then((B)=>fetch(J,{...p,headers:{...B,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=(J)=>{var p;if(J.code===401&&this._authProvider){this._authThenStart().then(D,F);return}let B=new a11(J.code,J.message,J);F(B),(p=this.onerror)===null||p===void 0||p.call(this,B)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(J)=>{var p;let B=J;try{if(this._endpoint=new URL(B.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(Y){F(Y),(p=this.onerror)===null||p===void 0||p.call(this,Y),this.close();return}D()}),this._eventSource.onmessage=(J)=>{var p,B;let Y=J,Q;try{Q=J4.parse(JSON.parse(Y.data))}catch(X){(p=this.onerror)===null||p===void 0||p.call(this,X);return}(B=this.onmessage)===null||B===void 0||B.call(this,Q)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(D){if(!this._authProvider)throw new B4("No auth provider");if(await k9(this._authProvider,{serverUrl:this._url,authorizationCode:D})!=="AUTHORIZED")throw new B4("Failed to authorize")}async close(){var D,F,w;(D=this._abortController)===null||D===void 0||D.abort(),(F=this._eventSource)===null||F===void 0||F.close(),(w=this.onclose)===null||w===void 0||w.call(this)}async send(D){var F,w,J;if(!this._endpoint)throw new Error("Not connected");try{let p=await this._commonHeaders(),B=new Headers({...p,...(F=this._requestInit)===null||F===void 0?void 0:F.headers});B.set("content-type","application/json");let Y={...this._requestInit,method:"POST",headers:B,body:JSON.stringify(D),signal:(w=this._abortController)===null||w===void 0?void 0:w.signal},Q=await fetch(this._endpoint,Y);if(!Q.ok){if(Q.status===401&&this._authProvider){if(await k9(this._authProvider,{serverUrl:this._url})!=="AUTHORIZED")throw new B4;return this.send(D)}let X=await Q.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${Q.status}): ${X}`)}}catch(p){throw(J=this.onerror)===null||J===void 0||J.call(this,p),p}}}var j01=z1(_01(),1);import YV from"node:process";import{PassThrough as Re1}from"node:stream";var Pe1=YV.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function xe1(){let D={};for(let F of Pe1){let w=YV.env[F];if(w===void 0)continue;if(w.startsWith("()"))continue;D[F]=w}return D}class LA{constructor(D){if(this._abortController=new AbortController,this._readBuffer=new Ap,this._stderrStream=null,this._serverParams=D,D.stderr==="pipe"||D.stderr==="overlapped")this._stderrStream=new Re1}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((D,F)=>{var w,J,p,B,Y,Q;if(this._process=j01.default(this._serverParams.command,(w=this._serverParams.args)!==null&&w!==void 0?w:[],{env:(J=this._serverParams.env)!==null&&J!==void 0?J:xe1(),stdio:["pipe","pipe",(p=this._serverParams.stderr)!==null&&p!==void 0?p:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:YV.platform==="win32"&&ve1(),cwd:this._serverParams.cwd}),this._process.on("error",(X)=>{var W,K;if(X.name==="AbortError"){(W=this.onclose)===null||W===void 0||W.call(this);return}F(X),(K=this.onerror)===null||K===void 0||K.call(this,X)}),this._process.on("spawn",()=>{D()}),this._process.on("close",(X)=>{var W;this._process=void 0,(W=this.onclose)===null||W===void 0||W.call(this)}),(B=this._process.stdin)===null||B===void 0||B.on("error",(X)=>{var W;(W=this.onerror)===null||W===void 0||W.call(this,X)}),(Y=this._process.stdout)===null||Y===void 0||Y.on("data",(X)=>{this._readBuffer.append(X),this.processReadBuffer()}),(Q=this._process.stdout)===null||Q===void 0||Q.on("error",(X)=>{var W;(W=this.onerror)===null||W===void 0||W.call(this,X)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){var D,F;if(this._stderrStream)return this._stderrStream;return(F=(D=this._process)===null||D===void 0?void 0:D.stderr)!==null&&F!==void 0?F:null}processReadBuffer(){var D,F;while(!0)try{let w=this._readBuffer.readMessage();if(w===null)break;(D=this.onmessage)===null||D===void 0||D.call(this,w)}catch(w){(F=this.onerror)===null||F===void 0||F.call(this,w)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(D){return new Promise((F)=>{var w;if(!((w=this._process)===null||w===void 0?void 0:w.stdin))throw new Error("Not connected");let J=zW(D);if(this._process.stdin.write(J))F();else this._process.stdin.once("drain",F)})}}function ve1(){return"type"in YV}class TA extends TransformStream{constructor({onError:D,onRetry:F,onComment:w}={}){let J;super({start(p){J=UK({onEvent:(B)=>{p.enqueue(B)},onError(B){D==="terminate"?p.error(B):typeof D=="function"&&D(B)},onRetry:F,onComment:w})},transform(p){J.feed(p)}})}}var Ie1={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class QV extends Error{constructor(D,F){super(`Streamable HTTP error: ${F}`);this.code=D}}class RA{constructor(D,F){var w;this._url=D,this._requestInit=F===null||F===void 0?void 0:F.requestInit,this._authProvider=F===null||F===void 0?void 0:F.authProvider,this._sessionId=F===null||F===void 0?void 0:F.sessionId,this._reconnectionOptions=(w=F===null||F===void 0?void 0:F.reconnectionOptions)!==null&&w!==void 0?w:Ie1}async _authThenStart(){var D;if(!this._authProvider)throw new B4("No auth provider");let F;try{F=await k9(this._authProvider,{serverUrl:this._url})}catch(w){throw(D=this.onerror)===null||D===void 0||D.call(this,w),w}if(F!=="AUTHORIZED")throw new B4;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var D;let F={};if(this._authProvider){let w=await this._authProvider.tokens();if(w)F.Authorization=`Bearer ${w.access_token}`}if(this._sessionId)F["mcp-session-id"]=this._sessionId;return new Headers({...F,...(D=this._requestInit)===null||D===void 0?void 0:D.headers})}async _startOrAuthSse(D){var F,w;let{resumptionToken:J}=D;try{let p=await this._commonHeaders();if(p.set("Accept","text/event-stream"),J)p.set("last-event-id",J);let B=await fetch(this._url,{method:"GET",headers:p,signal:(F=this._abortController)===null||F===void 0?void 0:F.signal});if(!B.ok){if(B.status===401&&this._authProvider)return await this._authThenStart();if(B.status===405)return;throw new QV(B.status,`Failed to open SSE stream: ${B.statusText}`)}this._handleSseStream(B.body,D)}catch(p){throw(w=this.onerror)===null||w===void 0||w.call(this,p),p}}_getNextReconnectionDelay(D){let F=this._reconnectionOptions.initialReconnectionDelay,w=this._reconnectionOptions.reconnectionDelayGrowFactor,J=this._reconnectionOptions.maxReconnectionDelay;return Math.min(F*Math.pow(w,D),J)}_scheduleReconnection(D,F=0){var w;let J=this._reconnectionOptions.maxRetries;if(J>0&&F>=J){(w=this.onerror)===null||w===void 0||w.call(this,new Error(`Maximum reconnection attempts (${J}) exceeded.`));return}let p=this._getNextReconnectionDelay(F);setTimeout(()=>{this._startOrAuthSse(D).catch((B)=>{var Y;(Y=this.onerror)===null||Y===void 0||Y.call(this,new Error(`Failed to reconnect SSE stream: ${B instanceof Error?B.message:String(B)}`)),this._scheduleReconnection(D,F+1)})},p)}_handleSseStream(D,F){if(!D)return;let{onresumptiontoken:w,replayMessageId:J}=F,p;(async()=>{var Y,Q,X,W;try{let K=D.pipeThrough(new TextDecoderStream).pipeThrough(new TA).getReader();while(!0){let{value:H,done:N}=await K.read();if(N)break;if(H.id)p=H.id,w===null||w===void 0||w(H.id);if(!H.event||H.event==="message")try{let u=J4.parse(JSON.parse(H.data));if(J!==void 0&&T3(u))u.id=J;(Y=this.onmessage)===null||Y===void 0||Y.call(this,u)}catch(u){(Q=this.onerror)===null||Q===void 0||Q.call(this,u)}}}catch(K){if((X=this.onerror)===null||X===void 0||X.call(this,new Error(`SSE stream disconnected: ${K}`)),this._abortController&&!this._abortController.signal.aborted){if(p!==void 0)try{this._scheduleReconnection({resumptionToken:p,onresumptiontoken:w,replayMessageId:J},0)}catch(H){(W=this.onerror)===null||W===void 0||W.call(this,new Error(`Failed to reconnect: ${H instanceof Error?H.message:String(H)}`))}}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(D){if(!this._authProvider)throw new B4("No auth provider");if(await k9(this._authProvider,{serverUrl:this._url,authorizationCode:D})!=="AUTHORIZED")throw new B4("Failed to authorize")}async close(){var D,F;(D=this._abortController)===null||D===void 0||D.abort(),(F=this.onclose)===null||F===void 0||F.call(this)}async send(D,F){var w,J,p;try{let{resumptionToken:B,onresumptiontoken:Y}=F||{};if(B){this._startOrAuthSse({resumptionToken:B,replayMessageId:t5(D)?D.id:void 0}).catch((G)=>{var U;return(U=this.onerror)===null||U===void 0?void 0:U.call(this,G)});return}let Q=await this._commonHeaders();Q.set("content-type","application/json"),Q.set("accept","application/json, text/event-stream");let X={...this._requestInit,method:"POST",headers:Q,body:JSON.stringify(D),signal:(w=this._abortController)===null||w===void 0?void 0:w.signal},W=await fetch(this._url,X),K=W.headers.get("mcp-session-id");if(K)this._sessionId=K;if(!W.ok){if(W.status===401&&this._authProvider){if(await k9(this._authProvider,{serverUrl:this._url})!=="AUTHORIZED")throw new B4;return this.send(D)}let G=await W.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${W.status}): ${G}`)}if(W.status===202){if(_h(D))this._startOrAuthSse({resumptionToken:void 0}).catch((G)=>{var U;return(U=this.onerror)===null||U===void 0?void 0:U.call(this,G)});return}let N=(Array.isArray(D)?D:[D]).filter((G)=>("method"in G)&&("id"in G)&&G.id!==void 0).length>0,u=W.headers.get("content-type");if(N)if(u===null||u===void 0?void 0:u.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:Y});else if(u===null||u===void 0?void 0:u.includes("application/json")){let G=await W.json(),U=Array.isArray(G)?G.map((Z)=>J4.parse(Z)):[J4.parse(G)];for(let Z of U)(J=this.onmessage)===null||J===void 0||J.call(this,Z)}else throw new QV(-1,`Unexpected content type: ${u}`)}catch(B){throw(p=this.onerror)===null||p===void 0||p.call(this,B),B}}get sessionId(){return this._sessionId}async terminateSession(){var D,F;if(!this._sessionId)return;try{let w=await this._commonHeaders(),J={...this._requestInit,method:"DELETE",headers:w,signal:(D=this._abortController)===null||D===void 0?void 0:D.signal},p=await fetch(this._url,J);if(!p.ok&&p.status!==405)throw new QV(p.status,`Failed to terminate session: ${p.statusText}`);this._sessionId=void 0}catch(w){throw(F=this.onerror)===null||F===void 0||F.call(this,w),w}}}class aB{constructor(){this._messageQueue=[]}static createLinkedPair(){let D=new aB,F=new aB;return D._otherTransport=F,F._otherTransport=D,[D,F]}async start(){var D;while(this._messageQueue.length>0){let F=this._messageQueue.shift();(D=this.onmessage)===null||D===void 0||D.call(this,F.message,F.extra)}}async close(){var D;let F=this._otherTransport;this._otherTransport=void 0,await(F===null||F===void 0?void 0:F.close()),(D=this.onclose)===null||D===void 0||D.call(this)}async send(D,F){if(!this._otherTransport)throw new Error("Not connected");if(this._otherTransport.onmessage)this._otherTransport.onmessage(D,{authInfo:F===null||F===void 0?void 0:F.authInfo});else this._otherTransport._messageQueue.push({message:D,extra:{authInfo:F===null||F===void 0?void 0:F.authInfo}})}}var Wq0=q1("SimpleClient");class s8 extends VA{name;constructor(D){super({name:D,version:MK.version},{capabilities:{prompts:{},resources:{subscribe:!0},tools:{}}});this.name=D}toPlainObject(){return{name:this.name}}async connectToHTTP(D,F){try{await this.connect(new RA(new URL(D),{requestInit:{headers:F}}))}catch(w){try{await this.connect(new NA(new URL(D),{requestInit:{headers:F}}))}catch(J){throw new O1("CONNECTION_REFUSED",`[${this.name}] failed to connect to ${D}`,{targetName:this.name,url:D,error:J})}}}async connectToStdio(D,F,w){try{await this.connect(new LA({command:D,args:F,env:w}))}catch(J){if(J instanceof Error&&J.code==="ENOENT")throw new O1("CONNECTION_REFUSED",`[${this.name}] command not found: '${D}'. Please make sure it is installed and available in your $PATH.`,{targetName:this.name,command:D,args:F,env:w});else if(J instanceof g0)throw new O1("CONNECTION_REFUSED",`[${this.name}] failed to run '${[D,...F].join(" ")}'. Please check the logs for more details.`,{targetName:this.name,command:D,args:F,env:w});else throw J}}static async createAndConnectToServer(D){let[F,w]=aB.createLinkedPair(),J=new s8("test client");return await Promise.all([J.connect(F),D.connect(w)]),J}static async createAndConnectToHTTP(D){let F=new s8("test streamable client");return await F.connectToHTTP(D),F}static async createAndConnectToStdio(D,F,w){let J=new s8("test client");return await J.connectToStdio(D,F,w),J}}var f01=q1("mcp/proxy-target");class XV extends s8{attributes;status="disconnected";constructor(D){super(D.name.toLocaleLowerCase());this.attributes=D}async smartConnect({throwOnError:D}={throwOnError:!1}){let{name:F,transport:w}=this.attributes;try{if(f01.info({message:`connecting to target ${F}`,transport:w}),w.type==="http")await this.connectToHTTP(w.url,w.headers);else await this.connectToStdio(w.command,w.args??[],{...process.env,...w?.env||{}})}catch(J){if(f01.error({message:`failed to connect to target ${F}`,error:J}),D)throw J}}}global.EventSource=I9;var Se1=q1("ProxyServer");class nF extends Bq{targets;attributes;constructor(D){super({name:D.name,version:MK.version},{capabilities:{prompts:{},resources:{subscribe:!0},tools:{listChanged:!0}}});this.targets=[],this.attributes=D;for(let F of this.attributes.servers){let w=new XV(F);this.targets.push(w)}qs(this,this.targets),Us(this,this.targets),Ms(this,this.targets),$s(this,this.targets)}async connectTargets({throwOnError:D}={throwOnError:!1}){for(let F of this.targets)await F.smartConnect({throwOnError:D})}async addTarget(D,F={throwOnError:!1}){if(this.targets.find((p)=>p.name.toLocaleLowerCase()===D.name.toLocaleLowerCase()))throw new O1("BAD_REQUEST",`Target ${D.name} already exists`);let J=new XV(D);await J.smartConnect({throwOnError:F.throwOnError}),this.attributes.servers.push(D),this.targets.push(J)}async removeTarget(D){let F=this.targets.find((w)=>w.name.toLocaleLowerCase()===D.toLocaleLowerCase());if(!F)throw new O1("BAD_REQUEST",`Target ${D} does not exists`);await F.close(),this.attributes.servers=this.attributes.servers.filter((w)=>w.name.toLocaleLowerCase()!==D.toLocaleLowerCase()),m01.default.remove(this.targets,(w)=>w.name===D)}update(D){let{name:F,description:w}=D;if(F)this.attributes.name=F;if(w&&w!==this.attributes.description)this.attributes.description=w}toPlainObject(){return this.attributes}get id(){return this.attributes.id}async close(){Se1.info({message:"shutting down",proxyId:this.id}),await Promise.all(this.targets.map((D)=>D.close())),await super.close()}}async function _e1(D){let F=new F$;await D.connect(F),process.on("SIGINT",async()=>{await F.close(),await D.close(),process.exit(0)})}async function k01(D){try{let F=new nF({id:"http2stdio",name:"http2stdio",servers:[{name:"director-http",transport:{type:"http",url:D}}]});await F.connectTargets({throwOnError:!0}),await _e1(F)}catch(F){console.error(F),process.exit(1)}}function c6(D,F){return new URL(F,D).toString()}class PA{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(D,F){this.keyToValue.set(D,F),this.valueToKey.set(F,D)}getByKey(D){return this.keyToValue.get(D)}getByValue(D){return this.valueToKey.get(D)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}}class nB{constructor(D){this.generateIdentifier=D,this.kv=new PA}register(D,F){if(this.kv.getByValue(D))return;if(!F)F=this.generateIdentifier(D);this.kv.set(F,D)}clear(){this.kv.clear()}getIdentifier(D){return this.kv.getByValue(D)}getValue(D){return this.kv.getByKey(D)}}class xA extends nB{constructor(){super((D)=>D.name);this.classToAllowedProps=new Map}register(D,F){if(typeof F==="object"){if(F.allowProps)this.classToAllowedProps.set(D,F.allowProps);super.register(D,F.identifier)}else super.register(D,F)}getAllowedProps(D){return this.classToAllowedProps.get(D)}}function je1(D){if("values"in Object)return Object.values(D);let F=[];for(let w in D)if(D.hasOwnProperty(w))F.push(D[w]);return F}function b01(D,F){let w=je1(D);if("find"in w)return w.find(F);let J=w;for(let p=0;p<J.length;p++){let B=J[p];if(F(B))return B}return}function C7(D,F){Object.entries(D).forEach(([w,J])=>F(J,w))}function oF(D,F){return D.indexOf(F)!==-1}function vA(D,F){for(let w=0;w<D.length;w++){let J=D[w];if(F(J))return J}return}class IA{constructor(){this.transfomers={}}register(D){this.transfomers[D.name]=D}findApplicable(D){return b01(this.transfomers,(F)=>F.isApplicable(D))}findByName(D){return this.transfomers[D]}}var fe1=(D)=>Object.prototype.toString.call(D).slice(8,-1),SA=(D)=>typeof D==="undefined",me1=(D)=>D===null,O7=(D)=>{if(typeof D!=="object"||D===null)return!1;if(D===Object.prototype)return!1;if(Object.getPrototypeOf(D)===null)return!0;return Object.getPrototypeOf(D)===Object.prototype},EV=(D)=>O7(D)&&Object.keys(D).length===0,K8=(D)=>Array.isArray(D),ke1=(D)=>typeof D==="string",be1=(D)=>typeof D==="number"&&!isNaN(D),he1=(D)=>typeof D==="boolean",h01=(D)=>D instanceof RegExp,b9=(D)=>D instanceof Map,h9=(D)=>D instanceof Set,dA=(D)=>fe1(D)==="Symbol",y01=(D)=>D instanceof Date&&!isNaN(D.valueOf()),i01=(D)=>D instanceof Error,_A=(D)=>typeof D==="number"&&isNaN(D),c01=(D)=>he1(D)||me1(D)||SA(D)||be1(D)||ke1(D)||dA(D),l01=(D)=>typeof D==="bigint",g01=(D)=>D===1/0||D===-1/0,a01=(D)=>ArrayBuffer.isView(D)&&!(D instanceof DataView),n01=(D)=>D instanceof URL;var jA=(D)=>D.replace(/\./g,"\\."),WV=(D)=>D.map(String).map(jA).join("."),sF=(D)=>{let F=[],w="";for(let p=0;p<D.length;p++){let B=D.charAt(p);if(B==="\\"&&D.charAt(p+1)==="."){w+=".",p++;continue}if(B==="."){F.push(w),w="";continue}w+=B}let J=w;return F.push(J),F};function t8(D,F,w,J){return{isApplicable:D,annotation:F,transform:w,untransform:J}}var o01=[t8(SA,"undefined",()=>null,()=>{return}),t8(l01,"bigint",(D)=>D.toString(),(D)=>{if(typeof BigInt!=="undefined")return BigInt(D);return console.error("Please add a BigInt polyfill."),D}),t8(y01,"Date",(D)=>D.toISOString(),(D)=>new Date(D)),t8(i01,"Error",(D,F)=>{let w={name:D.name,message:D.message};return F.allowedErrorProps.forEach((J)=>{w[J]=D[J]}),w},(D,F)=>{let w=new Error(D.message);return w.name=D.name,w.stack=D.stack,F.allowedErrorProps.forEach((J)=>{w[J]=D[J]}),w}),t8(h01,"regexp",(D)=>""+D,(D)=>{let F=D.slice(1,D.lastIndexOf("/")),w=D.slice(D.lastIndexOf("/")+1);return new RegExp(F,w)}),t8(h9,"set",(D)=>[...D.values()],(D)=>new Set(D)),t8(b9,"map",(D)=>[...D.entries()],(D)=>new Map(D)),t8((D)=>_A(D)||g01(D),"number",(D)=>{if(_A(D))return"NaN";if(D>0)return"Infinity";else return"-Infinity"},Number),t8((D)=>D===0&&1/D===-1/0,"number",()=>{return"-0"},Number),t8(n01,"URL",(D)=>D.toString(),(D)=>new URL(D))];function KV(D,F,w,J){return{isApplicable:D,annotation:F,transform:w,untransform:J}}var s01=KV((D,F)=>{if(dA(D))return!!F.symbolRegistry.getIdentifier(D);return!1},(D,F)=>{return["symbol",F.symbolRegistry.getIdentifier(D)]},(D)=>D.description,(D,F,w)=>{let J=w.symbolRegistry.getValue(F[1]);if(!J)throw new Error("Trying to deserialize unknown symbol");return J}),ye1=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((D,F)=>{return D[F.name]=F,D},{}),t01=KV(a01,(D)=>["typed-array",D.constructor.name],(D)=>[...D],(D,F)=>{let w=ye1[F[1]];if(!w)throw new Error("Trying to deserialize unknown typed array");return new w(D)});function fA(D,F){if(D?.constructor)return!!F.classRegistry.getIdentifier(D.constructor);return!1}var r01=KV(fA,(D,F)=>{return["class",F.classRegistry.getIdentifier(D.constructor)]},(D,F)=>{let w=F.classRegistry.getAllowedProps(D.constructor);if(!w)return{...D};let J={};return w.forEach((p)=>{J[p]=D[p]}),J},(D,F,w)=>{let J=w.classRegistry.getValue(F[1]);if(!J)throw new Error(`Trying to deserialize unknown class '${F[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(J.prototype),D)}),e01=KV((D,F)=>{return!!F.customTransformerRegistry.findApplicable(D)},(D,F)=>{return["custom",F.customTransformerRegistry.findApplicable(D).name]},(D,F)=>{return F.customTransformerRegistry.findApplicable(D).serialize(D)},(D,F,w)=>{let J=w.customTransformerRegistry.findByName(F[1]);if(!J)throw new Error("Trying to deserialize unknown custom value");return J.deserialize(D)}),ie1=[r01,s01,e01,t01],mA=(D,F)=>{let w=vA(ie1,(p)=>p.isApplicable(D,F));if(w)return{value:w.transform(D,F),type:w.annotation(D,F)};let J=vA(o01,(p)=>p.isApplicable(D,F));if(J)return{value:J.transform(D,F),type:J.annotation};return},D21={};o01.forEach((D)=>{D21[D.annotation]=D});var F21=(D,F,w)=>{if(K8(F))switch(F[0]){case"symbol":return s01.untransform(D,F,w);case"class":return r01.untransform(D,F,w);case"custom":return e01.untransform(D,F,w);case"typed-array":return t01.untransform(D,F,w);default:throw new Error("Unknown transformation: "+F)}else{let J=D21[F];if(!J)throw new Error("Unknown transformation: "+F);return J.untransform(D,w)}};var tF=(D,F)=>{if(F>D.size)throw new Error("index out of bounds");let w=D.keys();while(F>0)w.next(),F--;return w.next().value};function w21(D){if(oF(D,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(oF(D,"prototype"))throw new Error("prototype is not allowed as a property");if(oF(D,"constructor"))throw new Error("constructor is not allowed as a property")}var J21=(D,F)=>{w21(F);for(let w=0;w<F.length;w++){let J=F[w];if(h9(D))D=tF(D,+J);else if(b9(D)){let p=+J,B=+F[++w]===0?"key":"value",Y=tF(D,p);switch(B){case"key":D=Y;break;case"value":D=D.get(Y);break}}else D=D[J]}return D},VV=(D,F,w)=>{if(w21(F),F.length===0)return w(D);let J=D;for(let B=0;B<F.length-1;B++){let Y=F[B];if(K8(J)){let Q=+Y;J=J[Q]}else if(O7(J))J=J[Y];else if(h9(J)){let Q=+Y;J=tF(J,Q)}else if(b9(J)){if(B===F.length-2)break;let X=+Y,W=+F[++B]===0?"key":"value",K=tF(J,X);switch(W){case"key":J=K;break;case"value":J=J.get(K);break}}}let p=F[F.length-1];if(K8(J))J[+p]=w(J[+p]);else if(O7(J))J[p]=w(J[p]);if(h9(J)){let B=tF(J,+p),Y=w(B);if(B!==Y)J.delete(B),J.add(Y)}if(b9(J)){let B=+F[F.length-2],Y=tF(J,B);switch(+p===0?"key":"value"){case"key":{let X=w(Y);if(J.set(X,J.get(Y)),X!==Y)J.delete(Y);break}case"value":{J.set(Y,w(J.get(Y)));break}}}return D};function kA(D,F,w=[]){if(!D)return;if(!K8(D)){C7(D,(B,Y)=>kA(B,F,[...w,...sF(Y)]));return}let[J,p]=D;if(p)C7(p,(B,Y)=>{kA(B,F,[...w,...sF(Y)])});F(J,w)}function p21(D,F,w){return kA(F,(J,p)=>{D=VV(D,p,(B)=>F21(B,J,w))}),D}function B21(D,F){function w(J,p){let B=J21(D,sF(p));J.map(sF).forEach((Y)=>{D=VV(D,Y,()=>B)})}if(K8(F)){let[J,p]=F;if(J.forEach((B)=>{D=VV(D,sF(B),()=>D)}),p)C7(p,w)}else C7(F,w);return D}var ce1=(D,F)=>O7(D)||K8(D)||b9(D)||h9(D)||fA(D,F);function le1(D,F,w){let J=w.get(D);if(J)J.push(F);else w.set(D,[F])}function Y21(D,F){let w={},J=void 0;if(D.forEach((p)=>{if(p.length<=1)return;if(!F)p=p.map((Q)=>Q.map(String)).sort((Q,X)=>Q.length-X.length);let[B,...Y]=p;if(B.length===0)J=Y.map(WV);else w[WV(B)]=Y.map(WV)}),J)if(EV(w))return[J];else return[J,w];else return EV(w)?void 0:w}var bA=(D,F,w,J,p=[],B=[],Y=new Map)=>{let Q=c01(D);if(!Q){le1(D,p,F);let u=Y.get(D);if(u)return J?{transformedValue:null}:u}if(!ce1(D,w)){let u=mA(D,w),G=u?{transformedValue:u.value,annotations:[u.type]}:{transformedValue:D};if(!Q)Y.set(D,G);return G}if(oF(B,D))return{transformedValue:null};let X=mA(D,w),W=X?.value??D,K=K8(W)?[]:{},H={};C7(W,(u,G)=>{if(G==="__proto__"||G==="constructor"||G==="prototype")throw new Error(`Detected property ${G}. This is a prototype pollution risk, please remove it from your object.`);let U=bA(u,F,w,J,[...p,G],[...B,D],Y);if(K[G]=U.transformedValue,K8(U.annotations))H[G]=U.annotations;else if(O7(U.annotations))C7(U.annotations,(Z,C)=>{H[jA(G)+"."+C]=Z})});let N=EV(H)?{transformedValue:K,annotations:X?[X.type]:void 0}:{transformedValue:K,annotations:X?[X.type,H]:H};if(!Q)Y.set(D,N);return N};function HV(D){return Object.prototype.toString.call(D).slice(8,-1)}function hA(D){return HV(D)==="Array"}function Q21(D){if(HV(D)!=="Object")return!1;let F=Object.getPrototypeOf(D);return!!F&&F.constructor===Object&&F===Object.prototype}function ge1(D){return HV(D)==="Null"}function ae1(D,F,w,J,p){return(B)=>D(B)||F(B)||!!w&&w(B)||!!J&&J(B)||!!p&&p(B)}function ne1(D){return HV(D)==="Undefined"}var XA0=ae1(ge1,ne1);function oe1(D,F,w,J,p){let B={}.propertyIsEnumerable.call(J,F)?"enumerable":"nonenumerable";if(B==="enumerable")D[F]=w;if(p&&B==="nonenumerable")Object.defineProperty(D,F,{value:w,enumerable:!1,writable:!0,configurable:!0})}function GV(D,F={}){if(hA(D))return D.map((p)=>GV(p,F));if(!Q21(D))return D;let w=Object.getOwnPropertyNames(D),J=Object.getOwnPropertySymbols(D);return[...w,...J].reduce((p,B)=>{if(hA(F.props)&&!F.props.includes(B))return p;let Y=D[B],Q=GV(Y,F);return oe1(p,B,Q,D,F.nonenumerable),p},{})}class f1{constructor({dedupe:D=!1}={}){this.classRegistry=new xA,this.symbolRegistry=new nB((F)=>F.description??""),this.customTransformerRegistry=new IA,this.allowedErrorProps=[],this.dedupe=D}serialize(D){let F=new Map,w=bA(D,F,this,this.dedupe),J={json:w.transformedValue};if(w.annotations)J.meta={...J.meta,values:w.annotations};let p=Y21(F,this.dedupe);if(p)J.meta={...J.meta,referentialEqualities:p};return J}deserialize(D){let{json:F,meta:w}=D,J=GV(F);if(w?.values)J=p21(J,w.values,this);if(w?.referentialEqualities)J=B21(J,w.referentialEqualities);return J}stringify(D){return JSON.stringify(this.serialize(D))}parse(D){return this.deserialize(JSON.parse(D))}registerClass(D,F){this.classRegistry.register(D,F)}registerSymbol(D,F){this.symbolRegistry.register(D,F)}registerCustom(D,F){this.customTransformerRegistry.register({name:F,...D})}allowErrorProps(...D){this.allowedErrorProps.push(...D)}}f1.defaultInstance=new f1;f1.serialize=f1.defaultInstance.serialize.bind(f1.defaultInstance);f1.deserialize=f1.defaultInstance.deserialize.bind(f1.defaultInstance);f1.stringify=f1.defaultInstance.stringify.bind(f1.defaultInstance);f1.parse=f1.defaultInstance.parse.bind(f1.defaultInstance);f1.registerClass=f1.defaultInstance.registerClass.bind(f1.defaultInstance);f1.registerSymbol=f1.defaultInstance.registerSymbol.bind(f1.defaultInstance);f1.registerCustom=f1.defaultInstance.registerCustom.bind(f1.defaultInstance);f1.allowErrorProps=f1.defaultInstance.allowErrorProps.bind(f1.defaultInstance);var{serialize:zA0,deserialize:UA0,stringify:ZA0,parse:$A0,registerClass:MA0,registerCustom:qA0,registerSymbol:AA0,allowErrorProps:CA0}=f1;function X21(D){let F=c6(D,"/trpc");return dE({links:[oD({url:F,transformer:f1,async fetch(w,J){return fetch(w,J).catch((p)=>{if(p.code==="ConnectionRefused")throw new Error(`Could not connect to the gateway service on ${D}. Is it running?`);throw p})}})]})}var uV=q1("trpc"),se1=async({path:D,type:F,next:w,input:J})=>{if(D==="health")return w();let p=Date.now();uV.trace({path:D,type:F,input:J},"trpc request received");try{let B=await w(),Y=Date.now()-p;if(B.ok)uV.trace({path:D,type:F,duration:Y},"trpc request successful");else uV.error({path:D,type:F,duration:Y,error:B.error},"trpc request failed");return B}catch(B){let Y=Date.now()-p;throw uV.error({path:D,type:F,duration:Y,error:B instanceof Error?B.message:"Unknown error"},"trpc request failed"),B}},yA=iU.context().create({transformer:f1,errorFormatter:({shape:D})=>{return{...D,data:{...D.data}}}}),te1=yA.procedure.use(se1),v0={router:yA.router,procedure:te1,middleware:yA.middleware};function E21(D,F){return dE({links:[oD({url:D,transformer:f1,async fetch(w,J){return fetch(w,{...J,headers:{...F?.headers,...J?.headers}}).catch((p)=>{if(p.code==="ConnectionRefused")throw new Error(`Could not connect to the service on ${D}. Is it running?`);throw p})}})]})}function NV(D,F={}){let w=c6(D,"/trpc");return E21(w,F.apiKey?{headers:{"x-api-key":F.apiKey}}:void 0)}var I2=X21(Q0.GATEWAY_URL),T4=NV(Q0.REGISTRY_API_URL,{apiKey:Q0.REGISTRY_API_KEY});var C21=z1(dJ(),1);import AV from"node:process";import z21 from"node:process";import $V from"node:process";var re1=(D,F,w,J)=>{if(w==="length"||w==="prototype")return;if(w==="arguments"||w==="caller")return;let p=Object.getOwnPropertyDescriptor(D,w),B=Object.getOwnPropertyDescriptor(F,w);if(!ee1(p,B)&&J)return;Object.defineProperty(D,w,B)},ee1=function(D,F){return D===void 0||D.configurable||D.writable===F.writable&&D.enumerable===F.enumerable&&D.configurable===F.configurable&&(D.writable||D.value===F.value)},D10=(D,F)=>{let w=Object.getPrototypeOf(F);if(w===Object.getPrototypeOf(D))return;Object.setPrototypeOf(D,w)},F10=(D,F)=>`/* Wrapped ${D}*/
604
604
  ${F}`,w10=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),J10=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),p10=(D,F,w)=>{let J=w===""?"":`with ${w.trim()}() `,p=F10.bind(null,J,F.toString());Object.defineProperty(p,"name",J10);let{writable:B,enumerable:Y,configurable:Q}=w10;Object.defineProperty(D,"toString",{value:p,writable:B,enumerable:Y,configurable:Q})};function iA(D,F,{ignoreNonConfigurable:w=!1}={}){let{name:J}=D;for(let p of Reflect.ownKeys(F))re1(D,F,p,w);return D10(D,F),p10(D,F,J),D}var zV=new WeakMap,W21=(D,F={})=>{if(typeof D!=="function")throw new TypeError("Expected a function");let w,J=0,p=D.displayName||D.name||"<anonymous>",B=function(...Y){if(zV.set(B,++J),J===1)w=D.apply(this,Y),D=void 0;else if(F.throw===!0)throw new Error(`Function \`${p}\` can only be called once`);return w};return iA(B,D),zV.set(B,J),B};W21.callCount=(D)=>{if(!zV.has(D))throw new Error(`The given function \`${D.name}\` is not wrapped by the \`onetime\` package`);return zV.get(D)};var K21=W21;var L7=[];L7.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")L7.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")L7.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var UV=(D)=>!!D&&typeof D==="object"&&typeof D.removeListener==="function"&&typeof D.emit==="function"&&typeof D.reallyExit==="function"&&typeof D.listeners==="function"&&typeof D.kill==="function"&&typeof D.pid==="number"&&typeof D.on==="function",cA=Symbol.for("signal-exit emitter"),lA=globalThis,B10=Object.defineProperty.bind(Object);class V21{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(lA[cA])return lA[cA];B10(lA,cA,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(D,F){this.listeners[D].push(F)}removeListener(D,F){let w=this.listeners[D],J=w.indexOf(F);if(J===-1)return;if(J===0&&w.length===1)w.length=0;else w.splice(J,1)}emit(D,F,w){if(this.emitted[D])return!1;this.emitted[D]=!0;let J=!1;for(let p of this.listeners[D])J=p(F,w)===!0||J;if(D==="exit")J=this.emit("afterExit",F,w)||J;return J}}class aA{}var Y10=(D)=>{return{onExit(F,w){return D.onExit(F,w)},load(){return D.load()},unload(){return D.unload()}}};class H21 extends aA{onExit(){return()=>{}}load(){}unload(){}}class G21 extends aA{#J=gA.platform==="win32"?"SIGINT":"SIGHUP";#F=new V21;#D;#p;#V;#w={};#Y=!1;constructor(D){super();this.#D=D,this.#w={};for(let F of L7)this.#w[F]=()=>{let w=this.#D.listeners(F),{count:J}=this.#F,p=D;if(typeof p.__signal_exit_emitter__==="object"&&typeof p.__signal_exit_emitter__.count==="number")J+=p.__signal_exit_emitter__.count;if(w.length===J){this.unload();let B=this.#F.emit("exit",null,F),Y=F==="SIGHUP"?this.#J:F;if(!B)D.kill(D.pid,Y)}};this.#V=D.reallyExit,this.#p=D.emit}onExit(D,F){if(!UV(this.#D))return()=>{};if(this.#Y===!1)this.load();let w=F?.alwaysLast?"afterExit":"exit";return this.#F.on(w,D),()=>{if(this.#F.removeListener(w,D),this.#F.listeners.exit.length===0&&this.#F.listeners.afterExit.length===0)this.unload()}}load(){if(this.#Y)return;this.#Y=!0,this.#F.count+=1;for(let D of L7)try{let F=this.#w[D];if(F)this.#D.on(D,F)}catch(F){}this.#D.emit=(D,...F)=>{return this.#H(D,...F)},this.#D.reallyExit=(D)=>{return this.#B(D)}}unload(){if(!this.#Y)return;this.#Y=!1,L7.forEach((D)=>{let F=this.#w[D];if(!F)throw new Error("Listener not defined for signal: "+D);try{this.#D.removeListener(D,F)}catch(w){}}),this.#D.emit=this.#p,this.#D.reallyExit=this.#V,this.#F.count-=1}#B(D){if(!UV(this.#D))return 0;return this.#D.exitCode=D||0,this.#F.emit("exit",this.#D.exitCode,null),this.#V.call(this.#D,this.#D.exitCode)}#H(D,...F){let w=this.#p;if(D==="exit"&&UV(this.#D)){if(typeof F[0]==="number")this.#D.exitCode=F[0];let J=w.call(this.#D,D,...F);return this.#F.emit("exit",this.#D.exitCode,null),J}else return w.call(this.#D,D,...F)}}var gA=globalThis.process,{onExit:ZV,load:oA0,unload:sA0}=Y10(UV(gA)?new G21(gA):new H21);var u21=$V.stderr.isTTY?$V.stderr:$V.stdout.isTTY?$V.stdout:void 0,Q10=u21?K21(()=>{ZV(()=>{u21.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},N21=Q10;var MV=!1,rF={};rF.show=(D=z21.stderr)=>{if(!D.isTTY)return;MV=!1,D.write("\x1B[?25h")};rF.hide=(D=z21.stderr)=>{if(!D.isTTY)return;N21(),MV=!0,D.write("\x1B[?25l")};rF.toggle=(D,F)=>{if(D!==void 0)MV=D;if(MV)rF.show(F);else rF.hide(F)};var nA=rF;var sB=z1(oA(),1);import V8 from"node:process";function sA(){if(V8.platform!=="win32")return V8.env.TERM!=="linux";return Boolean(V8.env.CI)||Boolean(V8.env.WT_SESSION)||Boolean(V8.env.TERMINUS_SUBLIME)||V8.env.ConEmuTask==="{cmd::Cmder}"||V8.env.TERM_PROGRAM==="Terminus-Sublime"||V8.env.TERM_PROGRAM==="vscode"||V8.env.TERM==="xterm-256color"||V8.env.TERM==="alacritty"||V8.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var E10={info:x1.blue("ℹ"),success:x1.green("✔"),warning:x1.yellow("⚠"),error:x1.red("✖")},W10={info:x1.blue("i"),success:x1.green("√"),warning:x1.yellow("‼"),error:x1.red("×")},K10=sA()?E10:W10,oB=K10;function tA({stream:D=process.stdout}={}){return Boolean(D&&D.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import M21 from"node:process";function rA(){let{env:D}=M21,{TERM:F,TERM_PROGRAM:w}=D;if(M21.platform!=="win32")return F!=="linux";return Boolean(D.WT_SESSION)||Boolean(D.TERMINUS_SUBLIME)||D.ConEmuTask==="{cmd::Cmder}"||w==="Terminus-Sublime"||w==="vscode"||F==="xterm-256color"||F==="alacritty"||F==="rxvt-unicode"||F==="rxvt-unicode-256color"||D.TERMINAL_EMULATOR==="JetBrains-JediTerm"}import r8 from"node:process";var V10=3;class q21{#J=0;start(){if(this.#J++,this.#J===1)this.#F()}stop(){if(this.#J<=0)throw new Error("`stop` called more times than `start`");if(this.#J--,this.#J===0)this.#D()}#F(){if(r8.platform==="win32"||!r8.stdin.isTTY)return;r8.stdin.setRawMode(!0),r8.stdin.on("data",this.#p),r8.stdin.resume()}#D(){if(!r8.stdin.isTTY)return;r8.stdin.off("data",this.#p),r8.stdin.pause(),r8.stdin.setRawMode(!1)}#p(D){if(D[0]===V10)r8.emit("SIGINT")}}var H10=new q21,eA=H10;var G10=z1(oA(),1);class A21{#J=0;#F=!1;#D=0;#p=-1;#V=0;#w;#Y;#B;#H;#u;#E;#W;#K;#N;#Q;#X;color;constructor(D){if(typeof D==="string")D={text:D};if(this.#w={color:"cyan",stream:AV.stderr,discardStdin:!0,hideCursor:!0,...D},this.color=this.#w.color,this.spinner=this.#w.spinner,this.#u=this.#w.interval,this.#B=this.#w.stream,this.#E=typeof this.#w.isEnabled==="boolean"?this.#w.isEnabled:tA({stream:this.#B}),this.#W=typeof this.#w.isSilent==="boolean"?this.#w.isSilent:!1,this.text=this.#w.text,this.prefixText=this.#w.prefixText,this.suffixText=this.#w.suffixText,this.indent=this.#w.indent,AV.env.NODE_ENV==="test")this._stream=this.#B,this._isEnabled=this.#E,Object.defineProperty(this,"_linesToClear",{get(){return this.#J},set(F){this.#J=F}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#p}}),Object.defineProperty(this,"_lineCount",{get(){return this.#D}})}get indent(){return this.#K}set indent(D=0){if(!(D>=0&&Number.isInteger(D)))throw new Error("The `indent` option must be an integer from 0 and up");this.#K=D,this.#G()}get interval(){return this.#u??this.#Y.interval??100}get spinner(){return this.#Y}set spinner(D){if(this.#p=-1,this.#u=void 0,typeof D==="object"){if(D.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#Y=D}else if(!rA())this.#Y=sB.default.line;else if(D===void 0)this.#Y=sB.default.dots;else if(D!=="default"&&sB.default[D])this.#Y=sB.default[D];else throw new Error(`There is no built-in spinner named '${D}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#N}set text(D=""){this.#N=D,this.#G()}get prefixText(){return this.#Q}set prefixText(D=""){this.#Q=D,this.#G()}get suffixText(){return this.#X}set suffixText(D=""){this.#X=D,this.#G()}get isSpinning(){return this.#H!==void 0}#z(D=this.#Q,F=" "){if(typeof D==="string"&&D!=="")return D+F;if(typeof D==="function")return D()+F;return""}#U(D=this.#X,F=" "){if(typeof D==="string"&&D!=="")return F+D;if(typeof D==="function")return F+D();return""}#G(){let D=this.#B.columns??80,F=this.#z(this.#Q,"-"),w=this.#U(this.#X,"-"),J=" ".repeat(this.#K)+F+"--"+this.#N+"--"+w;this.#D=0;for(let p of Z5(J).split(`
605
605
  `))this.#D+=Math.max(1,Math.ceil(k2(p,{countAnsiEscapeCodes:!0})/D))}get isEnabled(){return this.#E&&!this.#W}set isEnabled(D){if(typeof D!=="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#E=D}get isSilent(){return this.#W}set isSilent(D){if(typeof D!=="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#W=D}frame(){let D=Date.now();if(this.#p===-1||D-this.#V>=this.interval)this.#p=++this.#p%this.#Y.frames.length,this.#V=D;let{frames:F}=this.#Y,w=F[this.#p];if(this.color)w=x1[this.color](w);let J=typeof this.#Q==="string"&&this.#Q!==""?this.#Q+" ":"",p=typeof this.text==="string"?" "+this.text:"",B=typeof this.#X==="string"&&this.#X!==""?" "+this.#X:"";return J+w+p+B}clear(){if(!this.#E||!this.#B.isTTY)return this;this.#B.cursorTo(0);for(let D=0;D<this.#J;D++){if(D>0)this.#B.moveCursor(0,-1);this.#B.clearLine(1)}if(this.#K||this.lastIndent!==this.#K)this.#B.cursorTo(this.#K);return this.lastIndent=this.#K,this.#J=0,this}render(){if(this.#W)return this;return this.clear(),this.#B.write(this.frame()),this.#J=this.#D,this}start(D){if(D)this.text=D;if(this.#W)return this;if(!this.#E){if(this.text)this.#B.write(`- ${this.text}
606
606
  `);return this}if(this.isSpinning)return this;if(this.#w.hideCursor)nA.hide(this.#B);if(this.#w.discardStdin&&AV.stdin.isTTY)this.#F=!0,eA.start();return this.render(),this.#H=setInterval(this.render.bind(this),this.interval),this}stop(){if(!this.#E)return this;if(clearInterval(this.#H),this.#H=void 0,this.#p=0,this.clear(),this.#w.hideCursor)nA.show(this.#B);if(this.#w.discardStdin&&AV.stdin.isTTY&&this.#F)eA.stop(),this.#F=!1;return this}succeed(D){return this.stopAndPersist({symbol:oB.success,text:D})}fail(D){return this.stopAndPersist({symbol:oB.error,text:D})}warn(D){return this.stopAndPersist({symbol:oB.warning,text:D})}info(D){return this.stopAndPersist({symbol:oB.info,text:D})}stopAndPersist(D={}){if(this.#W)return this;let F=D.prefixText??this.#Q,w=this.#z(F," "),J=D.symbol??" ",p=D.text??this.text,Y=typeof p==="string"?(J?" ":"")+p:"",Q=D.suffixText??this.#X,X=this.#U(Q," "),W=w+J+Y+X+`
@@ -620,7 +620,7 @@ ${B.style.help(`(${D.instructions?.pager??"Use arrow keys to reveal more choices
620
620
  ${B.style.description(U.description)}`:"";return`${[X,Z,C].filter(Boolean).join(" ")}
621
621
  ${L}${q}${P}${M61.default.cursorHide}`});function q61(D){return D.command("add <proxyId>").description("Add a server to a proxy.").addOption(L8({flags:"-e,--entry <entryName>",description:"add a server from the registry by specifying the entry name"})).addOption(L8({flags:"-u,--url <url>",description:"add a streamable or sse server by specifying the url"})).addOption(L8({flags:"-n,--name <serverName>",description:"the name of the server as it'll appear in the config file"})).action(_1(async(F,w)=>{if(w.entry)console.log(`adding ${w.entry} to ${F}`),await Q00(F,w.entry);else if(w.url){if(!w.name)throw new Error("No server name provided. use --name to specify the name of the server");console.log(`adding ${w.url} to ${F}`),await Y00(F,w.url,w.name)}else console.warn("No entry name or url provided. You must speciy --entry or --url and --name, alternatively update the config file directly and restart the gateway:"),console.log(),console.log(`${G2("CONFIG_FILE_PATH:")} ${Q0.CONFIG_FILE_PATH}`),console.log()}))}async function Y00(D,F,w){await l6(async()=>{await I2.store.addServer.mutate({proxyId:D,server:{name:w,transport:{type:"http",url:F}}})}).start("installing server...").succeed(`HTTP server ${F} added to ${D}`).run()}async function Q00(D,F){let w=await l6(()=>T4.entries.getEntryByName.query({name:F})).start("fetching entry...").succeed("Entry fetched.").run(),J=await X00(w);await l6(async()=>{let p=await T4.entries.getTransportForEntry.query({entryName:F,parameters:J});await I2.store.addServer.mutate({proxyId:D,server:{name:F,transport:p,source:{name:"registry",entryId:w.id,entryData:w}}})}).start("installing server...").succeed(`Registry entry ${F} added to ${D}`).run()}async function X00(D){let F={};if(!D.parameters)return{};for(let w of D.parameters)if(w.required)F[w.name]=await UC({message:w.name,mask:"*"});else F[w.name]=await zC({message:w.name});return F}var A61=q1("gateway/helpers");function BY(D){return`/${D}/mcp`}function YY(D){return`/${D}/sse`}async function MC(D){A61.info(`restarting connected clients for ${D.id}`);for(let F of lJ()){let w=y2(F);if(await w.isInstalled(D.id))A61.info(`${D.id} is intalled in ${F}, restarting...`),await w.restart()}}function C61(D){D.command("connect <proxyId>").description("Connect a proxy to a MCP client").addOption(L8({flags:"-t,--target <target>",description:"target client",choices:["claude","cursor","vscode"]})).action(_1(async(F,w)=>{if(w.target){let J=await I2.store.get.query({proxyId:F}),B=await(await y2(w.target)).install({name:J.id,url:c6(Q0.GATEWAY_URL,YY(J.id))});console.log(B)}else{console.log(),console.log(O8("--------------------------------")),console.log(O8(`Connection Details for '${F}'`)),console.log(O8("--------------------------------")),console.log(),console.log("Note: if you'd like to connect to a client automatically, run:"),console.log("director connect "+F+" --target <target>"),console.log();let J=await I2.store.get.query({proxyId:F}),p=Q0.GATEWAY_URL,B=c6(p,YY(J.id)),Y=c6(p,BY(J.id)),Q={command:"npx",args:["-y","@director.run/cli@latest","http2stdio",Y],env:{LOG_LEVEL:"silent"}};console.log(G2("HTTP Streamable:")+" "+Y),console.log(G2("HTTP SSE:")+" "+B),console.log(G2("Stdio:"),JSON.stringify(Q,null,2)),console.log()}}))}function O61(D){D.debugCommand("test-proxy <proxyId>").description("Run a high level test of a proxy").action(_1(async(F)=>{let w=new s8("proxy-test-client");await w.connectToHTTP(c6(Q0.GATEWAY_URL,`${F}/mcp`));let{tools:J}=await w.listTools();console.log(),console.log(G2("TOOLS")),console.log(),console.log(J.map((p)=>p.name).join(`
622
622
  `)),console.log(),await w.close()})),D.debugCommand("reset").description("Delete proxies, clear the config file, and reset all clients").action(_1(async({target:F})=>{console.log("resetting service"),await I2.store.purge.mutate(),console.log("resetting clients"),await zE()}))}import E00 from"node:fs";function L61(D){D.command("env").description("Print environment variables").option("--write","Write the environment variables to .env.local in current working directory").action(_1((F)=>{if(F.write){console.log(`writing env vars to '${JJ}'`);let w=Object.entries(Q0).map(([J,p])=>`${J}=${p}`).join(`
623
- `);E00.writeFileSync(JJ,w)}else AP()&&console.log(O8(`using env file: ${TQ()}`)),console.log(),console.log("env",Q0)}))}import{exec as W00,execSync as K00}from"node:child_process";import{promisify as V00}from"node:util";var H00=V00(W00),aL0=q1("restartApp");function qC(D){if(process.platform==="win32")return!1;try{return K00(`which ${D}`,{stdio:"pipe"}).toString().trim().length>0}catch(w){return!1}}async function T61(D){if(!D||typeof D!=="string")throw new Error("Invalid URL provided");let F=D.startsWith("http://")||D.startsWith("https://")?D:`https://${D}`,w=process.platform,J;switch(w){case"darwin":J=`open "${F}"`;break;case"win32":J=`start "" "${F}"`;break;case"linux":J=`xdg-open "${F}"`;break;default:throw new Error(`Unsupported platform: ${w}`)}try{await H00(J)}catch(p){throw new Error(`Failed to open URL: ${p instanceof Error?p.message:"Unknown error"}`)}}async function Yw(){return{platform:process.platform,dependencies:[{name:"npx",installed:qC("npx")},{name:"uvx",installed:qC("uvx")}],clients:await yD()}}var I61=z1(v61(),1),S61=q1("http/middleware"),d61=(D,F,w,J)=>{let{status:p,message:B,code:Y}=C00(D);S61.error({message:`${F.method} ${F.originalUrl} failed: ${B}`,code:Y}),w.status(p).json({message:B,code:Y})};function C00(D){if(vX(D))return O00(D);if(C_(D))return{status:D.statusCode,message:D.message};else return{status:500,message:"Something unexpected happened :("}}function O00(D){let F;switch(D.code){case"NOT_FOUND":F=404;break;case"BAD_REQUEST":F=400;break;default:F=500}return{status:F,message:D.message,code:D.code}}function _61(){throw new O1("NOT_FOUND","there's nothing here")}function Ew(D){return(F,w,J)=>{Promise.resolve(D(F,w,J)).catch(J)}}function j61(){return I61.default({logger:S61,useLevel:"trace",autoLogging:{ignore:(D)=>D.originalUrl?.startsWith("/trpc")},serializers:{req:(D)=>({id:D.id,ip:D.ip||D.connection?.remoteAddress,userAgent:D.headers["user-agent"]}),res:(D)=>({status:D.statusCode})},customReceivedMessage:(D)=>`→ ${D.method} ${D.originalUrl}`,customSuccessMessage:(D,F)=>{let w=F.statusCode,J=w>=500?"\uD83D\uDD34":w>=400?"\uD83D\uDFE1":"\uD83D\uDFE2";return`← ${D.method} ${D.originalUrl} ${J} ${w}`},customErrorMessage:(D,F)=>`← ${D.method} ${D.originalUrl} \uD83D\uDD34 ${F.statusCode}`})}var pw1=z1(ww1(),1),Bw1=z1(Jw1(),1);import zL from"os";class F5{analytics;machineId;enabled;traits;constructor(D){this.analytics=new pw1.Analytics({writeKey:D.writeKey}),this.enabled=D.enabled,this.traits=D.traits||{}}async initialize(){if(this.machineId)return;if(this.machineId=await Bw1.machineId(),this.enabled)this.analytics.identify({userId:this.machineId,traits:{...this.traits,os:zL.platform(),osVersion:zL.release(),arch:zL.arch()}})}static noTelemetry(){return new F5({writeKey:"--",enabled:!1})}async trackEvent(D,F={}){if(await this.initialize(),this.enabled)this.analytics.track({userId:this.machineId,event:D,properties:F})}}var Tw1=z1(Ww1(),1),Rw1=z1(ZB(),1);import{existsSync as _J0}from"node:fs";var M2=A.string().trim().min(1,"Required"),UH=M2.nullish(),TJ0=A.string().trim().min(1,"Required").regex(/^[a-z0-9._-]+$/,"Only lowercase ASCII letters, digits, and characters ., -, _ are allowed"),RJ0=A.object({type:A.literal("http"),url:M2.url(),headers:A.record(M2,A.string()).optional()}),PJ0=A.object({type:A.literal("stdio"),command:M2,args:A.array(A.string()).default([]),env:A.record(M2,A.string()).optional()}),Kw1=A.discriminatedUnion("type",[RJ0,PJ0]),xJ0=A.object({name:M2,description:M2,required:A.boolean(),type:A.enum(["string"]),password:A.boolean().optional()}),vJ0=A.object({name:M2,description:M2,inputSchema:A.object({type:M2,required:A.array(A.string()).optional(),properties:A.record(M2,A.object({type:A.string().optional(),description:A.string().optional(),default:A.unknown().optional(),title:A.string().optional(),anyOf:A.unknown().optional()})).optional()})}),IJ0=A.object({id:M2,name:M2,title:M2,description:M2,icon:UH,createdAt:A.coerce.date().nullable().default(null),isOfficial:A.boolean().nullable().default(null),isEnriched:A.boolean().nullable().default(null),isConnectable:A.boolean().nullable().default(null),lastConnectionAttemptedAt:A.coerce.date().nullable().default(null),lastConnectionError:UH,homepage:M2,transport:Kw1,source_registry:A.any(),categories:A.array(A.string()).nullable().default(null),tools:A.array(vJ0).nullable().default(null),parameters:A.array(xJ0),readme:UH}),SJ0=A.object({name:A.literal("registry"),entryId:M2,entryData:IJ0}),ZH=A.object({name:TJ0,transport:Kw1,source:SJ0.optional()}),dJ0=A.object({id:M2,name:M2,description:UH,servers:A.array(ZH)}),Vw1=A.object({proxies:A.array(dJ0)});var $H=z1(Hw1(),1);async function PY(D){let F=await HE(D);return Vw1.parse(F)}async function xY(D,F){return await t4(D,F)}class MH{filePath;constructor(D){this.filePath=D}static async connect(D){let F=new MH(D);if(!_J0(D))await xY(D,{proxies:[]});return F}async addProxy(D){let F=await PY(this.filePath);if(F.proxies.find((p)=>p.name===D.name))throw new Error("Proxy already exists");let J={...D,servers:(D.servers||[]).map((p)=>({...p,name:$H.default(p.name,{lower:!0,strict:!0,trim:!0})})),id:$H.default(D.name,{lower:!0,strict:!0,trim:!0})};return F.proxies.push(J),await xY(this.filePath,F),J}async getProxy(D){let w=(await PY(this.filePath)).proxies.find((J)=>J.id===D);if(!w)throw new Error("Proxy not found");return w}async deleteProxy(D){let F=await PY(this.filePath);if(!F.proxies.find((J)=>J.id===D))throw new Error("Proxy not found");F.proxies=F.proxies.filter((J)=>J.id!==D),await xY(this.filePath,F)}async updateProxy(D,F){let w=await PY(this.filePath),J=w.proxies.find((p)=>p.id===D);if(!J)throw new Error("Proxy not found");return Object.assign(J,{...F,servers:(F.servers||J.servers||[]).map((p)=>({...p,name:$H.default(p.name,{lower:!0,trim:!0})}))}),await xY(this.filePath,w),J}async getAll(){return(await PY(this.filePath)).proxies}async purge(){await xY(this.filePath,{proxies:[]})}}var b7=q1("ProxyServerStore");class qH{proxyServers=new Map;db;telemetry;constructor(D){this.db=D.db,this.telemetry=D.telemetry||F5.noTelemetry()}static async create(D,F){b7.debug("initializing ProxyServerStore");let w=new qH({db:D,telemetry:F});return await w.initialize(),b7.debug("initialization complete"),w}async initialize(){let D=await this.db.getAll();for(let F of D){let w=F.id;b7.debug({message:`initializing ${w}`,proxyId:w});let J=new nF({id:w,name:F.name,description:F.description??void 0,servers:F.servers});await J.connectTargets(),this.proxyServers.set(w,J)}}get(D){let F=this.proxyServers.get(D);if(!F)throw new O1("NOT_FOUND",`proxy server '${D}' not found or failed to initialize.`);return F}async delete(D){this.telemetry.trackEvent("proxy_deleted"),await this.get(D).close(),await this.db.deleteProxy(D),this.proxyServers.delete(D),b7.info(`successfully deleted proxy server configuration: ${D}`)}async purge(){await this.closeAll(),await this.db.purge(),this.proxyServers.clear()}async closeAll(){b7.info("cleaning up all proxy servers..."),await Promise.all(Array.from(this.proxyServers.values()).map((D)=>D.close())),b7.info("finished cleaning up all proxy servers.")}getAll(){return Array.from(this.proxyServers.values())}async create({name:D,description:F,servers:w,source:J}){this.telemetry.trackEvent("proxy_created");let p=await this.db.addProxy({name:D,description:F,servers:w??[]}),B=new nF({name:D,id:p.id,servers:p.servers,description:p.description??void 0});return await B.connectTargets(),this.proxyServers.set(p.id,B),b7.info({message:"Created new proxy",proxyId:p.id}),B}async addServer(D,F){this.telemetry.trackEvent("server_added");let w=this.get(D);return await w.addTarget(F,{throwOnError:!0}),await this.db.updateProxy(D,{servers:w.attributes.servers}),w}async removeServer(D,F){this.telemetry.trackEvent("server_removed");let w=this.get(D);return await w.removeTarget(F),await this.db.updateProxy(D,{servers:w.attributes.servers}),w}async update(D,F){this.telemetry.trackEvent("proxy_updated");let w=this.get(D);return await w.update(F),await this.db.updateProxy(D,F),w}}var Gw1=z1(A9(),1),uw1=z1(uW(),1),jJ0="4mb";async function Nw1(D){let F=Gw1.default.parse(D.headers["content-type"]??"");if(F.type!=="application/json")throw new Error(`Unsupported content-type: ${F}`);let w=await uw1.default(D,{limit:jJ0,encoding:F.parameters.charset??"utf-8"});return JSON.parse(w)}var zw1=z1(ZB(),1),AH=q1("mcp/sse"),Uw1=({proxyStore:D,telemetry:F})=>{let w=zw1.default.Router(),J=new Map;return w.get("/:proxy_id/sse",Ew(async(p,B)=>{let Y=p.params.proxy_id,Q=D.get(Y),X=new NW(`/${Q.id}/message`,B);J.set(X.sessionId,X),AH.info({message:"SSE connection started",sessionId:X.sessionId,proxyId:Q.id,userAgent:p.headers["user-agent"],host:p.headers.host}),F.trackEvent("connection_started",{transport:"sse"}),p.socket.on("close",()=>{AH.info({message:"SSE connection closed",sessionId:X.sessionId,proxyId:Q.id}),J.delete(X.sessionId)}),await Q.connect(X)})),w.post("/:proxy_id/message",Ew(async(p,B)=>{let Y=p.params.proxy_id,Q=D.get(Y),X=p.query.sessionId?.toString();if(!X)throw new O1("BAD_REQUEST","No sessionId provided");let W=await Nw1(p);AH.info({message:"Message received",proxyId:Q.id,sessionId:X,method:W.method,params:W.params});let K=J.get(X);if(!K)throw AH.warn({message:"Transport not found",sessionId:X,proxyId:Q.id}),new O1("NOT_FOUND","Transport not found");F.trackEvent("method_called",{method:W.method,transport:"sse"}),await K.handlePostMessage(p,B,W)})),w};var $L=z1(ZB(),1),vY=q1("mcp/streamable"),Zw1=({proxyStore:D,telemetry:F})=>{let w=$L.default.Router(),J=new Map;w.use($L.default.json()),w.post("/:proxy_id/mcp",Ew(async(B,Y)=>{let Q=B.params.proxy_id,X=await D.get(Q),W=B.headers["mcp-session-id"],K;if(W&&J.has(W)){let H=J.get(W);if(!H)throw new O1("NOT_FOUND","Transport not found");K=H}else if(!W&&Ep(B.body))vY.info(`[${X.id}] new initialization request`),F.trackEvent("connection_started",{transport:"streamable"}),K=new UW({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:(H)=>{J.set(H,K)}}),K.onclose=()=>{if(vY.info(`[${X.id}] transport closed`,{proxyId:X.id,sessionId:K.sessionId}),K.sessionId)J.delete(K.sessionId)},B.socket.on("close",()=>{vY.info(`[${X.id}] socket closed'`,{proxyId:X.id,sessionId:K.sessionId})}),await X.connect(K);else throw new O1("BAD_REQUEST","No valid session ID provided");vY.info({message:`[${X.id}] '${B.body.method}' called`,proxyId:X.id,sessionId:K.sessionId,method:B.body.method,body:B.body}),F.trackEvent("method_called",{method:B.body.method,transport:"streamable"}),await K.handleRequest(B,Y,B.body)}));let p=Ew(async(B,Y)=>{let Q=B.params.proxy_id,X=D.get(Q),W=B.headers["mcp-session-id"];if(!W||!J.has(W))throw new O1("BAD_REQUEST","Invalid or missing session ID");let K=J.get(W);if(!K)throw new O1("NOT_FOUND","Transport not found");let H=K;vY.info({message:"MCP handleSessionRequest",proxyId:X.id,sessionId:H.sessionId,body:B.body}),await H.handleRequest(B,Y)});return w.get("/:proxy_id/mcp",p),w.delete("/:proxy_id/mcp",p),w};function fJ0(D,F){if("body"in D){if(D.body===void 0)return;if(typeof D.body==="string")return D.body;return JSON.stringify(D.body)}let w=0,J=!1;return new ReadableStream({start(p){let B=(Q)=>{if(w+=Q.length,!F.maxBodySize||w<=F.maxBodySize){p.enqueue(new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength));return}p.error(new K0({code:"PAYLOAD_TOO_LARGE"})),J=!0,D.off("data",B),D.off("end",Y)},Y=()=>{if(J)return;J=!0,D.off("data",B),D.off("end",Y),p.close()};D.on("data",B),D.on("end",Y)},cancel(){D.destroy()}})}function mJ0(D){try{var F,w;let J=D.headers[":scheme"]&&D.headers[":scheme"]==="https"||D.socket&&"encrypted"in D.socket&&D.socket.encrypted?"https:":"http:",p=(F=(w=D.headers.host)!==null&&w!==void 0?w:D.headers[":authority"])!==null&&F!==void 0?F:"localhost";return new URL(D.url,`${J}//${p}`)}catch(J){throw new K0({code:"BAD_REQUEST",message:"Invalid URL",cause:J})}}function kJ0(D){let F=new Headers;for(let w in D){let J=D[w];if(typeof w==="string"&&w.startsWith(":"))continue;if(Array.isArray(J))for(let p of J)F.append(w,p);else if(J!=null)F.append(w,J)}return F}function bJ0(D,F,w){let J=new AbortController,p=()=>{F.off("close",p),D.off("aborted",p),J.abort()};F.once("close",p),D.once("aborted",p);let B=mJ0(D),Y={headers:kJ0(D.headers),method:D.method,signal:J.signal};if(D.method!=="GET"&&D.method!=="HEAD")Y.body=fJ0(D,w),Y.duplex="half";return new Request(B,Y)}async function hJ0(D,F){if(D.write(F)===!1)await new Promise((w,J)=>{let p=(Q)=>{J(Q),Y()},B=()=>{w(),Y()},Y=()=>{D.off("error",p),D.off("drain",B)};D.once("error",p),D.once("drain",B)})}async function yJ0(D){let{res:F}=D;try{let w=new WritableStream({async write(J){var p;await hJ0(F,J),(p=F.flush)===null||p===void 0||p.call(F)}});await D.body.pipeTo(w,{signal:D.signal})}catch(w){if(LE(w))return;throw w}}async function iJ0(D){let{response:F,rawResponse:w}=D;if(w.statusCode===200)w.statusCode=F.status;for(let[J,p]of F.headers)w.setHeader(J,p);try{if(F.body)await yJ0({res:w,signal:D.request.signal,body:F.body})}catch(J){if(!w.headersSent)w.statusCode=500;throw J}finally{w.end()}}var Rw=y1(G6(),1);function ML(D){return(F)=>{var w;let{res:J,req:p}=D,B=D6(F),Y=_8({config:D.router._def._config,error:B,type:"unknown",path:void 0,input:void 0,ctx:void 0});(w=D.onError)===null||w===void 0||w.call(D,{req:p,error:B,type:"unknown",path:void 0,input:void 0,ctx:void 0});let Q=a5(D.router._def._config,{error:Y});J.statusCode=Y.data.httpStatus,J.end(JSON.stringify(Q))}}async function $w1(D){return new Promise((F)=>{var w;let J=(w=D.middleware)!==null&&w!==void 0?w:(p,B,Y)=>Y();return D.res.once("finish",()=>{F()}),J(D.req,D.res,(p)=>{e4(async()=>{var B;let Y=bJ0(D.req,D.res,{maxBodySize:(B=D.maxBodySize)!==null&&B!==void 0?B:null}),Q=async(W)=>{var K;return await((K=D.createContext)===null||K===void 0?void 0:K.call(D,Rw.default(Rw.default({},D),W)))},X=await Eb(Rw.default(Rw.default({},D),{},{req:Y,error:p?D6(p):null,createContext:Q,onError(W){var K;D===null||D===void 0||(K=D.onError)===null||K===void 0||K.call(D,Rw.default(Rw.default({},W),{},{req:D.req}))}}));await iJ0({request:Y,response:X,rawResponse:D.res})}).catch(ML(D))})})}var qL=y1(G6(),1);function Mw1(D){return(F,w)=>{let J="";e4(async()=>{J=F.path.slice(F.path.lastIndexOf("/")+1),await $w1(qL.default(qL.default({},D),{},{req:F,res:w,path:J}))}).catch(ML(qL.default({req:F,res:w,path:J},D)))}}function qw1({proxyStore:D}){return v0.router({allClients:v0.procedure.query(()=>yD()),byProxy:v0.router({list:v0.procedure.input(A.object({proxyId:A.string()})).query(async({input:F})=>{return await Mk(F.proxyId)}),install:v0.procedure.input(A.object({client:A.nativeEnum(cJ),proxyId:A.string(),baseUrl:A.string()})).mutation(async({input:F})=>{let w=D.get(F.proxyId);await(await y2(F.client)).install({name:w.id,url:c6(F.baseUrl,YY(w.id))})}),uninstall:v0.procedure.input(A.object({client:A.nativeEnum(cJ),proxyId:A.string()})).mutation(async({input:F})=>{let w=D.get(F.proxyId);await(await y2(F.client)).uninstall(w.id)})})})}function Aw1({registryURL:D,proxyStore:F}){let w=NV(D);return v0.router({getEntries:v0.procedure.input(A.object({pageIndex:A.number().min(0),pageSize:A.number().min(1)})).query(({input:J})=>w.entries.getEntries.query(J)),getEntryByName:v0.procedure.input(A.object({name:A.string()})).query(({input:J})=>w.entries.getEntryByName.query(J)),getTransportForEntry:v0.procedure.input(A.object({entryName:A.string(),parameters:A.record(A.string(),A.string()).optional()})).mutation(async({input:J})=>{return await w.entries.getTransportForEntry.query({entryName:J.entryName,parameters:J.parameters})})})}var Cw1=A.object({name:A.string(),description:A.string().optional(),servers:A.array(ZH).optional()}),lJ0=Cw1.omit({servers:!0}).partial();function Ow1({proxyStore:D}){return v0.router({getAll:v0.procedure.query(async()=>{return(await D.getAll()).map((F)=>({...F.toPlainObject(),path:BY(F.id)}))}),get:v0.procedure.input(A.object({proxyId:A.string()})).query(({input:F})=>{return{...D.get(F.proxyId).toPlainObject(),path:BY(F.proxyId)}}),create:v0.procedure.input(Cw1).mutation(async({input:F})=>{return(await D.create({name:F.name,description:F.description??void 0,servers:F.servers})).toPlainObject()}),update:v0.procedure.input(A.object({proxyId:A.string(),attributes:lJ0})).mutation(async({input:F})=>{return(await D.update(F.proxyId,{name:F.attributes.name,description:F.attributes.description??void 0})).toPlainObject()}),delete:v0.procedure.input(A.object({proxyId:A.string()})).mutation(async({input:F})=>{return await D.delete(F.proxyId),{success:!0}}),addServer:v0.procedure.input(A.object({proxyId:A.string(),server:ZH})).mutation(async({input:F})=>{let w=await D.addServer(F.proxyId,F.server);return await MC(w),w.toPlainObject()}),purge:v0.procedure.mutation(()=>D.purge()),removeServer:v0.procedure.input(A.object({proxyId:A.string(),serverName:A.string()})).mutation(async({input:F})=>{let w=await D.removeServer(F.proxyId,F.serverName);return await MC(w),w.toPlainObject()})})}function gJ0({proxyStore:D,registryURL:F}){return v0.router({health:v0.procedure.query(()=>Yw()),store:Ow1({proxyStore:D}),installer:qw1({proxyStore:D}),registry:Aw1({registryURL:F,proxyStore:D})})}function Lw1({proxyStore:D,registryURL:F}){return Mw1({router:gJ0({proxyStore:D,registryURL:F})})}var AL=q1("Gateway");class CH{proxyStore;port;server;constructor(D){this.port=D.port,this.proxyStore=D.proxyStore,this.server=D.server}static async start(D,F){AL.info("starting director gateway");let w=await MH.connect(D.databaseFilePath),J=D.telemetry||F5.noTelemetry(),p=await qH.create(w,J),B=Rw1.default(),Y=D.registryURL;B.use(Tw1.default({origin:D.allowedOrigins})),B.use(j61()),B.use("/",Uw1({proxyStore:p,telemetry:J})),B.use("/",Zw1({proxyStore:p,telemetry:J})),B.use("/trpc",Lw1({proxyStore:p,registryURL:Y})),B.all("*",_61),B.use(d61),J.trackEvent("gateway_start");let Q=B.listen(D.port,()=>{AL.info(`director gateway running on port ${D.port}`),F?.()}),X=new CH({port:D.port,db:w,proxyStore:p,server:Q});return process.on("SIGINT",async()=>{AL.info("received SIGINT, cleaning up proxy servers..."),await X.stop(),process.exit(0)}),X}async stop(){await this.proxyStore.closeAll(),await new Promise((D)=>{this.server.closeAllConnections(),this.server.close(()=>D())})}}function Pw1(D){D.command("serve").description("Start the web service").action(_1(async()=>{try{await CL()}catch(F){console.error("Fatal error starting gateway",F),process.exit(1)}}))}async function CL(D){console.log(`v${K9.version}`),Oh(),await CH.start({port:Q0.GATEWAY_PORT,databaseFilePath:Q0.CONFIG_FILE_PATH,registryURL:Q0.REGISTRY_API_URL,allowedOrigins:[Q0.STUDIO_URL,/^https?:\/\/localhost(:\d+)?$/],telemetry:new F5({writeKey:Q0.SEGMENT_WRITE_KEY,enabled:Q0.SEND_TELEMETRY,traits:{cliVersion:K9.version}})},D)}function xw1(D){D.command("studio").description("Open the UI in your browser").action(_1(async()=>{let F=tB();F.start("opening studio...");try{await I2.health.query()}catch(w){F.fail("Failed to connect to gateway. Have you ran `director serve`?"),process.exit(1)}try{OL()}catch(w){F.fail(`failed to open ${Q0.STUDIO_URL}, try manually`)}F.stop()}))}async function OL(){await T61(Q0.STUDIO_URL)}var aJ0=q1("quickstart");function Iw1(D){D.command("quickstart").description("Start the gateway and open the studio in your browser").action(_1(async()=>{await nJ0(),await CL(async()=>{aJ0.info(`gateway started, opening ${Q0.STUDIO_URL} in your browser...`),await OL()})}))}async function nJ0(){let D=tB();D.start("checking prerequisites...");let F=await Yw();D.stop();let w=[],J=[];w.push(""),w.push(G2("Dependency Check")),w.push("The following dependencies are required by some MCP servers that use Stdout. It's best to have them all installed."),w.push("");for(let Y of F.dependencies)w.push(vw1({name:Y.name,installed:Y.installed,successText:`${Y.name} is installed`,failureText:`${Y.name} is not available in $PATH. ${oJ0(Y)}`}));if(F.dependencies.filter((Y)=>Y.installed).length<F.dependencies.length)J.push("Some dependencies are not available in $PATH, MCP servers that depend on them will not work.");w.push(""),w.push(G2("MCP Clients Check")),w.push("Director can automatically configure the following MCP clients for you. It's best to have at least one installed."),w.push("");for(let Y of F.clients)w.push(vw1({name:Y.name,installed:Y.installed}));if(F.clients.filter((Y)=>Y.installed).length===0)J.push("No MCP clients found. It's best to have at least one MCP client installed in order to use the automatic client configuration.");if(w.push(""),w.push(G2("Summary")),w.push(""),console.log(w.join(`
623
+ `);E00.writeFileSync(JJ,w)}else AP()&&console.log(O8(`using env file: ${TQ()}`)),console.log(),console.log("env",Q0)}))}import{exec as W00,execSync as K00}from"node:child_process";import{promisify as V00}from"node:util";var H00=V00(W00),aL0=q1("restartApp");function qC(D){if(process.platform==="win32")return!1;try{return K00(`which ${D}`,{stdio:"pipe"}).toString().trim().length>0}catch(w){return!1}}async function T61(D){if(!D||typeof D!=="string")throw new Error("Invalid URL provided");let F=D.startsWith("http://")||D.startsWith("https://")?D:`https://${D}`,w=process.platform,J;switch(w){case"darwin":J=`open "${F}"`;break;case"win32":J=`start "" "${F}"`;break;case"linux":J=`xdg-open "${F}"`;break;default:throw new Error(`Unsupported platform: ${w}`)}try{await H00(J)}catch(p){throw new Error(`Failed to open URL: ${p instanceof Error?p.message:"Unknown error"}`)}}async function Yw(){return{platform:process.platform,dependencies:[{name:"npx",installed:qC("npx")},{name:"uvx",installed:qC("uvx")}],clients:await yD()}}var I61=z1(v61(),1),S61=q1("http/middleware"),d61=(D,F,w,J)=>{let{status:p,message:B,code:Y}=C00(D);S61.error({message:`${F.method} ${F.originalUrl} failed: ${B}`,code:Y}),w.status(p).json({message:B,code:Y})};function C00(D){if(vX(D))return O00(D);if(C_(D))return{status:D.statusCode,message:D.message};else return{status:500,message:"Something unexpected happened :("}}function O00(D){let F;switch(D.code){case"NOT_FOUND":F=404;break;case"BAD_REQUEST":F=400;break;default:F=500}return{status:F,message:D.message,code:D.code}}function _61(){throw new O1("NOT_FOUND","there's nothing here")}function Ew(D){return(F,w,J)=>{Promise.resolve(D(F,w,J)).catch(J)}}function j61(){return I61.default({logger:S61,useLevel:"trace",autoLogging:{ignore:(D)=>D.originalUrl?.startsWith("/trpc")},serializers:{req:(D)=>({id:D.id,ip:D.ip||D.connection?.remoteAddress,userAgent:D.headers["user-agent"]}),res:(D)=>({status:D.statusCode})},customReceivedMessage:(D)=>`→ ${D.method} ${D.originalUrl}`,customSuccessMessage:(D,F)=>{let w=F.statusCode,J=w>=500?"\uD83D\uDD34":w>=400?"\uD83D\uDFE1":"\uD83D\uDFE2";return`← ${D.method} ${D.originalUrl} ${J} ${w}`},customErrorMessage:(D,F)=>`← ${D.method} ${D.originalUrl} \uD83D\uDD34 ${F.statusCode}`})}var pw1=z1(ww1(),1),Bw1=z1(Jw1(),1);import zL from"os";class F5{analytics;machineId;enabled;traits;constructor(D){this.analytics=new pw1.Analytics({writeKey:D.writeKey}),this.enabled=D.enabled,this.traits=D.traits||{}}async initialize(){if(this.machineId)return;if(this.machineId=await Bw1.machineId(),this.enabled)this.analytics.identify({userId:this.machineId,traits:{...this.traits,os:zL.platform(),osVersion:zL.release(),arch:zL.arch()}})}static noTelemetry(){return new F5({writeKey:"--",enabled:!1})}async trackEvent(D,F={}){if(await this.initialize(),this.enabled)this.analytics.track({userId:this.machineId,event:D,properties:F})}}var Tw1=z1(Ww1(),1),Rw1=z1(ZB(),1);import{existsSync as _J0}from"node:fs";var M2=A.string().trim().min(1,"Required"),UH=M2.nullish(),TJ0=A.string().trim().min(1,"Required").regex(/^[a-z0-9._-]+$/,"Only lowercase ASCII letters, digits, and characters ., -, _ are allowed"),RJ0=A.object({type:A.literal("http"),url:M2.url(),headers:A.record(M2,A.string()).optional()}),PJ0=A.object({type:A.literal("stdio"),command:M2,args:A.array(A.string()).default([]),env:A.record(M2,A.string()).optional()}),Kw1=A.discriminatedUnion("type",[RJ0,PJ0]),xJ0=A.object({name:M2,description:M2,required:A.boolean(),type:A.enum(["string"]),password:A.boolean().optional()}),vJ0=A.object({name:M2,description:M2,inputSchema:A.object({type:M2,required:A.array(A.string()).optional(),properties:A.record(M2,A.object({type:A.string().optional(),description:A.string().optional(),default:A.unknown().optional(),title:A.string().optional(),anyOf:A.unknown().optional()})).optional()})}),IJ0=A.object({id:M2,name:M2,title:M2,description:M2,icon:UH,createdAt:A.coerce.date().nullable().default(null),isOfficial:A.boolean().nullable().default(null),isEnriched:A.boolean().nullable().default(null),isConnectable:A.boolean().nullable().default(null),lastConnectionAttemptedAt:A.coerce.date().nullable().default(null),lastConnectionError:UH,homepage:M2,transport:Kw1,source_registry:A.any(),categories:A.array(A.string()).nullable().default(null),tools:A.array(vJ0).nullable().default(null),parameters:A.array(xJ0),readme:UH}),SJ0=A.object({name:A.literal("registry"),entryId:M2,entryData:IJ0}),ZH=A.object({name:TJ0,transport:Kw1,source:SJ0.optional(),add_prefix:A.boolean().default(!1).optional()}),dJ0=A.object({id:M2,name:M2,description:UH,servers:A.array(ZH)}),Vw1=A.object({proxies:A.array(dJ0)});var $H=z1(Hw1(),1);async function PY(D){let F=await HE(D);return Vw1.parse(F)}async function xY(D,F){return await t4(D,F)}class MH{filePath;constructor(D){this.filePath=D}static async connect(D){let F=new MH(D);if(!_J0(D))await xY(D,{proxies:[]});return F}async addProxy(D){let F=await PY(this.filePath);if(F.proxies.find((p)=>p.name===D.name))throw new Error("Proxy already exists");let J={...D,servers:(D.servers||[]).map((p)=>({...p,name:$H.default(p.name,{lower:!0,strict:!0,trim:!0})})),id:$H.default(D.name,{lower:!0,strict:!0,trim:!0})};return F.proxies.push(J),await xY(this.filePath,F),J}async getProxy(D){let w=(await PY(this.filePath)).proxies.find((J)=>J.id===D);if(!w)throw new Error("Proxy not found");return w}async deleteProxy(D){let F=await PY(this.filePath);if(!F.proxies.find((J)=>J.id===D))throw new Error("Proxy not found");F.proxies=F.proxies.filter((J)=>J.id!==D),await xY(this.filePath,F)}async updateProxy(D,F){let w=await PY(this.filePath),J=w.proxies.find((p)=>p.id===D);if(!J)throw new Error("Proxy not found");return Object.assign(J,{...F,servers:(F.servers||J.servers||[]).map((p)=>({...p,name:$H.default(p.name,{lower:!0,trim:!0})}))}),await xY(this.filePath,w),J}async getAll(){return(await PY(this.filePath)).proxies}async purge(){await xY(this.filePath,{proxies:[]})}}var b7=q1("ProxyServerStore");class qH{proxyServers=new Map;db;telemetry;constructor(D){this.db=D.db,this.telemetry=D.telemetry||F5.noTelemetry()}static async create(D,F){b7.debug("initializing ProxyServerStore");let w=new qH({db:D,telemetry:F});return await w.initialize(),b7.debug("initialization complete"),w}async initialize(){let D=await this.db.getAll();for(let F of D){let w=F.id;b7.debug({message:`initializing ${w}`,proxyId:w});let J=new nF({id:w,name:F.name,description:F.description??void 0,servers:F.servers});await J.connectTargets(),this.proxyServers.set(w,J)}}get(D){let F=this.proxyServers.get(D);if(!F)throw new O1("NOT_FOUND",`proxy server '${D}' not found or failed to initialize.`);return F}async delete(D){this.telemetry.trackEvent("proxy_deleted"),await this.get(D).close(),await this.db.deleteProxy(D),this.proxyServers.delete(D),b7.info(`successfully deleted proxy server configuration: ${D}`)}async purge(){await this.closeAll(),await this.db.purge(),this.proxyServers.clear()}async closeAll(){b7.info("cleaning up all proxy servers..."),await Promise.all(Array.from(this.proxyServers.values()).map((D)=>D.close())),b7.info("finished cleaning up all proxy servers.")}getAll(){return Array.from(this.proxyServers.values())}async create({name:D,description:F,servers:w,source:J}){this.telemetry.trackEvent("proxy_created");let p=await this.db.addProxy({name:D,description:F,servers:w??[]}),B=new nF({name:D,id:p.id,servers:p.servers,description:p.description??void 0});return await B.connectTargets(),this.proxyServers.set(p.id,B),b7.info({message:"Created new proxy",proxyId:p.id}),B}async addServer(D,F){this.telemetry.trackEvent("server_added");let w=this.get(D);return await w.addTarget(F,{throwOnError:!0}),await this.db.updateProxy(D,{servers:w.attributes.servers}),w}async removeServer(D,F){this.telemetry.trackEvent("server_removed");let w=this.get(D);return await w.removeTarget(F),await this.db.updateProxy(D,{servers:w.attributes.servers}),w}async update(D,F){this.telemetry.trackEvent("proxy_updated");let w=this.get(D);return await w.update(F),await this.db.updateProxy(D,F),w}}var Gw1=z1(A9(),1),uw1=z1(uW(),1),jJ0="4mb";async function Nw1(D){let F=Gw1.default.parse(D.headers["content-type"]??"");if(F.type!=="application/json")throw new Error(`Unsupported content-type: ${F}`);let w=await uw1.default(D,{limit:jJ0,encoding:F.parameters.charset??"utf-8"});return JSON.parse(w)}var zw1=z1(ZB(),1),AH=q1("mcp/sse"),Uw1=({proxyStore:D,telemetry:F})=>{let w=zw1.default.Router(),J=new Map;return w.get("/:proxy_id/sse",Ew(async(p,B)=>{let Y=p.params.proxy_id,Q=D.get(Y),X=new NW(`/${Q.id}/message`,B);J.set(X.sessionId,X),AH.info({message:"SSE connection started",sessionId:X.sessionId,proxyId:Q.id,userAgent:p.headers["user-agent"],host:p.headers.host}),F.trackEvent("connection_started",{transport:"sse"}),p.socket.on("close",()=>{AH.info({message:"SSE connection closed",sessionId:X.sessionId,proxyId:Q.id}),J.delete(X.sessionId)}),await Q.connect(X)})),w.post("/:proxy_id/message",Ew(async(p,B)=>{let Y=p.params.proxy_id,Q=D.get(Y),X=p.query.sessionId?.toString();if(!X)throw new O1("BAD_REQUEST","No sessionId provided");let W=await Nw1(p);AH.info({message:"Message received",proxyId:Q.id,sessionId:X,method:W.method,params:W.params});let K=J.get(X);if(!K)throw AH.warn({message:"Transport not found",sessionId:X,proxyId:Q.id}),new O1("NOT_FOUND","Transport not found");F.trackEvent("method_called",{method:W.method,transport:"sse"}),await K.handlePostMessage(p,B,W)})),w};var $L=z1(ZB(),1),vY=q1("mcp/streamable"),Zw1=({proxyStore:D,telemetry:F})=>{let w=$L.default.Router(),J=new Map;w.use($L.default.json()),w.post("/:proxy_id/mcp",Ew(async(B,Y)=>{let Q=B.params.proxy_id,X=await D.get(Q),W=B.headers["mcp-session-id"],K;if(W&&J.has(W)){let H=J.get(W);if(!H)throw new O1("NOT_FOUND","Transport not found");K=H}else if(!W&&Ep(B.body))vY.info(`[${X.id}] new initialization request`),F.trackEvent("connection_started",{transport:"streamable"}),K=new UW({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:(H)=>{J.set(H,K)}}),K.onclose=()=>{if(vY.info(`[${X.id}] transport closed`,{proxyId:X.id,sessionId:K.sessionId}),K.sessionId)J.delete(K.sessionId)},B.socket.on("close",()=>{vY.info(`[${X.id}] socket closed'`,{proxyId:X.id,sessionId:K.sessionId})}),await X.connect(K);else throw new O1("BAD_REQUEST","No valid session ID provided");vY.info({message:`[${X.id}] '${B.body.method}' called`,proxyId:X.id,sessionId:K.sessionId,method:B.body.method,body:B.body}),F.trackEvent("method_called",{method:B.body.method,transport:"streamable"}),await K.handleRequest(B,Y,B.body)}));let p=Ew(async(B,Y)=>{let Q=B.params.proxy_id,X=D.get(Q),W=B.headers["mcp-session-id"];if(!W||!J.has(W))throw new O1("BAD_REQUEST","Invalid or missing session ID");let K=J.get(W);if(!K)throw new O1("NOT_FOUND","Transport not found");let H=K;vY.info({message:"MCP handleSessionRequest",proxyId:X.id,sessionId:H.sessionId,body:B.body}),await H.handleRequest(B,Y)});return w.get("/:proxy_id/mcp",p),w.delete("/:proxy_id/mcp",p),w};function fJ0(D,F){if("body"in D){if(D.body===void 0)return;if(typeof D.body==="string")return D.body;return JSON.stringify(D.body)}let w=0,J=!1;return new ReadableStream({start(p){let B=(Q)=>{if(w+=Q.length,!F.maxBodySize||w<=F.maxBodySize){p.enqueue(new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength));return}p.error(new K0({code:"PAYLOAD_TOO_LARGE"})),J=!0,D.off("data",B),D.off("end",Y)},Y=()=>{if(J)return;J=!0,D.off("data",B),D.off("end",Y),p.close()};D.on("data",B),D.on("end",Y)},cancel(){D.destroy()}})}function mJ0(D){try{var F,w;let J=D.headers[":scheme"]&&D.headers[":scheme"]==="https"||D.socket&&"encrypted"in D.socket&&D.socket.encrypted?"https:":"http:",p=(F=(w=D.headers.host)!==null&&w!==void 0?w:D.headers[":authority"])!==null&&F!==void 0?F:"localhost";return new URL(D.url,`${J}//${p}`)}catch(J){throw new K0({code:"BAD_REQUEST",message:"Invalid URL",cause:J})}}function kJ0(D){let F=new Headers;for(let w in D){let J=D[w];if(typeof w==="string"&&w.startsWith(":"))continue;if(Array.isArray(J))for(let p of J)F.append(w,p);else if(J!=null)F.append(w,J)}return F}function bJ0(D,F,w){let J=new AbortController,p=()=>{F.off("close",p),D.off("aborted",p),J.abort()};F.once("close",p),D.once("aborted",p);let B=mJ0(D),Y={headers:kJ0(D.headers),method:D.method,signal:J.signal};if(D.method!=="GET"&&D.method!=="HEAD")Y.body=fJ0(D,w),Y.duplex="half";return new Request(B,Y)}async function hJ0(D,F){if(D.write(F)===!1)await new Promise((w,J)=>{let p=(Q)=>{J(Q),Y()},B=()=>{w(),Y()},Y=()=>{D.off("error",p),D.off("drain",B)};D.once("error",p),D.once("drain",B)})}async function yJ0(D){let{res:F}=D;try{let w=new WritableStream({async write(J){var p;await hJ0(F,J),(p=F.flush)===null||p===void 0||p.call(F)}});await D.body.pipeTo(w,{signal:D.signal})}catch(w){if(LE(w))return;throw w}}async function iJ0(D){let{response:F,rawResponse:w}=D;if(w.statusCode===200)w.statusCode=F.status;for(let[J,p]of F.headers)w.setHeader(J,p);try{if(F.body)await yJ0({res:w,signal:D.request.signal,body:F.body})}catch(J){if(!w.headersSent)w.statusCode=500;throw J}finally{w.end()}}var Rw=y1(G6(),1);function ML(D){return(F)=>{var w;let{res:J,req:p}=D,B=D6(F),Y=_8({config:D.router._def._config,error:B,type:"unknown",path:void 0,input:void 0,ctx:void 0});(w=D.onError)===null||w===void 0||w.call(D,{req:p,error:B,type:"unknown",path:void 0,input:void 0,ctx:void 0});let Q=a5(D.router._def._config,{error:Y});J.statusCode=Y.data.httpStatus,J.end(JSON.stringify(Q))}}async function $w1(D){return new Promise((F)=>{var w;let J=(w=D.middleware)!==null&&w!==void 0?w:(p,B,Y)=>Y();return D.res.once("finish",()=>{F()}),J(D.req,D.res,(p)=>{e4(async()=>{var B;let Y=bJ0(D.req,D.res,{maxBodySize:(B=D.maxBodySize)!==null&&B!==void 0?B:null}),Q=async(W)=>{var K;return await((K=D.createContext)===null||K===void 0?void 0:K.call(D,Rw.default(Rw.default({},D),W)))},X=await Eb(Rw.default(Rw.default({},D),{},{req:Y,error:p?D6(p):null,createContext:Q,onError(W){var K;D===null||D===void 0||(K=D.onError)===null||K===void 0||K.call(D,Rw.default(Rw.default({},W),{},{req:D.req}))}}));await iJ0({request:Y,response:X,rawResponse:D.res})}).catch(ML(D))})})}var qL=y1(G6(),1);function Mw1(D){return(F,w)=>{let J="";e4(async()=>{J=F.path.slice(F.path.lastIndexOf("/")+1),await $w1(qL.default(qL.default({},D),{},{req:F,res:w,path:J}))}).catch(ML(qL.default({req:F,res:w,path:J},D)))}}function qw1({proxyStore:D}){return v0.router({allClients:v0.procedure.query(()=>yD()),byProxy:v0.router({list:v0.procedure.input(A.object({proxyId:A.string()})).query(async({input:F})=>{return await Mk(F.proxyId)}),install:v0.procedure.input(A.object({client:A.nativeEnum(cJ),proxyId:A.string(),baseUrl:A.string()})).mutation(async({input:F})=>{let w=D.get(F.proxyId);await(await y2(F.client)).install({name:w.id,url:c6(F.baseUrl,YY(w.id))})}),uninstall:v0.procedure.input(A.object({client:A.nativeEnum(cJ),proxyId:A.string()})).mutation(async({input:F})=>{let w=D.get(F.proxyId);await(await y2(F.client)).uninstall(w.id)})})})}function Aw1({registryURL:D,proxyStore:F}){let w=NV(D);return v0.router({getEntries:v0.procedure.input(A.object({pageIndex:A.number().min(0),pageSize:A.number().min(1)})).query(({input:J})=>w.entries.getEntries.query(J)),getEntryByName:v0.procedure.input(A.object({name:A.string()})).query(({input:J})=>w.entries.getEntryByName.query(J)),getTransportForEntry:v0.procedure.input(A.object({entryName:A.string(),parameters:A.record(A.string(),A.string()).optional()})).mutation(async({input:J})=>{return await w.entries.getTransportForEntry.query({entryName:J.entryName,parameters:J.parameters})})})}var Cw1=A.object({name:A.string(),description:A.string().optional(),servers:A.array(ZH).optional()}),lJ0=Cw1.omit({servers:!0}).partial();function Ow1({proxyStore:D}){return v0.router({getAll:v0.procedure.query(async()=>{return(await D.getAll()).map((F)=>({...F.toPlainObject(),path:BY(F.id)}))}),get:v0.procedure.input(A.object({proxyId:A.string()})).query(({input:F})=>{return{...D.get(F.proxyId).toPlainObject(),path:BY(F.proxyId)}}),create:v0.procedure.input(Cw1).mutation(async({input:F})=>{return(await D.create({name:F.name,description:F.description??void 0,servers:F.servers})).toPlainObject()}),update:v0.procedure.input(A.object({proxyId:A.string(),attributes:lJ0})).mutation(async({input:F})=>{return(await D.update(F.proxyId,{name:F.attributes.name,description:F.attributes.description??void 0})).toPlainObject()}),delete:v0.procedure.input(A.object({proxyId:A.string()})).mutation(async({input:F})=>{return await D.delete(F.proxyId),{success:!0}}),addServer:v0.procedure.input(A.object({proxyId:A.string(),server:ZH})).mutation(async({input:F})=>{let w=await D.addServer(F.proxyId,F.server);return await MC(w),w.toPlainObject()}),purge:v0.procedure.mutation(()=>D.purge()),removeServer:v0.procedure.input(A.object({proxyId:A.string(),serverName:A.string()})).mutation(async({input:F})=>{let w=await D.removeServer(F.proxyId,F.serverName);return await MC(w),w.toPlainObject()})})}function gJ0({proxyStore:D,registryURL:F}){return v0.router({health:v0.procedure.query(()=>Yw()),store:Ow1({proxyStore:D}),installer:qw1({proxyStore:D}),registry:Aw1({registryURL:F,proxyStore:D})})}function Lw1({proxyStore:D,registryURL:F}){return Mw1({router:gJ0({proxyStore:D,registryURL:F})})}var AL=q1("Gateway");class CH{proxyStore;port;server;constructor(D){this.port=D.port,this.proxyStore=D.proxyStore,this.server=D.server}static async start(D,F){AL.info("starting director gateway");let w=await MH.connect(D.databaseFilePath),J=D.telemetry||F5.noTelemetry(),p=await qH.create(w,J),B=Rw1.default(),Y=D.registryURL;B.use(Tw1.default({origin:D.allowedOrigins})),B.use(j61()),B.use("/",Uw1({proxyStore:p,telemetry:J})),B.use("/",Zw1({proxyStore:p,telemetry:J})),B.use("/trpc",Lw1({proxyStore:p,registryURL:Y})),B.all("*",_61),B.use(d61),J.trackEvent("gateway_start");let Q=B.listen(D.port,()=>{AL.info(`director gateway running on port ${D.port}`),F?.()}),X=new CH({port:D.port,db:w,proxyStore:p,server:Q});return process.on("SIGINT",async()=>{AL.info("received SIGINT, cleaning up proxy servers..."),await X.stop(),process.exit(0)}),X}async stop(){await this.proxyStore.closeAll(),await new Promise((D)=>{this.server.closeAllConnections(),this.server.close(()=>D())})}}function Pw1(D){D.command("serve").description("Start the web service").action(_1(async()=>{try{await CL()}catch(F){console.error("Fatal error starting gateway",F),process.exit(1)}}))}async function CL(D){console.log(`v${K9.version}`),Oh(),await CH.start({port:Q0.GATEWAY_PORT,databaseFilePath:Q0.CONFIG_FILE_PATH,registryURL:Q0.REGISTRY_API_URL,allowedOrigins:[Q0.STUDIO_URL,/^https?:\/\/localhost(:\d+)?$/],telemetry:new F5({writeKey:Q0.SEGMENT_WRITE_KEY,enabled:Q0.SEND_TELEMETRY,traits:{cliVersion:K9.version}})},D)}function xw1(D){D.command("studio").description("Open the UI in your browser").action(_1(async()=>{let F=tB();F.start("opening studio...");try{await I2.health.query()}catch(w){F.fail("Failed to connect to gateway. Have you ran `director serve`?"),process.exit(1)}try{OL()}catch(w){F.fail(`failed to open ${Q0.STUDIO_URL}, try manually`)}F.stop()}))}async function OL(){await T61(Q0.STUDIO_URL)}var aJ0=q1("quickstart");function Iw1(D){D.command("quickstart").description("Start the gateway and open the studio in your browser").action(_1(async()=>{await nJ0(),await CL(async()=>{aJ0.info(`gateway started, opening ${Q0.STUDIO_URL} in your browser...`),await OL()})}))}async function nJ0(){let D=tB();D.start("checking prerequisites...");let F=await Yw();D.stop();let w=[],J=[];w.push(""),w.push(G2("Dependency Check")),w.push("The following dependencies are required by some MCP servers that use Stdout. It's best to have them all installed."),w.push("");for(let Y of F.dependencies)w.push(vw1({name:Y.name,installed:Y.installed,successText:`${Y.name} is installed`,failureText:`${Y.name} is not available in $PATH. ${oJ0(Y)}`}));if(F.dependencies.filter((Y)=>Y.installed).length<F.dependencies.length)J.push("Some dependencies are not available in $PATH, MCP servers that depend on them will not work.");w.push(""),w.push(G2("MCP Clients Check")),w.push("Director can automatically configure the following MCP clients for you. It's best to have at least one installed."),w.push("");for(let Y of F.clients)w.push(vw1({name:Y.name,installed:Y.installed}));if(F.clients.filter((Y)=>Y.installed).length===0)J.push("No MCP clients found. It's best to have at least one MCP client installed in order to use the automatic client configuration.");if(w.push(""),w.push(G2("Summary")),w.push(""),console.log(w.join(`
624
624
  `)),J.length>0)if(console.log(J.map((Q)=>`${z5("✗")} ${z5(Q)}`).join(`
625
625
  `)),console.log(""),await $C({message:"Would you like to continue with a degraded experience?",choices:["No","Yes"]})==="Yes")console.log(QJ("Continuing with a degraded experience..."));else console.log("Exiting..."),process.exit(1);else console.log(QJ("All systems go!")),console.log("")}function vw1(D){let F=`[${D.installed?QJ("✓"):z5("✗")}]`,w=D.successText??`${D.name} is installed`,J=D.failureText??`${D.name} is not installed`;return`${F} ${D.installed?w:J}`}function oJ0(D){switch(D.name){case"npx":return"Follow the installation instructions here: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm.";case"uvx":return"Follow the installation instructions here: https://docs.astral.sh/uv/getting-started/installation/.";default:return}}function Sw1(D){return D.command("remove <proxyId> <serverName>").description("Remove a server from a proxy").action(_1(async(F,w)=>{let J=await l6(()=>I2.store.removeServer.mutate({proxyId:F,serverName:w})).start("removing server...").succeed(`Server ${w} removed from ${F}`).run()}))}function dw1(D){D.command("status").description("Get the status of the director").action(_1(async()=>{let F=await Yw();console.log(F)}))}function _w1(D){Iw1(D),Pw1(D),xw1(D),D.command("ls").alias("list").description("List proxies").action(_1(async()=>{let F=await I2.store.getAll.query();if(F.length===0)console.log("no proxies configured yet.");else{let w=L3(["id","name","path"]);w.push(...F.map((J)=>[J.id,J.name,c6(Q0.GATEWAY_URL,J.path)])),console.log(w.toString())}})),D.command("get <proxyId>").description("Show proxy details").action(_1(async(F)=>{let w=await I2.store.get.query({proxyId:F});if(!w){console.error(`proxy ${F} not found`);return}console.log(`id=${w.id}`),console.log(`name=${w.name}`);let J=L3(["name","transport","url/command"]);J.push(...w.servers.map((p)=>[p.name,p.transport.type,p.transport.type==="http"?p.transport.url:[p.transport.command,...p.transport.args??[]].join(" ")])),console.log(J.toString())})),D.command("create <name>").description("Create a new proxy").action(_1(async(F)=>{let w=await I2.store.create.mutate({name:F,servers:[]});console.log(`proxy ${w.id} created`)})),D.command("destroy <proxyId>").description("Delete a proxy").action(_1(async(F)=>{await I2.store.delete.mutate({proxyId:F}),console.log(`proxy ${F} deleted`)})),C61(D),D.command("disconnect <proxyId>").description("Disconnect a proxy from an MCP client").addOption(L8({flags:"-t,--target <target>",description:"target client",choices:["claude","cursor","vscode"]}).makeOptionMandatory()).action(_1(async(F,w)=>{let J=await I2.store.get.query({proxyId:F}),B=await(await y2(w.target)).uninstall(J.id);console.log(B)})),q61(D),Sw1(D),D.command("http2stdio <url>").description("Proxy an HTTP connection (sse or streamable) to a stdio stream").action(async(F)=>{await k01(F)}),L61(D),dw1(D),O61(D)}var OH=q1("enrich/tools");async function jw1(D){let F=await D.entries.getEntries.query({pageIndex:0,pageSize:100});for(let w of F.entries){if(w.lastConnectionAttemptedAt){OH.info(`skipping ${w.name}, already processed`);continue}let J;try{J=await sJ0(w)}catch(p){let B=p instanceof Error?p.message:String(p);OH.error(`error enriching ${w.name}: ${B}`),await D.entries.updateEntry.mutate({id:w.id,isConnectable:!1,lastConnectionAttemptedAt:new Date,lastConnectionError:B});continue}await D.entries.updateEntry.mutate({id:w.id,isConnectable:!0,lastConnectionAttemptedAt:new Date,lastConnectionError:void 0,tools:J})}}async function sJ0(D){let F=D.transport,w=new s8(`${D.name}-client`);if(F.type==="stdio")await w.connectToStdio(F.command,F.args,{...process.env,...F.env});else if(F.type==="http")await w.connectToHTTP(F.url);else return[];OH.info(`connected to ${D.name}, fetching tools...`);let J=(await w.listTools()).tools.map(({name:p,description:B,inputSchema:Y})=>({name:p,description:B??"",inputSchema:{type:"object",properties:Y?.properties??{},required:Y?.required}}));return OH.info(`closing client ${D.name}`),await w.close(),J}function fw1(D){console.log(`
626
626
  ${G2(D.name.toUpperCase())}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@director.run/cli",
3
3
  "type": "module",
4
- "version": "0.0.43",
4
+ "version": "0.0.44",
5
5
  "files": ["dist", "README.md"],
6
6
  "bin": {
7
7
  "director": "./dist/cli.js"