@agimon-ai/model-proxy-mcp 0.2.3 → 0.2.5

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/cli.cjs ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ const e=require(`./stdio-D5p7q_0H.cjs`);let t=require(`node:fs`),n=require(`node:path`);n=e.u(n);let r=require(`node:url`),i=require(`commander`),a=require(`node:child_process`),o=require(`node:crypto`),s=require(`node:fs/promises`);s=e.u(s);let c=require(`node:os`);c=e.u(c);let l=require(`node:util`),u=require(`@hono/node-server`);var d=class{async check(e){try{let t=await fetch(`http://127.0.0.1:${e}/health`);return t.ok?{healthy:!0,serviceName:(await t.json()).service}:{healthy:!1,error:`Health check failed with status ${t.status}`}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}};const f=[`pnpm-workspace.yaml`,`nx.json`,`.git`],p=25,m=`sh`,h=`lsof -n -P -sTCP:LISTEN`,g=5e3,_=250,ee=1e3,te=`SIGTERM`,ne=`SIGKILL`,re=`model-proxy-mcp-http`,v=`utf8`,y=(0,l.promisify)(a.execFile);function b(e=process.cwd()){let r=n.default.resolve(e);for(;;){for(let e of f)if((0,t.existsSync)(n.default.join(r,e)))return r;let e=n.default.dirname(r);if(e===r)return process.cwd();r=e}}var x=class{repositoryPath=b(process.cwd());serviceName=e.l;stateFilePath=n.default.join(c.default.tmpdir(),`model-proxy-mcp-http-${Buffer.from(b(process.cwd())).toString(`hex`)}.json`);constructor(e=new d){this.healthCheck=e}createEmptyStatus(e={}){return{running:!1,scope:`default`,activeProfileId:null,auth:{configured:!1,authFilePath:``},profiles:[],slotModels:{},...e}}async getRegistration(){try{let e=await s.default.readFile(this.stateFilePath,v),t=JSON.parse(e);return t.port?t:null}catch(e){if(e.code===`ENOENT`)return null;throw e}}async releaseService(e){let t=await this.getRegistration();e&&t?.pid&&t.pid!==e||await s.default.rm(this.stateFilePath,{force:!0})}async listListeningProcesses(e){try{let{stdout:t}=await y(`sh`,[`-lc`,`lsof -n -P -sTCP:LISTEN -iTCP:${e} || true`],{encoding:`utf8`});return t.split(`
3
+ `).slice(1).map(e=>e.trim()).filter(Boolean).map(e=>e.split(/\s+/)).map(t=>({pid:Number.parseInt(t[1]||``,10),port:e})).filter(e=>Number.isInteger(e.pid)&&e.pid>0)}catch{return[]}}async findHealthyServicePort(e){for(let t=0;t<=25;t+=1){let n=e+t,r=await this.healthCheck.check(n);if(r.healthy&&r.serviceName===this.serviceName)return n}return null}async clearPortListeners(e,t){let n=await this.listListeningProcesses(e);for(let e of n)t&&e.pid===t||await this.killProcess(e.pid)}async registerService(e,t){await s.default.writeFile(this.stateFilePath,JSON.stringify({port:e,pid:t}),v)}async findAvailablePort(t){let n=Math.min(e.c,t),r=Math.max(e.c+1e3,t);for(let e=t;e<=r;e+=1)if((await this.listListeningProcesses(e)).length===0)return e;for(let e=n;e<t;e+=1)if((await this.listListeningProcesses(e)).length===0)return e;throw Error(`No available port found from ${t}`)}async fileExists(e){try{return await s.default.access(e),!0}catch{return!1}}async resolveCliPath(){let e=n.default.dirname((0,r.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),t=n.default.resolve(e,`cli.mjs`);if(await this.fileExists(t))return{cliPath:t,useLoader:!1};let i=n.default.resolve(e,`..`,`cli.mjs`);if(await this.fileExists(i))return{cliPath:i,useLoader:!1};for(let t of[n.default.resolve(e,`cli.ts`),n.default.resolve(e,`..`,`cli.ts`)])if(await this.fileExists(t))return{cliPath:t,useLoader:!0};let a=n.default.join(this.repositoryPath,`packages`,`mcp`,`model-proxy-mcp`,`dist`,`cli.mjs`);if(await this.fileExists(a))return{cliPath:a,useLoader:!1};let o=n.default.join(this.repositoryPath,`packages`,`mcp`,`model-proxy-mcp`,`src`,`cli.ts`);if(await this.fileExists(o))return{cliPath:o,useLoader:!0};throw Error(`Cannot find model-proxy-mcp CLI`)}async startHttpServer(e){let{cliPath:t,useLoader:n}=await this.resolveCliPath(),r=(0,a.spawn)(`node`,n?[`--loader`,`ts-node/esm`,t,`http-serve`,`--port`,String(e)]:[t,`http-serve`,`--port`,String(e)],{detached:!0,stdio:`ignore`,env:{...process.env,NODE_ENV:process.env.NODE_ENV||`development`}});if(r.unref(),!r.pid)throw Error(`Failed to spawn HTTP server`);return r.pid}async killProcess(e){try{process.kill(e,`SIGTERM`),await new Promise(e=>setTimeout(e,1e3));try{process.kill(e,0),process.kill(e,`SIGKILL`)}catch{return}}catch{return}}async waitForHealthy(e){let t=Date.now()+5e3,n=`Server failed health check after startup`;for(;Date.now()<t;){let t=await this.healthCheck.check(e);if(t.healthy&&t.serviceName===this.serviceName)return{healthy:!0};n=t.error||`Unexpected service on port ${e}`,await new Promise(e=>setTimeout(e,250))}return{healthy:!1,error:n}}async ensureRunning(t=e.c){try{let e=await this.findHealthyServicePort(t);if(e!==null){let t=(await this.listListeningProcesses(e))[0]?.pid;return await this.registerService(e,t??process.pid),this.createEmptyStatus({running:!0,port:e,pid:t})}let n=await this.getRegistration();if(n){let e=await this.healthCheck.check(n.port);if(e.healthy&&e.serviceName===this.serviceName)return this.createEmptyStatus({running:!0,port:n.port,pid:n.pid});n.pid&&await this.killProcess(n.pid),await this.clearPortListeners(n.port,n.pid),await this.releaseService(n.pid)}await this.clearPortListeners(t);let r=await this.findAvailablePort(t),i=await this.startHttpServer(r),a=await this.waitForHealthy(r);return a.healthy?(await this.registerService(r,i),this.createEmptyStatus({running:!0,port:r,pid:i})):(await this.killProcess(i),await this.clearPortListeners(r,i),await this.releaseService(i),this.createEmptyStatus({error:a.error||`Server failed health check after startup`}))}catch(e){return this.createEmptyStatus({error:e instanceof Error?e.message:String(e)})}}async stop(){let t=await this.getRegistration(),n=!1;t?.pid&&(await this.killProcess(t.pid),n=!0),t&&(await this.clearPortListeners(t.port,t.pid),await this.releaseService(t.pid));let r=await this.findHealthyServicePort(e.c);if(r!==null){let e=await this.listListeningProcesses(r);for(let t of e)await this.killProcess(t.pid),n=!0;await this.releaseService()}return n}async getStatus(){let t=await this.getRegistration();if(t&&(await this.healthCheck.check(t.port)).healthy)return this.createEmptyStatus({running:!0,port:t.port,pid:t.pid});let n=await this.findHealthyServicePort(e.c);if(n!==null){let e=(await this.listListeningProcesses(n))[0]?.pid;return e&&await this.registerService(n,e),this.createEmptyStatus({running:!0,port:n,pid:e})}return this.createEmptyStatus({error:t?`Registered server is unhealthy`:`No HTTP server registered`})}};const S=`claude`,C=`default`,ie=`.claude-sessions`,ae=`scope`,oe=3,w=`utf8`,se=`inherit`,ce=10,T=`[model-proxy-mcp]`,E=`Recovery: verify HOME, proxy port, and that \`${S}\` is on PATH.`,le=`--resume`,ue=`--session-id`,de=`--dangerously-skip-permissions`,fe=`ccproxy-opus`,pe=`ccproxy-sonnet`,me=`ccproxy-haiku`,he=`ccproxy-subagent`,ge=`model-proxy-mcp.yaml`,_e=`MODEL_PROXY_MCP_SCOPE`,ve=`MODEL_PROXY_MCP_SLOT`,ye=`default`;var D=class extends Error{constructor(e,t,n){super(e,n),this.code=t,this.name=`ClaudeCommandError`}},O=class extends D{constructor(e,t){super(e,`CLAUDE_COMMAND_CONFIG_ERROR`,t),this.name=`ClaudeCommandConfigError`}},k=class extends D{constructor(e,t){super(e,`CLAUDE_COMMAND_VALIDATION_ERROR`,t),this.name=`ClaudeCommandValidationError`}},A=class extends D{constructor(e,t){super(e,`CLAUDE_COMMAND_LAUNCH_ERROR`,t),this.name=`ClaudeCommandLaunchError`}};function j(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`default`}function M(){return`scope-${(0,o.randomBytes)(3).toString(`hex`)}`}function N(e,t,n=process.env){return{...n,ANTHROPIC_BASE_URL:`http://127.0.0.1:${e}/scopes/${t}`,ANTHROPIC_DEFAULT_OPUS_MODEL:n.ANTHROPIC_DEFAULT_OPUS_MODEL||`ccproxy-opus`,ANTHROPIC_DEFAULT_SONNET_MODEL:n.ANTHROPIC_DEFAULT_SONNET_MODEL||`ccproxy-sonnet`,ANTHROPIC_DEFAULT_HAIKU_MODEL:n.ANTHROPIC_DEFAULT_HAIKU_MODEL||`ccproxy-haiku`,CLAUDE_CODE_SUBAGENT_MODEL:n.CLAUDE_CODE_SUBAGENT_MODEL||`ccproxy-subagent`,MODEL_PROXY_MCP_SCOPE:n.MODEL_PROXY_MCP_SCOPE||t,MODEL_PROXY_MCP_SLOT:n.MODEL_PROXY_MCP_SLOT||`default`}}async function P(e,t=process.cwd()){let r=e?n.default.resolve(t,e):n.default.join(t,`model-proxy-mcp.yaml`);try{if(!(await s.default.stat(r)).isFile()){if(e)throw new O(`Scope seed config path is not a file: ${r}`);return}return r}catch(t){if(t.code===`ENOENT`){if(e)throw new O(`Scope seed config file not found: ${r}`,{cause:t});return}throw t instanceof O?t:new O(`Failed to read scope seed config file: ${r}`,{cause:t})}}function F(){let e=process.env.HOME||process.env.USERPROFILE;if(!e)throw new O(`HOME or USERPROFILE is not set`);return n.default.join(e,`.claude-sessions`)}async function I(){let e=F();return await s.default.mkdir(e,{recursive:!0}),e}async function L(e){try{return(await s.default.readFile(e,w)).trim()||null}catch(t){if(t.code===`ENOENT`)return null;throw new O(`Failed to read Claude session file: ${e}`,{cause:t})}}async function R(e,t){let r=await I(),i=n.default.join(r,e);if(t)try{await s.default.rm(i,{force:!0})}catch(e){throw new O(`Failed to clear Claude session file: ${i}`,{cause:e})}let a=await L(i);if(a)return{sessionId:a,resume:!0};let c=(0,o.randomUUID)().toLowerCase();try{await s.default.writeFile(i,`${c}\n`,w)}catch(e){throw new O(`Failed to write Claude session file: ${i}`,{cause:e})}return{sessionId:c,resume:!1}}async function z(t,n,r,i,o){let s=await P(o);await new e.o().ensureConfig(t,s);let c=await new x().ensureRunning(n);if(!c.running||!c.port)throw new A(c.error||`Failed to start model proxy HTTP server`);let{sessionId:l,resume:u}=await R(t,r),d=N(c.port,t),f=[`--dangerously-skip-permissions`,...u?[`--resume`,l]:[`--session-id`,l],...i];return console.log(`${T} Scope: ${t}`),console.log(`${T} Proxy: ${d.ANTHROPIC_BASE_URL}`),console.log(`${T} Session: ${l}${u?` (resume)`:` (new)`}`),s&&console.log(`${T} Scope config seed: ${s}`),new Promise((e,t)=>{let n=(0,a.spawn)(S,f,{stdio:`inherit`,env:d});n.on(`error`,e=>{t(new A(`Failed to launch ${S}`,{cause:e}))}),n.on(`exit`,(n,r)=>{if(r){t(new A(`${S} exited with signal ${r}`));return}e(n??0)})})}const B=new i.Command(`claude`).description(`Launch Claude Code through the model proxy`).option(`-s, --scope <scope>`,`Proxy scope to use`).option(`-p, --port <port>`,`Preferred HTTP port for the proxy`,String(e.c)).option(`-c, --config-file <path>`,`Seed a new scope from the specified scope config file`).option(`--config <path>`,`Alias for --config-file`).option(`--clear-session`,`Start with a fresh Claude session for the selected scope`,!1).allowUnknownOption(!0).allowExcessArguments(!0).argument(`[claudeArgs...]`).action(async(e,t)=>{try{let n=j(t.scope||M()),r=Number.parseInt(t.port,10);if(!Number.isInteger(r)||r<=0)throw new k(`Invalid port: ${t.port}`);let i=await z(n,r,t.clearSession,e,t.configFile??t.config);process.exit(i)}catch(e){let t=e instanceof D?e:new A(`Failed to launch Claude`,{cause:e});console.error(`${T} ${t.code}: ${t.message}`),console.error(`${T} ${E}`),t.cause&&console.error(`${T} Cause:`,t.cause),process.exit(1)}}),V=`127.0.0.1`,H=new i.Command(`http-serve`).description(`Start the Claude-compatible HTTP model proxy server`).option(`-p, --port <port>`,`Port to listen on`,String(e.c)).action(async t=>{try{let n=Number.parseInt(t.port,10);if(!Number.isInteger(n)||n<=0)throw Error(`Invalid port: ${t.port}`);let r=new e.i;await r.ensureConfig();let i=(0,u.serve)({fetch:e.r(r).fetch,port:n,hostname:V});console.log(`model-proxy-mcp listening on http://${V}:${n}`),console.log(`Claude base URL: http://${V}:${n}`);let a=e=>{console.log(`\n${e} received. Shutting down...`),i.close(),process.exit(0)};process.once(`SIGINT`,()=>a(`SIGINT`)),process.once(`SIGTERM`,()=>a(`SIGTERM`))}catch(e){console.error(`Failed to start HTTP server:`,e),process.exit(1)}}),be=`default`,xe=`MODEL_PROXY_MCP_SCOPE`,U=new i.Command(`mcp-serve`).description(`Start MCP server with stdio transport`).option(`--cleanup`,`Stop HTTP server on shutdown`,!1).option(`-p, --port <port>`,`Port for HTTP server`,String(e.c)).action(async t=>{try{let n=Number.parseInt(t.port,10);if(!Number.isInteger(n)||n<=0)throw Error(`Invalid port: ${t.port}`);let r=new e.i;await r.ensureConfig(process.env.MODEL_PROXY_MCP_SCOPE||`default`);let i=new x,a=await i.ensureRunning(n);a.running||console.error(`Warning: HTTP server failed to start: ${a.error}`);let o=new e.t(e.n(r)),s=async e=>{console.error(`\nReceived ${e}, shutting down gracefully...`),await o.stop(),t.cleanup&&a.running&&await i.stop(),process.exit(0)};process.once(`SIGINT`,()=>void s(`SIGINT`).catch(e=>{console.error(`Failed to shut down after SIGINT:`,e),process.exit(1)})),process.once(`SIGTERM`,()=>void s(`SIGTERM`).catch(e=>{console.error(`Failed to shut down after SIGTERM:`,e),process.exit(1)})),await o.start()}catch(e){console.error(`Failed to start MCP server:`,e),process.exit(1)}}),W=new i.Command(`start`).description(`Start HTTP and/or MCP server for the model proxy`).option(`--mcp-only`,`Start only the MCP server`,!1).option(`--http-only`,`Start only the HTTP server`,!1).option(`-p, --port <port>`,`Port for HTTP server`,String(e.c)).action(async t=>{try{let n=new x,r=Number.parseInt(t.port,10),i=!t.mcpOnly,a=!t.httpOnly;if(i){let e=await n.ensureRunning(r);e.running||(console.error(`HTTP server failed to start: ${e.error}`),process.exit(1)),console.log(`HTTP server running on http://127.0.0.1:${e.port}`)}if(a){let t=new e.t(e.n());await t.start();let n=async e=>{console.error(`\n${e} received. Shutting down...`),await t.stop(),process.exit(0)};process.on(`SIGINT`,()=>n(`SIGINT`)),process.on(`SIGTERM`,()=>n(`SIGTERM`))}else process.exit(0)}catch(e){console.error(`Failed to start services:`,e),process.exit(1)}}),G=`default`,K=`status`,Se=`Show proxy server and profile status`,q=`Failed to read status`;var J=class extends Error{code=`STATUS_CHECK_FAILED`;constructor(e){super(q,{cause:e instanceof Error?e:Error(String(e))}),this.name=`StatusCommandError`}};const Y=new i.Command(K).description(`Show proxy server and profile status`).option(`-s, --scope <scope>`,`Configuration scope`,`default`).action(async t=>{try{let n=await new x().getStatus(),r=await new e.i().getStatus(t.scope,n.port,n.pid);r.running=n.running,r.error=n.error,e.s.info(JSON.stringify(r,null,2)),process.exit(0)}catch(n){let r=new J(n);e.s.error(q,{command:K,code:r.code,scope:t.scope,cause:r.cause}),process.exit(1)}}),X=new i.Command(`stop`).description(`Stop the background HTTP server`).action(async()=>{try{let e=await new x().stop();console.log(e?`HTTP server stopped`:`No HTTP server running`),process.exit(0)}catch(e){console.error(`Failed to stop HTTP server:`,e),process.exit(1)}}),Z=(0,n.dirname)((0,r.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),Q=JSON.parse((0,t.readFileSync)((0,n.join)(Z,`../package.json`),`utf-8`));async function $(){let e=new i.Command;e.name(`model-proxy-mcp`).description(`Claude-compatible model proxy MCP`).version(Q.version),e.addCommand(W),e.addCommand(X),e.addCommand(Y),e.addCommand(B),e.addCommand(H),e.addCommand(U),await e.parseAsync(process.argv)}$();