@smithery/cli 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -58,7 +58,7 @@ Calls to async() callback can have unexpected results.`),f=!0,function(y,m){y?c(
|
|
|
58
58
|
`+ia.red(">> ")+e),this.firstRender=!1,this.screen.render(t,n)}onSubmit(e){let t=e||this.rl.line;if(this.opt.suggestOnly&&!t&&(t=this.opt.default===null?"":this.opt.default),typeof this.opt.validate=="function"){let n=a=>{a!==!0?this.render(a||"Enter something, tab to autocomplete!"):this.onSubmitAfterValidation(t)},i;if(this.opt.suggestOnly)i=this.opt.validate(t,this.answers);else{let a=this.currentChoices.getChoice(this.selected);i=this.opt.validate(a,this.answers)}Dse(i)?i.then(n):n(i)}else this.onSubmitAfterValidation(t)}onSubmitAfterValidation(e){let t={};if(this.nbChoices<=this.selected&&!this.opt.suggestOnly){this.rl.write(e),this.search(e);return}if(this.opt.suggestOnly)t.value=e||this.rl.line,this.answer=e||this.rl.line,this.answerName=e||this.rl.line,this.shortAnswer=e||this.rl.line,this.rl.line="";else if(this.nbChoices)t=this.currentChoices.getChoice(this.selected),this.answer=t.value,this.answerName=t.name,this.shortAnswer=t.short;else{this.rl.write(e),this.search(e);return}gse(this.opt.filter,(n,i)=>{t.value=i,this.answer=i,this.opt.suggestOnly&&(this.shortAnswer=i),this.status="answered",this.render(),this.screen.done(),this.done(t.value)})(t.value)}search(e){this.selected=0,this.searchedOnce?(this.searching=!0,this.currentChoices=new ym([]),this.render()):this.searchedOnce=!0,this.lastSearchTerm=e;let t;try{let n=this.opt.source(this.answers,e);t=Promise.resolve(n)}catch(n){t=Promise.reject(n)}return this.lastPromise=t,t.then(n=>{if(t!==this.lastPromise)return;this.currentChoices=new ym(n);let i=n.filter(o=>_se(o));this.nbChoices=i.length;let a=i.findIndex(o=>o===this.initialValue||o.value===this.initialValue);a>=0&&(this.selected=a),this.searching=!1,this.render()})}ensureSelectedInRange(){let e=Math.min(this.selected,this.nbChoices);this.selected=Math.max(e,0)}onKeypress(e){let t,n=e.key&&e.key.name||void 0;if(n==="tab"&&this.opt.suggestOnly){if(this.currentChoices.getChoice(this.selected)){this.rl.write(GS.cursorLeft);let i=this.currentChoices.getChoice(this.selected).value;this.rl.write(GS.cursorForward(i.length)),this.rl.line=i,this.render()}}else n==="down"||n==="n"&&e.key.ctrl?(t=this.nbChoices,this.selected=this.selected<t-1?this.selected+1:0,this.ensureSelectedInRange(),this.render(),bse.up(this.rl,2)):n==="up"||n==="p"&&e.key.ctrl?(t=this.nbChoices,this.selected=this.selected>0?this.selected-1:t-1,this.ensureSelectedInRange(),this.render()):(this.render(),this.lastSearchTerm!==this.rl.line&&this.search(this.rl.line))}};function Ese(r,e){let t="",n=0;return r.forEach((i,a)=>{if(i.type==="separator"){n++,t+=" "+i+`
|
|
59
59
|
`;return}if(i.disabled){n++,t+=" - "+i.name,t+=" ("+(typeof i.disabled=="string"?i.disabled:"Disabled")+")",t+=`
|
|
60
60
|
`;return}let o=a-n===e,s=(o?xse.pointer+" ":" ")+i.name;o&&(s=ia.cyan(s)),t+=s+`
|
|
61
|
-
`}),t.replace(/\n$/,"")}function Dse(r){return typeof r=="object"&&typeof r.then=="function"}HS.exports=gm});var rf=K(Z());var Tn=K(require("node:fs")),Pb=K(require("node:os")),Ce=K(require("node:path")),Se=class r{static{let e=Pb.default.homedir(),t={win32:{baseDir:process.env.APPDATA||Ce.default.join(e,"AppData","Roaming"),vscodePath:Ce.default.join("Code","User","globalStorage")},darwin:{baseDir:Ce.default.join(e,"Library","Application Support"),vscodePath:Ce.default.join("Code","User","globalStorage")},linux:{baseDir:process.env.XDG_CONFIG_HOME||Ce.default.join(e,".config"),vscodePath:Ce.default.join("Code/User/globalStorage")}},n=process.platform,{baseDir:i,vscodePath:a}=t[n],o={claude:Ce.default.join(i,"Claude","claude_desktop_config.json"),cline:Ce.default.join(i,a,"saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),"roo-cline":Ce.default.join(i,a,"rooveterinaryinc.roo-cline","settings","cline_mcp_settings.json")};r.configPath=o.claude,r.clientPaths=o}static getConfigPath(e){let t=e?.toLowerCase()||"claude";return r.clientPaths[t]||Ce.default.join(Ce.default.dirname(r.configPath),"..",e||"claude",`${t}_config.json`)}static readConfig(e){try{let t=r.getConfigPath(e);return Tn.default.existsSync(t)?{mcpServers:JSON.parse(Tn.default.readFileSync(t,"utf8")).mcpServers||{}}:{mcpServers:{}}}catch{return{mcpServers:{}}}}static writeConfig(e,t){let n=r.getConfigPath(t),i=Ce.default.dirname(n);if(Tn.default.existsSync(i)||Tn.default.mkdirSync(i,{recursive:!0}),!e.mcpServers||typeof e.mcpServers!="object")throw new Error("Invalid config structure");Tn.default.writeFileSync(n,JSON.stringify(e,null,2))}static isServerInstalled(e,t){let n=r.readConfig(t);return r.normalizeServerId(e)in n.mcpServers}static async installServer(e,t,n){let i=r.normalizeServerId(e),a=r.readConfig(n);a.mcpServers[i]=t,r.writeConfig(a,n)}static async uninstallServer(e,t){let n=r.normalizeServerId(e),i=r.readConfig(t);if(!i.mcpServers[n]){console.log(`Server ${n} not found in configuration`);return}delete i.mcpServers[n],r.writeConfig(i,t)}static getServerConfig(e,t){return r.readConfig(t).mcpServers[e]||null}static envVarsToArgs(e){return Object.entries(e).flatMap(([t,n])=>[`--${t.toLowerCase().replace(/_/g,"-")}`,n])}static normalizeServerId(e){if(e.startsWith("@")){let t=e.indexOf("/");if(t!==-1)return`${e.substring(0,t)}-${e.substring(t+1)}`}return e}static denormalizeServerId(e){if(e.startsWith("@")){let t=e.indexOf("-");if(t!==-1)return`${e.substring(0,t)}/${e.substring(t+1)}`}return e}static getInstalledServerIds(e){let t=r.readConfig(e);return Object.keys(t.mcpServers||{})}};var FS=require("node:child_process"),OS=require("node:util"),qS=K(Et()),jr=(0,OS.promisify)(FS.exec);async function Hoe(r){if(!r)return!1;try{let e=process.platform,t={claude:"Claude"}[r]||r;if(e==="win32"){let{stdout:n}=await jr(`tasklist /FI "IMAGENAME eq ${t}.exe" /NH`);return n.includes(`${t}.exe`)}else if(e==="darwin"){let{stdout:n}=await jr(`pgrep -x "${t}"`);return!!n.trim()}else if(e==="linux"){let{stdout:n}=await jr(`pgrep -f "${t.toLowerCase()}"`);return!!n.trim()}return!1}catch{return!1}}async function Koe(r){let e={claude:"Claude",jan:"Jan"}[r]||r;try{let t=process.platform;t==="win32"?await jr(`taskkill /F /IM "${e}.exe" && start "" "${e}.exe"`):t==="darwin"?await jr(`killall "${e}" && open -a "${e}"`):t==="linux"&&await jr(`pkill -f "${e.toLowerCase()}" && ${e.toLowerCase()}`),await new Promise(n=>setTimeout(n,2e3)),t==="win32"?await jr(`start "" "${e}.exe"`):t==="darwin"?await jr(`open -a "${e}"`):t==="linux"&&await jr(e.toLowerCase()),console.log(`${e} has been restarted.`)}catch(t){console.error(`Failed to restart ${e}:`,t)}}async function dm(r){if(!r||!await Hoe(r))return!1;let{shouldRestart:t}=await qS.default.prompt([{type:"confirm",name:"shouldRestart",message:`Would you like to restart the ${r} app to apply changes?`,default:!0}]);return t&&(console.log(`Restarting ${r} app...`),await Koe(r)),t}var AS=require("node:child_process"),TS=require("node:util"),hm=K(Et()),pm=K(Z()),Hme=(0,TS.promisify)(AS.exec);async function Ql(r,e){let t=new Map;if(r.configSchema?.properties){let a=new Set(r.configSchema.required||[]);Object.entries(r.configSchema.properties).forEach(([o,s])=>{let u=s;t.set(o,{key:o,description:u.description||`Enter value for ${o}`,required:a.has(o),default:u.default,type:u.type})})}let n={};function i(a,o){if(!o)return a;if(a==="")switch(o){case"array":return[];case"number":case"integer":return null;default:return a}if(!a)return a;switch(o){case"boolean":return String(a).toLowerCase()==="true";case"number":return Number(a);case"integer":return Number.parseInt(String(a),10);case"array":return String(a).split(",").map(s=>s.trim()).filter(s=>s!=="");default:return a}}if(e){for(let a of t.values()){let o=e[a.key];if(o!==void 0||a.default!==void 0)n[a.key]=i(o??a.default,a.type);else if(a.required)throw new Error(`Missing required config value: ${a.key}`)}return n}for(let a of t.values()){if(process.env[a.key]&&!a.required){let{reuseExisting:c}=await hm.default.prompt([{type:"confirm",name:"reuseExisting",message:`Found ${a.key} in environment. Use it?`,default:!0}]);if(c){n[a.key]=i(process.env[a.key],a.type);continue}}let o=a.required?pm.default.red(" (required)"):pm.default.gray(" (optional)"),s=a.key.toLowerCase().includes("key")?"password":a.type==="boolean"?"confirm":a.type==="array"?"input":a.type==="number"||a.type==="integer"?"number":"input",{value:u}=await hm.default.prompt([{type:s,name:"value",message:`${a.description}${o}${a.type==="array"?" (comma-separated)":""}`,default:a.default,mask:s==="password"?"*":void 0,validate:c=>a.required&&!c?!1:a.type==="number"||a.type==="integer"?!Number.isNaN(Number(c))||"Please enter a valid number":!0}]);(u!==void 0||a.default!==void 0)&&(n[a.key]=i(u??a.default,a.type))}return n}var Dt=class{constructor(e=Se){this.configManager=e}selectPreferredConnection(e){if(!e.connections?.length)throw new Error("No connection configuration found");let t=e.connections.find(n=>n.type==="sse");return t||e.connections[0]}formatServerConfig(e,t){return{command:"npx",args:["-y","@smithery/cli","run",e,"--config",
|
|
61
|
+
`}),t.replace(/\n$/,"")}function Dse(r){return typeof r=="object"&&typeof r.then=="function"}HS.exports=gm});var rf=K(Z());var Tn=K(require("node:fs")),Pb=K(require("node:os")),Ce=K(require("node:path")),Se=class r{static{let e=Pb.default.homedir(),t={win32:{baseDir:process.env.APPDATA||Ce.default.join(e,"AppData","Roaming"),vscodePath:Ce.default.join("Code","User","globalStorage")},darwin:{baseDir:Ce.default.join(e,"Library","Application Support"),vscodePath:Ce.default.join("Code","User","globalStorage")},linux:{baseDir:process.env.XDG_CONFIG_HOME||Ce.default.join(e,".config"),vscodePath:Ce.default.join("Code/User/globalStorage")}},n=process.platform,{baseDir:i,vscodePath:a}=t[n],o={claude:Ce.default.join(i,"Claude","claude_desktop_config.json"),cline:Ce.default.join(i,a,"saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),"roo-cline":Ce.default.join(i,a,"rooveterinaryinc.roo-cline","settings","cline_mcp_settings.json")};r.configPath=o.claude,r.clientPaths=o}static getConfigPath(e){let t=e?.toLowerCase()||"claude";return r.clientPaths[t]||Ce.default.join(Ce.default.dirname(r.configPath),"..",e||"claude",`${t}_config.json`)}static readConfig(e){try{let t=r.getConfigPath(e);return Tn.default.existsSync(t)?{mcpServers:JSON.parse(Tn.default.readFileSync(t,"utf8")).mcpServers||{}}:{mcpServers:{}}}catch{return{mcpServers:{}}}}static writeConfig(e,t){let n=r.getConfigPath(t),i=Ce.default.dirname(n);if(Tn.default.existsSync(i)||Tn.default.mkdirSync(i,{recursive:!0}),!e.mcpServers||typeof e.mcpServers!="object")throw new Error("Invalid config structure");Tn.default.writeFileSync(n,JSON.stringify(e,null,2))}static isServerInstalled(e,t){let n=r.readConfig(t);return r.normalizeServerId(e)in n.mcpServers}static async installServer(e,t,n){let i=r.normalizeServerId(e),a=r.readConfig(n);a.mcpServers[i]=t,r.writeConfig(a,n)}static async uninstallServer(e,t){let n=r.normalizeServerId(e),i=r.readConfig(t);if(!i.mcpServers[n]){console.log(`Server ${n} not found in configuration`);return}delete i.mcpServers[n],r.writeConfig(i,t)}static getServerConfig(e,t){return r.readConfig(t).mcpServers[e]||null}static envVarsToArgs(e){return Object.entries(e).flatMap(([t,n])=>[`--${t.toLowerCase().replace(/_/g,"-")}`,n])}static normalizeServerId(e){if(e.startsWith("@")){let t=e.indexOf("/");if(t!==-1)return`${e.substring(0,t)}-${e.substring(t+1)}`}return e}static denormalizeServerId(e){if(e.startsWith("@")){let t=e.indexOf("-");if(t!==-1)return`${e.substring(0,t)}/${e.substring(t+1)}`}return e}static getInstalledServerIds(e){let t=r.readConfig(e);return Object.keys(t.mcpServers||{})}};var FS=require("node:child_process"),OS=require("node:util"),qS=K(Et()),jr=(0,OS.promisify)(FS.exec);async function Hoe(r){if(!r)return!1;try{let e=process.platform,t={claude:"Claude"}[r]||r;if(e==="win32"){let{stdout:n}=await jr(`tasklist /FI "IMAGENAME eq ${t}.exe" /NH`);return n.includes(`${t}.exe`)}else if(e==="darwin"){let{stdout:n}=await jr(`pgrep -x "${t}"`);return!!n.trim()}else if(e==="linux"){let{stdout:n}=await jr(`pgrep -f "${t.toLowerCase()}"`);return!!n.trim()}return!1}catch{return!1}}async function Koe(r){let e={claude:"Claude",jan:"Jan"}[r]||r;try{let t=process.platform;t==="win32"?await jr(`taskkill /F /IM "${e}.exe" && start "" "${e}.exe"`):t==="darwin"?await jr(`killall "${e}" && open -a "${e}"`):t==="linux"&&await jr(`pkill -f "${e.toLowerCase()}" && ${e.toLowerCase()}`),await new Promise(n=>setTimeout(n,2e3)),t==="win32"?await jr(`start "" "${e}.exe"`):t==="darwin"?await jr(`open -a "${e}"`):t==="linux"&&await jr(e.toLowerCase()),console.log(`${e} has been restarted.`)}catch(t){console.error(`Failed to restart ${e}:`,t)}}async function dm(r){if(!r||!await Hoe(r))return!1;let{shouldRestart:t}=await qS.default.prompt([{type:"confirm",name:"shouldRestart",message:`Would you like to restart the ${r} app to apply changes?`,default:!0}]);return t&&(console.log(`Restarting ${r} app...`),await Koe(r)),t}var AS=require("node:child_process"),TS=require("node:util"),hm=K(Et()),pm=K(Z()),Hme=(0,TS.promisify)(AS.exec);async function Ql(r,e){let t=new Map;if(r.configSchema?.properties){let a=new Set(r.configSchema.required||[]);Object.entries(r.configSchema.properties).forEach(([o,s])=>{let u=s;t.set(o,{key:o,description:u.description||`Enter value for ${o}`,required:a.has(o),default:u.default,type:u.type})})}let n={};function i(a,o){if(!o)return a;if(a==="")switch(o){case"array":return[];case"number":case"integer":return null;default:return a}if(!a)return a;switch(o){case"boolean":return String(a).toLowerCase()==="true";case"number":return Number(a);case"integer":return Number.parseInt(String(a),10);case"array":return String(a).split(",").map(s=>s.trim()).filter(s=>s!=="");default:return a}}if(e){for(let a of t.values()){let o=e[a.key];if(o!==void 0||a.default!==void 0)n[a.key]=i(o??a.default,a.type);else if(a.required)throw new Error(`Missing required config value: ${a.key}`)}return n}for(let a of t.values()){if(process.env[a.key]&&!a.required){let{reuseExisting:c}=await hm.default.prompt([{type:"confirm",name:"reuseExisting",message:`Found ${a.key} in environment. Use it?`,default:!0}]);if(c){n[a.key]=i(process.env[a.key],a.type);continue}}let o=a.required?pm.default.red(" (required)"):pm.default.gray(" (optional)"),s=a.key.toLowerCase().includes("key")?"password":a.type==="boolean"?"confirm":a.type==="array"?"input":a.type==="number"||a.type==="integer"?"number":"input",{value:u}=await hm.default.prompt([{type:s,name:"value",message:`${a.description}${o}${a.type==="array"?" (comma-separated)":""}`,default:a.default,mask:s==="password"?"*":void 0,validate:c=>a.required&&!c?!1:a.type==="number"||a.type==="integer"?!Number.isNaN(Number(c))||"Please enter a valid number":!0}]);(u!==void 0||a.default!==void 0)&&(n[a.key]=i(u??a.default,a.type))}return n}var Dt=class{constructor(e=Se){this.configManager=e}selectPreferredConnection(e){if(!e.connections?.length)throw new Error("No connection configuration found");let t=e.connections.find(n=>n.type==="sse");return t||e.connections[0]}formatServerConfig(e,t){let n=JSON.stringify(JSON.stringify(t));return{command:"npx",args:["-y","@smithery/cli","run",e,"--config",n]}}async installServer(e,t){let n=this.selectPreferredConnection(e),i=await Ql(n),a=this.formatServerConfig(e.id,i);await this.configManager.installServer(e.id,a,t),await dm(t)}async uninstallServer(e,t){try{await this.configManager.uninstallServer(e,t),console.log(`
|
|
62
62
|
Uninstalled ${e}`),await dm(t)}catch(n){throw console.error("Failed to uninstall server:",n),n}}};var MS=K(kS());var ve=["claude","cline","roo-cline"],ef=process.env.REGISTRY_ENDPOINT||"https://registry.smithery.ai";MS.default.config();async function BS(r,e=[]){try{if(e.length===0)return[];let t=e.map(i=>an(i,r));return(await Promise.all(t)).filter(i=>i!==null)}catch(t){throw new Error(`Failed to resolve servers: ${t instanceof Error?t.message:String(t)}`)}}async function an(r,e="claude"){try{let t=Se.isServerInstalled(r,e),n=await fetch(`${ef}/servers/${r}`);if(!n.ok)return t?{id:r,name:r,connections:[],isInstalled:!0,client:e}:null;let i=await n.json(),a=await Promise.all(i.connections.map(async s=>{if(s.type==="sse"&&s.deploymentUrl)try{let u=await fetch(`${s.deploymentUrl}/.well-known/mcp/smithery.json`);if(u.ok){let c=await u.json();return{type:"sse",deploymentUrl:s.deploymentUrl,configSchema:c.configSchema,exampleConfig:s.exampleConfig}}}catch{}return s}));return{id:i.qualifiedName,name:i.displayName,connections:a,isInstalled:t,client:e}}catch(t){return console.error("Error resolving server:",t),null}}var lse=new Dt;async function NS(r,e){e&&!ve.includes(e)&&(console.error(rf.default.red(`Invalid client: ${e}
|
|
63
63
|
Valid clients are: ${ve.join(", ")}`)),process.exit(1));let t=await an(r,e);t||(console.error(rf.default.red(`Server '${r}' not found in registry`)),process.exit(1)),await lse.installServer(t,e),console.log(rf.default.green(`\u2713 Successfully installed package '${r}' for ${e}`))}var on=K(Z()),LS=K(Et());var fse=new Dt;async function US(r,e){try{e&&!ve.includes(e)&&(console.error(on.default.red(`Invalid client: ${e}
|
|
64
64
|
Valid clients are: ${ve.join(", ")}`)),process.exit(1)),r||(console.error(on.default.red("Error: Server ID is required")),console.log("Usage: @smithery/cli uninstall <server-id>"),process.exit(1));let{confirmUninstall:t}=await LS.default.prompt([{type:"confirm",name:"confirmUninstall",message:`Are you sure you want to uninstall ${r}?`,default:!1}]);if(!t){console.log("Uninstallation cancelled.");return}await fse.uninstallServer(r,e),console.log(on.default.green(`
|
|
@@ -81,7 +81,7 @@ Connecting to server...`));let a=t.mcpServers[i.id];if("command"in a){let o=awai
|
|
|
81
81
|
`;break;case"id":s=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):t(new Af(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:_}));break;default:t(new Af(`Unknown field "${m.length>20?`${m.slice(0,20)}\u2026`:m}"`,{type:"unknown-field",field:m,value:g,line:_}));break}}function b(){u.length>0&&e({id:s,event:c||void 0,data:u.endsWith(`
|
|
82
82
|
`)?u.slice(0,-1):u}),s=void 0,u="",c=""}function y(m={}){a&&m.consume&&p(a),s=void 0,u="",c="",a=""}return{feed:f,reset:y}}function bce(r){let e=[],t="",n=r.length;for(let i=0;i<n;i++){let a=r[i];a==="\r"&&r[i+1]===`
|
|
83
83
|
`?(e.push(t),t="",i++):a==="\r"||a===`
|
|
84
|
-
`?(e.push(t),t=""):t+=a}return[e,t]}var Pf=class extends Event{};function yce(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}var OF=r=>{throw TypeError(r)},Jm=(r,e,t)=>e.has(r)||OF("Cannot "+t),k=(r,e,t)=>(Jm(r,e,"read from private field"),t?t.call(r):e.get(r)),ne=(r,e,t)=>e.has(r)?OF("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Q=(r,e,t,n)=>(Jm(r,e,"write to private field"),e.set(r,t),t),Lr=(r,e,t)=>(Jm(r,e,"access private method"),t),we,wn,Ea,Tf,jf,Yo,Ca,Jo,Ft,Da,Sa,wa,Ko,Xe,$m,Gm,zm,FF,Hm,Km,Zo,Zm,Ym,Cn=class extends EventTarget{constructor(e,t){var n,i;super(),ne(this,Xe),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ne(this,we),ne(this,wn),ne(this,Ea),ne(this,Tf),ne(this,jf),ne(this,Yo),ne(this,Ca),ne(this,Jo,null),ne(this,Ft),ne(this,Da),ne(this,Sa,null),ne(this,wa,null),ne(this,Ko,null),ne(this,Gm,async a=>{var o;k(this,Da).reset();let{body:s,redirected:u,status:c,headers:f}=a;if(c===204){Lr(this,Xe,Zo).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Q(this,Ea,new URL(a.url)):Q(this,Ea,void 0),c!==200){Lr(this,Xe,Zo).call(this,`Non-200 status code (${c})`,c);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){Lr(this,Xe,Zo).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(k(this,we)===this.CLOSED)return;Q(this,we,this.OPEN);let p=new Event("open");if((o=k(this,Ko))==null||o.call(this,p),this.dispatchEvent(p),typeof s!="object"||!s||!("getReader"in s)){Lr(this,Xe,Zo).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let v=new TextDecoder,b=s.getReader(),y=!0;do{let{done:m,value:g}=await b.read();g&&k(this,Da).feed(v.decode(g,{stream:!m})),m&&(y=!1,k(this,Da).reset(),Lr(this,Xe,Zm).call(this))}while(y)}),ne(this,zm,a=>{Q(this,Ft,void 0),!(a.name==="AbortError"||a.type==="aborted")&&Lr(this,Xe,Zm).call(this)}),ne(this,Hm,a=>{typeof a.id=="string"&&Q(this,Jo,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:k(this,Ea)?k(this,Ea).origin:k(this,wn).origin,lastEventId:a.id||""});k(this,wa)&&(!a.event||a.event==="message")&&k(this,wa).call(this,o),this.dispatchEvent(o)}),ne(this,Km,a=>{Q(this,Yo,a)}),ne(this,Ym,()=>{Q(this,Ca,void 0),k(this,we)===this.CONNECTING&&Lr(this,Xe,$m).call(this)});try{if(e instanceof URL)Q(this,wn,e);else if(typeof e=="string")Q(this,wn,new URL(e,gce()));else throw new Error("Invalid URL")}catch{throw yce("An invalid or illegal string was specified")}Q(this,Da,SF({onEvent:k(this,Hm),onRetry:k(this,Km)})),Q(this,we,this.CONNECTING),Q(this,Yo,3e3),Q(this,jf,(n=t?.fetch)!=null?n:globalThis.fetch),Q(this,Tf,(i=t?.withCredentials)!=null?i:!1),Lr(this,Xe,$m).call(this)}get readyState(){return k(this,we)}get url(){return k(this,wn).href}get withCredentials(){return k(this,Tf)}get onerror(){return k(this,Sa)}set onerror(e){Q(this,Sa,e)}get onmessage(){return k(this,wa)}set onmessage(e){Q(this,wa,e)}get onopen(){return k(this,Ko)}set onopen(e){Q(this,Ko,e)}addEventListener(e,t,n){let i=t;super.addEventListener(e,i,n)}removeEventListener(e,t,n){let i=t;super.removeEventListener(e,i,n)}close(){k(this,Ca)&&clearTimeout(k(this,Ca)),k(this,we)!==this.CLOSED&&(k(this,Ft)&&k(this,Ft).abort(),Q(this,we,this.CLOSED),Q(this,Ft,void 0))}};we=new WeakMap,wn=new WeakMap,Ea=new WeakMap,Tf=new WeakMap,jf=new WeakMap,Yo=new WeakMap,Ca=new WeakMap,Jo=new WeakMap,Ft=new WeakMap,Da=new WeakMap,Sa=new WeakMap,wa=new WeakMap,Ko=new WeakMap,Xe=new WeakSet,$m=function(){Q(this,we,this.CONNECTING),Q(this,Ft,new AbortController),k(this,jf)(k(this,wn),Lr(this,Xe,FF).call(this)).then(k(this,Gm)).catch(k(this,zm))},Gm=new WeakMap,zm=new WeakMap,FF=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...k(this,Jo)?{"Last-Event-ID":k(this,Jo)}:void 0},cache:"no-store",signal:(r=k(this,Ft))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Hm=new WeakMap,Km=new WeakMap,Zo=function(r,e){var t;k(this,we)!==this.CLOSED&&Q(this,we,this.CLOSED);let n=new Pf("error");n.code=e,n.message=r,(t=k(this,Sa))==null||t.call(this,n),this.dispatchEvent(n)},Zm=function(){var r;if(k(this,we)===this.CLOSED)return;Q(this,we,this.CONNECTING);let e=new Pf("error");(r=k(this,Sa))==null||r.call(this,e),this.dispatchEvent(e),Q(this,Ca,setTimeout(k(this,Ym),k(this,Yo)))},Ym=new WeakMap,Cn.CONNECTING=0,Cn.OPEN=1,Cn.CLOSED=2;function gce(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var Qo=class extends ma{constructor(e,t){super(t),this._serverInfo=e,this._capabilities=t.capabilities,this.setRequestHandler(Om,n=>this._oninitialize(n)),this.setNotificationHandler(Am,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}assertCapabilityForMethod(e){var t,n;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:xf.includes(t)?t:No,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Nr)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},Bm,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Lm,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Qm=K(require("node:process"),1);var Xo=class{constructor(e=Qm.default.stdin,t=Qm.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ya,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let n=Ff(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var Rf=class{constructor(e,t){this._url=e,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit}start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._eventSource=new EventSource(this._url.href,this._eventSourceInit),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;let a=new Error(`SSE error: ${JSON.stringify(n)}`);t(a),(i=this.onerror)===null||i===void 0||i.call(this,a)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let a=n;try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){t(o),(i=this.onerror)===null||i===void 0||i.call(this,o),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,a;let o=n,s;try{s=bf.parse(JSON.parse(o.data))}catch(u){(i=this.onerror)===null||i===void 0||i.call(this,u);return}(a=this.onmessage)===null||a===void 0||a.call(this,s)}})}async close(){var e,t,n;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var t,n,i;if(!this._endpoint)throw new Error("Not connected");try{let a=new Headers((t=this._requestInit)===null||t===void 0?void 0:t.headers);a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},s=await fetch(this._endpoint,o);if(!s.ok){let u=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${u}`)}}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}};var If=class{constructor(e,t){this.server=e;this.makeRequest=t}async setupHandlers(e){console.error("[Gateway] Setting up handlers for remote capabilities:",e),e.tools&&this.setupToolHandlers(),e.resources&&this.setupResourceHandlers(),e.prompts&&this.setupPromptHandlers(),console.error("[Gateway] Handlers setup complete")}setupToolHandlers(){this.server.setRequestHandler(km,async e=>(console.error("[Gateway] ListTools request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"tools/list",params:{}},zo))),this.server.setRequestHandler(Mm,async e=>{console.error("[Gateway] CallTool request:",JSON.stringify(e,null,2));try{let t=await this.makeRequest({method:"tools/call",params:e.params},yF);return console.error("[Gateway] CallTool response:",JSON.stringify(t,null,2)),t}catch(t){throw console.error("[Gateway] CallTool error:",t),t}})}setupResourceHandlers(){this.server.setRequestHandler(Tm,async e=>(console.error("[Gateway] ListResources request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"resources/list",params:{}},Uo))),this.server.setRequestHandler(jm,async e=>{console.error("[Gateway] ReadResource request:",JSON.stringify(e,null,2));try{return await this.makeRequest({method:"resources/read",params:e.params},Vo)}catch(t){throw console.error("[Gateway] ReadResource error:",t),t}}),this.server.setRequestHandler(Pm,async e=>(console.error("[Gateway] ListResourceTemplates request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"resources/templates/list",params:{}},Wo)))}setupPromptHandlers(){this.server.setRequestHandler(Rm,async e=>(console.error("[Gateway] ListPrompts request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"prompts/list",params:{}},$o))),this.server.setRequestHandler(Im,async e=>{console.error("[Gateway] GetPrompt request:",JSON.stringify(e,null,2));try{return await this.makeRequest({method:"prompts/get",params:e.params},Go)}catch(t){throw console.error("[Gateway] GetPrompt error:",t),t}})}};function qF(r,e){let t=new URL(r);if(e){let n=typeof window<"u"?btoa(JSON.stringify(e)):Buffer.from(JSON.stringify(e)).toString("base64");t.searchParams.set("config",n)}return t}var kf=class{constructor(){this.closing=!1;this.requestTimeout=Um;this.closing=!1,this.client=new ba({name:"smithery-runner",version:"1.0.0"},{capabilities:{}})}async makeRequest(e,t){if(!this.client)throw new Error("Client not connected");let n=new AbortController,i=setTimeout(()=>{n.abort("Request timed out")},this.requestTimeout);try{return await this.client.request(e,t,{signal:n.signal})}finally{clearTimeout(i)}}async setupHandlers(e){this.handlerManager=new If(this.server,this.makeRequest.bind(this)),await this.handlerManager.setupHandlers(e)}setupErrorHandling(){this.server.onerror=e=>{console.error("[Gateway] Server error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.client.onerror=e=>{console.error("[Gateway] SSE client error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.server.onclose=()=>{console.error("[Gateway] Server closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},this.client.onclose=()=>{console.error("[Gateway] SSE client closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},process.on("SIGINT",()=>this.cleanup()),process.on("SIGTERM",()=>this.cleanup())}async cleanup(){if(!this.closing){this.closing=!0,console.error("[Gateway] Starting cleanup...");try{this.client&&(console.error("[Gateway] Closing SSE client..."),await this.client.close()),this.server&&(console.error("[Gateway] Closing server..."),await this.server.close()),console.error("[Gateway] Cleanup completed"),process.exit(0)}catch(e){console.error("[Gateway] Fatal error during cleanup:",e),process.exit(1)}}}async handleStdioConnection(e,t){let n=e.connections.find(b=>b.type==="stdio");if(!n)throw new Error("No STDIO connection found");let i=await Ql(n,t),a=await fetch(`${ef}/servers/${e.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionType:"stdio",config:i})});if(!a.ok)throw new Error(`Failed to get server configuration: ${a.statusText}`);let{result:o}=await a.json(),s=o;console.error("[Gateway] Server configuration:",s);let{command:u,args:c,env:f}=s,p=null;try{let y={...Wm(),...f||{}};p=new ga({command:u,args:c||[],env:y,stderr:"pipe"}),p.onerror=_=>{console.error("[Gateway] STDIO transport error:",_),this.cleanup().catch(T=>{console.error("[Gateway] Cleanup error during transport error:",T)})},await this.client.connect(p);let m=this.client.getServerCapabilities()||{};console.error("[Gateway] Child process capabilities:",m),this.server=new Qo({name:`smithery-runner-${e.id}`,version:"1.0.0"},{capabilities:m}),this.setupErrorHandling(),await this.setupHandlers(m);let g=new Xo;await this.server.connect(g),console.error("[Gateway] STDIO server ready"),p.stderr&&p.stderr.on("data",_=>{console.error("[Gateway] Child process stderr:",_.toString())})}catch(b){if(console.error("[Gateway] Error during STDIO setup:",b),p)try{await p.close()}catch(y){console.error("[Gateway] Error closing transport during error recovery:",y)}throw b}let v=()=>{p&&!this.closing&&(console.error("[Gateway] Process termination detected, cleaning up..."),this.cleanup().catch(b=>{console.error("[Gateway] Cleanup error during process termination:",b),process.exit(1)}))};process.once("SIGTERM",v),process.once("SIGINT",v)}async handleSSEConnection(e,t){let n=e.connections.find(u=>u.type==="sse");if(!n?.deploymentUrl)throw new Error("SSE connection missing deployment URL");let i=new URL("/sse",n.deploymentUrl).toString(),a=qF(i,t||{});console.error("[Gateway] Attempting to connect to SSE server at:",a);try{let u=new Rf(new URL(a));await this.client.connect(u),console.error("[Gateway] Connected to remote SSE server")}catch(u){throw console.error("[Gateway] Failed to connect to SSE server:",{url:a,error:u,status:u?.status,message:u?.message}),u}let o=this.client.getServerCapabilities()||{};console.error("[Gateway] Remote server capabilities:",o),this.server=new Qo({name:`smithery-runner-${e.id}`,version:"1.0.0"},{capabilities:o}),this.setupErrorHandling(),await this.setupHandlers(o);let s=new Xo;await this.server.connect(s),console.error("[Gateway] STDIO server ready")}async run(e,t){try{let n=e.connections.some(a=>a.type==="sse"),i=e.connections.some(a=>a.type==="stdio");if(n)await this.handleSSEConnection(e,t);else if(i)await this.handleStdioConnection(e,t);else throw new Error("No connection types found. Server not deployed.")}catch(n){throw console.error("[Gateway] Setup error:",n),await this.cleanup(),n}}};global.EventSource=Cn;async function AF(r,e){try{let t=await an(r);if(!t)throw new Error(`Could not resolve server: ${r}`);console.error("[Runner] Resolved server details:",{id:t.id,connectionTypes:t.connections.map(i=>i.type)}),await new kf().run(t,e)}catch(t){console.error("[Runner] Fatal error:",t),process.exit(1)}}var PF=K(Z()),_ce=process.argv[2],Sn=process.argv[3],Xm=process.argv.indexOf("--client"),TF=process.argv.indexOf("--config"),es=Xm!==-1?process.argv[Xm+1]:"claude",Ece=TF!==-1?JSON.parse(process.argv[TF+1]):{};async function Dce(){switch(_ce){case"inspect":await CF(es);break;case"install":Sn||(console.error("Please provide a package name to install"),process.exit(1)),Xm===-1&&console.log(PF.default.yellow("Client not provided, defaulting to claude")),await NS(Sn,es);break;case"uninstall":await US(Sn,es);break;case"installed":await uf(es);break;case"view":Sn||(console.error("Please provide a package ID to get details"),process.exit(1)),await XS(Sn,es);break;case"run":Sn||(console.error("Please provide a server ID to run"),process.exit(1)),await AF(Sn,Ece);break;default:console.log("Available commands:"),console.log(" install <package> Install a package"),console.log(" --client <name> Specify the AI client"),console.log(" uninstall [package] Uninstall a package"),console.log(" installed List installed packages"),console.log(" view <package> Get details for a specific package"),console.log(" inspect Inspect installed servers"),console.log(" run <server-id> Run a server"),process.exit(1)}}Dce();
|
|
84
|
+
`?(e.push(t),t=""):t+=a}return[e,t]}var Pf=class extends Event{};function yce(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}var OF=r=>{throw TypeError(r)},Jm=(r,e,t)=>e.has(r)||OF("Cannot "+t),k=(r,e,t)=>(Jm(r,e,"read from private field"),t?t.call(r):e.get(r)),ne=(r,e,t)=>e.has(r)?OF("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),Q=(r,e,t,n)=>(Jm(r,e,"write to private field"),e.set(r,t),t),Lr=(r,e,t)=>(Jm(r,e,"access private method"),t),we,wn,Ea,Tf,jf,Yo,Ca,Jo,Ft,Da,Sa,wa,Ko,Xe,$m,Gm,zm,FF,Hm,Km,Zo,Zm,Ym,Cn=class extends EventTarget{constructor(e,t){var n,i;super(),ne(this,Xe),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ne(this,we),ne(this,wn),ne(this,Ea),ne(this,Tf),ne(this,jf),ne(this,Yo),ne(this,Ca),ne(this,Jo,null),ne(this,Ft),ne(this,Da),ne(this,Sa,null),ne(this,wa,null),ne(this,Ko,null),ne(this,Gm,async a=>{var o;k(this,Da).reset();let{body:s,redirected:u,status:c,headers:f}=a;if(c===204){Lr(this,Xe,Zo).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Q(this,Ea,new URL(a.url)):Q(this,Ea,void 0),c!==200){Lr(this,Xe,Zo).call(this,`Non-200 status code (${c})`,c);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){Lr(this,Xe,Zo).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(k(this,we)===this.CLOSED)return;Q(this,we,this.OPEN);let p=new Event("open");if((o=k(this,Ko))==null||o.call(this,p),this.dispatchEvent(p),typeof s!="object"||!s||!("getReader"in s)){Lr(this,Xe,Zo).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let v=new TextDecoder,b=s.getReader(),y=!0;do{let{done:m,value:g}=await b.read();g&&k(this,Da).feed(v.decode(g,{stream:!m})),m&&(y=!1,k(this,Da).reset(),Lr(this,Xe,Zm).call(this))}while(y)}),ne(this,zm,a=>{Q(this,Ft,void 0),!(a.name==="AbortError"||a.type==="aborted")&&Lr(this,Xe,Zm).call(this)}),ne(this,Hm,a=>{typeof a.id=="string"&&Q(this,Jo,a.id);let o=new MessageEvent(a.event||"message",{data:a.data,origin:k(this,Ea)?k(this,Ea).origin:k(this,wn).origin,lastEventId:a.id||""});k(this,wa)&&(!a.event||a.event==="message")&&k(this,wa).call(this,o),this.dispatchEvent(o)}),ne(this,Km,a=>{Q(this,Yo,a)}),ne(this,Ym,()=>{Q(this,Ca,void 0),k(this,we)===this.CONNECTING&&Lr(this,Xe,$m).call(this)});try{if(e instanceof URL)Q(this,wn,e);else if(typeof e=="string")Q(this,wn,new URL(e,gce()));else throw new Error("Invalid URL")}catch{throw yce("An invalid or illegal string was specified")}Q(this,Da,SF({onEvent:k(this,Hm),onRetry:k(this,Km)})),Q(this,we,this.CONNECTING),Q(this,Yo,3e3),Q(this,jf,(n=t?.fetch)!=null?n:globalThis.fetch),Q(this,Tf,(i=t?.withCredentials)!=null?i:!1),Lr(this,Xe,$m).call(this)}get readyState(){return k(this,we)}get url(){return k(this,wn).href}get withCredentials(){return k(this,Tf)}get onerror(){return k(this,Sa)}set onerror(e){Q(this,Sa,e)}get onmessage(){return k(this,wa)}set onmessage(e){Q(this,wa,e)}get onopen(){return k(this,Ko)}set onopen(e){Q(this,Ko,e)}addEventListener(e,t,n){let i=t;super.addEventListener(e,i,n)}removeEventListener(e,t,n){let i=t;super.removeEventListener(e,i,n)}close(){k(this,Ca)&&clearTimeout(k(this,Ca)),k(this,we)!==this.CLOSED&&(k(this,Ft)&&k(this,Ft).abort(),Q(this,we,this.CLOSED),Q(this,Ft,void 0))}};we=new WeakMap,wn=new WeakMap,Ea=new WeakMap,Tf=new WeakMap,jf=new WeakMap,Yo=new WeakMap,Ca=new WeakMap,Jo=new WeakMap,Ft=new WeakMap,Da=new WeakMap,Sa=new WeakMap,wa=new WeakMap,Ko=new WeakMap,Xe=new WeakSet,$m=function(){Q(this,we,this.CONNECTING),Q(this,Ft,new AbortController),k(this,jf)(k(this,wn),Lr(this,Xe,FF).call(this)).then(k(this,Gm)).catch(k(this,zm))},Gm=new WeakMap,zm=new WeakMap,FF=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...k(this,Jo)?{"Last-Event-ID":k(this,Jo)}:void 0},cache:"no-store",signal:(r=k(this,Ft))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Hm=new WeakMap,Km=new WeakMap,Zo=function(r,e){var t;k(this,we)!==this.CLOSED&&Q(this,we,this.CLOSED);let n=new Pf("error");n.code=e,n.message=r,(t=k(this,Sa))==null||t.call(this,n),this.dispatchEvent(n)},Zm=function(){var r;if(k(this,we)===this.CLOSED)return;Q(this,we,this.CONNECTING);let e=new Pf("error");(r=k(this,Sa))==null||r.call(this,e),this.dispatchEvent(e),Q(this,Ca,setTimeout(k(this,Ym),k(this,Yo)))},Ym=new WeakMap,Cn.CONNECTING=0,Cn.OPEN=1,Cn.CLOSED=2;function gce(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var Qo=class extends ma{constructor(e,t){super(t),this._serverInfo=e,this._capabilities=t.capabilities,this.setRequestHandler(Om,n=>this._oninitialize(n)),this.setNotificationHandler(Am,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}assertCapabilityForMethod(e){var t,n;switch(e){case"sampling/createMessage":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:xf.includes(t)?t:No,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Nr)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},Bm,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Lm,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Qm=K(require("node:process"),1);var Xo=class{constructor(e=Qm.default.stdin,t=Qm.default.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new ya,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(t=>{let n=Ff(e);this._stdout.write(n)?t():this._stdout.once("drain",t)})}};var Rf=class{constructor(e,t){this._url=e,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit}start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._eventSource=new EventSource(this._url.href,this._eventSourceInit),this._abortController=new AbortController,this._eventSource.onerror=n=>{var i;let a=new Error(`SSE error: ${JSON.stringify(n)}`);t(a),(i=this.onerror)===null||i===void 0||i.call(this,a)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{var i;let a=n;try{if(this._endpoint=new URL(a.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(o){t(o),(i=this.onerror)===null||i===void 0||i.call(this,o),this.close();return}e()}),this._eventSource.onmessage=n=>{var i,a;let o=n,s;try{s=bf.parse(JSON.parse(o.data))}catch(u){(i=this.onerror)===null||i===void 0||i.call(this,u);return}(a=this.onmessage)===null||a===void 0||a.call(this,s)}})}async close(){var e,t,n;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(e){var t,n,i;if(!this._endpoint)throw new Error("Not connected");try{let a=new Headers((t=this._requestInit)===null||t===void 0?void 0:t.headers);a.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},s=await fetch(this._endpoint,o);if(!s.ok){let u=await s.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${s.status}): ${u}`)}}catch(a){throw(i=this.onerror)===null||i===void 0||i.call(this,a),a}}};var If=class{constructor(e,t){this.server=e;this.makeRequest=t}async setupHandlers(e){console.error("[Gateway] Setting up handlers for remote capabilities:",e),e.tools&&this.setupToolHandlers(),e.resources&&this.setupResourceHandlers(),e.prompts&&this.setupPromptHandlers(),console.error("[Gateway] Handlers setup complete")}setupToolHandlers(){this.server.setRequestHandler(km,async e=>(console.error("[Gateway] ListTools request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"tools/list",params:{}},zo))),this.server.setRequestHandler(Mm,async e=>{console.error("[Gateway] CallTool request:",JSON.stringify(e,null,2));try{let t=await this.makeRequest({method:"tools/call",params:e.params},yF);return console.error("[Gateway] CallTool response:",JSON.stringify(t,null,2)),t}catch(t){throw console.error("[Gateway] CallTool error:",t),t}})}setupResourceHandlers(){this.server.setRequestHandler(Tm,async e=>(console.error("[Gateway] ListResources request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"resources/list",params:{}},Uo))),this.server.setRequestHandler(jm,async e=>{console.error("[Gateway] ReadResource request:",JSON.stringify(e,null,2));try{return await this.makeRequest({method:"resources/read",params:e.params},Vo)}catch(t){throw console.error("[Gateway] ReadResource error:",t),t}}),this.server.setRequestHandler(Pm,async e=>(console.error("[Gateway] ListResourceTemplates request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"resources/templates/list",params:{}},Wo)))}setupPromptHandlers(){this.server.setRequestHandler(Rm,async e=>(console.error("[Gateway] ListPrompts request:",JSON.stringify(e,null,2)),await this.makeRequest({method:"prompts/list",params:{}},$o))),this.server.setRequestHandler(Im,async e=>{console.error("[Gateway] GetPrompt request:",JSON.stringify(e,null,2));try{return await this.makeRequest({method:"prompts/get",params:e.params},Go)}catch(t){throw console.error("[Gateway] GetPrompt error:",t),t}})}};function qF(r,e){let t=new URL(r);if(e){let n=typeof window<"u"?btoa(JSON.stringify(e)):Buffer.from(JSON.stringify(e)).toString("base64");t.searchParams.set("config",n)}return t}var kf=class{constructor(){this.closing=!1;this.requestTimeout=Um;this.closing=!1,this.client=new ba({name:"smithery-runner",version:"1.0.0"},{capabilities:{}})}async makeRequest(e,t){if(!this.client)throw new Error("Client not connected");let n=new AbortController,i=setTimeout(()=>{n.abort("Request timed out")},this.requestTimeout);try{return await this.client.request(e,t,{signal:n.signal})}finally{clearTimeout(i)}}async setupHandlers(e){this.handlerManager=new If(this.server,this.makeRequest.bind(this)),await this.handlerManager.setupHandlers(e)}setupErrorHandling(){this.server.onerror=e=>{console.error("[Gateway] Server error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.client.onerror=e=>{console.error("[Gateway] SSE client error:",e),this.closing||this.cleanup().catch(t=>{console.error("[Gateway] Cleanup error during error handling:",t)})},this.server.onclose=()=>{console.error("[Gateway] Server closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},this.client.onclose=()=>{console.error("[Gateway] SSE client closed"),this.closing||this.cleanup().catch(e=>{console.error("[Gateway] Cleanup error during close:",e)})},process.on("SIGINT",()=>this.cleanup()),process.on("SIGTERM",()=>this.cleanup())}async cleanup(){if(!this.closing){this.closing=!0,console.error("[Gateway] Starting cleanup...");try{this.client&&(console.error("[Gateway] Closing SSE client..."),await this.client.close()),this.server&&(console.error("[Gateway] Closing server..."),await this.server.close()),console.error("[Gateway] Cleanup completed"),process.exit(0)}catch(e){console.error("[Gateway] Fatal error during cleanup:",e),process.exit(1)}}}async handleStdioConnection(e,t){let n=e.connections.find(b=>b.type==="stdio");if(!n)throw new Error("No STDIO connection found");let i=await Ql(n,t),a=await fetch(`${ef}/servers/${e.id}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connectionType:"stdio",config:i})});if(!a.ok)throw new Error(`Failed to get server configuration: ${a.statusText}`);let{result:o}=await a.json(),s=o;console.error("[Gateway] Server configuration:",s);let{command:u,args:c,env:f}=s,p=null;try{let y={...Wm(),...f||{}};p=new ga({command:u,args:c||[],env:y,stderr:"pipe"}),p.onerror=_=>{console.error("[Gateway] STDIO transport error:",_),this.cleanup().catch(T=>{console.error("[Gateway] Cleanup error during transport error:",T)})},await this.client.connect(p);let m=this.client.getServerCapabilities()||{};console.error("[Gateway] Child process capabilities:",m),this.server=new Qo({name:`smithery-runner-${e.id}`,version:"1.0.0"},{capabilities:m}),this.setupErrorHandling(),await this.setupHandlers(m);let g=new Xo;await this.server.connect(g),console.error("[Gateway] STDIO server ready"),p.stderr&&p.stderr.on("data",_=>{console.error("[Gateway] Child process stderr:",_.toString())})}catch(b){if(console.error("[Gateway] Error during STDIO setup:",b),p)try{await p.close()}catch(y){console.error("[Gateway] Error closing transport during error recovery:",y)}throw b}let v=()=>{p&&!this.closing&&(console.error("[Gateway] Process termination detected, cleaning up..."),this.cleanup().catch(b=>{console.error("[Gateway] Cleanup error during process termination:",b),process.exit(1)}))};process.once("SIGTERM",v),process.once("SIGINT",v)}async handleSSEConnection(e,t){let n=e.connections.find(u=>u.type==="sse");if(!n?.deploymentUrl)throw new Error("SSE connection missing deployment URL");let i=new URL("/sse",n.deploymentUrl).toString(),a=qF(i,t||{});console.error("[Gateway] Attempting to connect to SSE server at:",a);try{let u=new Rf(new URL(a));await this.client.connect(u),console.error("[Gateway] Connected to remote SSE server")}catch(u){throw console.error("[Gateway] Failed to connect to SSE server:",{url:a,error:u,status:u?.status,message:u?.message}),u}let o=this.client.getServerCapabilities()||{};console.error("[Gateway] Remote server capabilities:",o),this.server=new Qo({name:`smithery-runner-${e.id}`,version:"1.0.0"},{capabilities:o}),this.setupErrorHandling(),await this.setupHandlers(o);let s=new Xo;await this.server.connect(s),console.error("[Gateway] STDIO server ready")}async run(e,t){try{let n=e.connections.some(a=>a.type==="sse"),i=e.connections.some(a=>a.type==="stdio");if(n)await this.handleSSEConnection(e,t);else if(i)await this.handleStdioConnection(e,t);else throw new Error("No connection types found. Server not deployed.")}catch(n){throw console.error("[Gateway] Setup error:",n),await this.cleanup(),n}}};global.EventSource=Cn;async function AF(r,e){try{let t=await an(r);if(!t)throw new Error(`Could not resolve server: ${r}`);console.error("[Runner] Resolved server details:",{id:t.id,connectionTypes:t.connections.map(i=>i.type)}),await new kf().run(t,e)}catch(t){console.error("[Runner] Fatal error:",t),process.exit(1)}}var PF=K(Z()),_ce=process.argv[2],Sn=process.argv[3],Xm=process.argv.indexOf("--client"),TF=process.argv.indexOf("--config"),es=Xm!==-1?process.argv[Xm+1]:"claude",Ece=TF!==-1?(()=>{let r=JSON.parse(process.argv[TF+1]);return typeof r=="string"&&(r=JSON.parse(r)),r})():{};async function Dce(){switch(_ce){case"inspect":await CF(es);break;case"install":Sn||(console.error("Please provide a package name to install"),process.exit(1)),Xm===-1&&console.log(PF.default.yellow("Client not provided, defaulting to claude")),await NS(Sn,es);break;case"uninstall":await US(Sn,es);break;case"installed":await uf(es);break;case"view":Sn||(console.error("Please provide a package ID to get details"),process.exit(1)),await XS(Sn,es);break;case"run":Sn||(console.error("Please provide a server ID to run"),process.exit(1)),await AF(Sn,Ece);break;default:console.log("Available commands:"),console.log(" install <package> Install a package"),console.log(" --client <name> Specify the AI client"),console.log(" uninstall [package] Uninstall a package"),console.log(" installed List installed packages"),console.log(" view <package> Get details for a specific package"),console.log(" inspect Inspect installed servers"),console.log(" run <server-id> Run a server"),process.exit(1)}}Dce();
|
|
85
85
|
/*! Bundled license information:
|
|
86
86
|
|
|
87
87
|
safe-buffer/index.js:
|