@agimon-ai/model-proxy-mcp 0.2.3 → 0.2.4
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 +3 -0
- package/dist/cli.mjs +2 -651
- package/dist/index.cjs +1 -0
- package/dist/index.mjs +1 -3
- package/dist/stdio-BKQRhaEs.cjs +1127 -0
- package/dist/stdio-xpvsxU_k.mjs +596 -0
- package/package.json +6 -4
- package/dist/cli.d.mts +0 -1
- package/dist/index.d.mts +0 -468
- package/dist/stdio-C23n_O3v.mjs +0 -4041
package/dist/cli.mjs
CHANGED
|
@@ -1,652 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
-
import path, { dirname, join } from "node:path";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { Command } from "commander";
|
|
7
|
-
import { execFile, spawn } from "node:child_process";
|
|
8
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
9
|
-
import fs$1 from "node:fs/promises";
|
|
10
|
-
import os from "node:os";
|
|
11
|
-
import { promisify } from "node:util";
|
|
12
|
-
import { serve } from "@hono/node-server";
|
|
13
|
-
|
|
14
|
-
//#region src/services/HttpServerHealthCheck.ts
|
|
15
|
-
var HttpServerHealthCheck = class {
|
|
16
|
-
async check(port) {
|
|
17
|
-
try {
|
|
18
|
-
const response = await fetch(`http://127.0.0.1:${port}/health`);
|
|
19
|
-
if (!response.ok) return {
|
|
20
|
-
healthy: false,
|
|
21
|
-
error: `Health check failed with status ${response.status}`
|
|
22
|
-
};
|
|
23
|
-
return {
|
|
24
|
-
healthy: true,
|
|
25
|
-
serviceName: (await response.json()).service
|
|
26
|
-
};
|
|
27
|
-
} catch (error) {
|
|
28
|
-
return {
|
|
29
|
-
healthy: false,
|
|
30
|
-
error: error instanceof Error ? error.message : String(error)
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
//#endregion
|
|
37
|
-
//#region src/services/HttpServerManager.ts
|
|
38
|
-
const WORKSPACE_MARKERS = [
|
|
39
|
-
"pnpm-workspace.yaml",
|
|
40
|
-
"nx.json",
|
|
41
|
-
".git"
|
|
42
|
-
];
|
|
43
|
-
const PORT_SCAN_RANGE = 25;
|
|
44
|
-
const SHELL_BINARY = "sh";
|
|
45
|
-
const LSOF_COMMAND_PREFIX = "lsof -n -P -sTCP:LISTEN";
|
|
46
|
-
const HEALTH_CHECK_STABILIZE_MS = 5e3;
|
|
47
|
-
const HEALTH_CHECK_POLL_INTERVAL_MS = 250;
|
|
48
|
-
const PROCESS_SHUTDOWN_WAIT_MS = 1e3;
|
|
49
|
-
const SIGTERM_SIGNAL = "SIGTERM";
|
|
50
|
-
const SIGKILL_SIGNAL = "SIGKILL";
|
|
51
|
-
const STATE_FILE_PREFIX = "model-proxy-mcp-http";
|
|
52
|
-
const STATE_FILE_ENCODING = "utf8";
|
|
53
|
-
const execFileAsync = promisify(execFile);
|
|
54
|
-
function resolveWorkspaceRoot(startPath = process.cwd()) {
|
|
55
|
-
let currentDir = path.resolve(startPath);
|
|
56
|
-
while (true) {
|
|
57
|
-
for (const marker of WORKSPACE_MARKERS) if (existsSync(path.join(currentDir, marker))) return currentDir;
|
|
58
|
-
const parentDir = path.dirname(currentDir);
|
|
59
|
-
if (parentDir === currentDir) return process.cwd();
|
|
60
|
-
currentDir = parentDir;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
var HttpServerManager = class {
|
|
64
|
-
repositoryPath = resolveWorkspaceRoot(process.cwd());
|
|
65
|
-
serviceName = DEFAULT_SERVICE_NAME;
|
|
66
|
-
stateFilePath = path.join(os.tmpdir(), `${STATE_FILE_PREFIX}-${Buffer.from(resolveWorkspaceRoot(process.cwd())).toString("hex")}.json`);
|
|
67
|
-
constructor(healthCheck = new HttpServerHealthCheck()) {
|
|
68
|
-
this.healthCheck = healthCheck;
|
|
69
|
-
}
|
|
70
|
-
createEmptyStatus(overrides = {}) {
|
|
71
|
-
return {
|
|
72
|
-
running: false,
|
|
73
|
-
scope: "default",
|
|
74
|
-
activeProfileId: null,
|
|
75
|
-
auth: {
|
|
76
|
-
configured: false,
|
|
77
|
-
authFilePath: ""
|
|
78
|
-
},
|
|
79
|
-
profiles: [],
|
|
80
|
-
slotModels: {},
|
|
81
|
-
...overrides
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
async getRegistration() {
|
|
85
|
-
try {
|
|
86
|
-
const rawState = await fs$1.readFile(this.stateFilePath, STATE_FILE_ENCODING);
|
|
87
|
-
const parsed = JSON.parse(rawState);
|
|
88
|
-
return parsed.port ? parsed : null;
|
|
89
|
-
} catch (error) {
|
|
90
|
-
if (error.code === "ENOENT") return null;
|
|
91
|
-
throw error;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
async releaseService(pid) {
|
|
95
|
-
const registration = await this.getRegistration();
|
|
96
|
-
if (pid && registration?.pid && registration.pid !== pid) return;
|
|
97
|
-
await fs$1.rm(this.stateFilePath, { force: true });
|
|
98
|
-
}
|
|
99
|
-
async listListeningProcesses(port) {
|
|
100
|
-
try {
|
|
101
|
-
const { stdout } = await execFileAsync(SHELL_BINARY, ["-lc", `${LSOF_COMMAND_PREFIX} -iTCP:${port} || true`], { encoding: "utf8" });
|
|
102
|
-
return stdout.split("\n").slice(1).map((line) => line.trim()).filter(Boolean).map((line) => line.split(/\s+/)).map((parts) => ({
|
|
103
|
-
pid: Number.parseInt(parts[1] || "", 10),
|
|
104
|
-
port
|
|
105
|
-
})).filter((listener) => Number.isInteger(listener.pid) && listener.pid > 0);
|
|
106
|
-
} catch (error) {
|
|
107
|
-
return [];
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
async findHealthyServicePort(startPort) {
|
|
111
|
-
for (let offset = 0; offset <= PORT_SCAN_RANGE; offset += 1) {
|
|
112
|
-
const candidatePort = startPort + offset;
|
|
113
|
-
const health = await this.healthCheck.check(candidatePort);
|
|
114
|
-
if (health.healthy && health.serviceName === this.serviceName) return candidatePort;
|
|
115
|
-
}
|
|
116
|
-
return null;
|
|
117
|
-
}
|
|
118
|
-
async clearPortListeners(port, preservePid) {
|
|
119
|
-
const listeners = await this.listListeningProcesses(port);
|
|
120
|
-
for (const listener of listeners) {
|
|
121
|
-
if (preservePid && listener.pid === preservePid) continue;
|
|
122
|
-
await this.killProcess(listener.pid);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
async registerService(port, pid) {
|
|
126
|
-
await fs$1.writeFile(this.stateFilePath, JSON.stringify({
|
|
127
|
-
port,
|
|
128
|
-
pid
|
|
129
|
-
}), STATE_FILE_ENCODING);
|
|
130
|
-
}
|
|
131
|
-
async findAvailablePort(startPort) {
|
|
132
|
-
const minimumPort = Math.min(DEFAULT_HTTP_PORT, startPort);
|
|
133
|
-
const maximumPort = Math.max(DEFAULT_HTTP_PORT + 1e3, startPort);
|
|
134
|
-
for (let candidatePort = startPort; candidatePort <= maximumPort; candidatePort += 1) if ((await this.listListeningProcesses(candidatePort)).length === 0) return candidatePort;
|
|
135
|
-
for (let candidatePort = minimumPort; candidatePort < startPort; candidatePort += 1) if ((await this.listListeningProcesses(candidatePort)).length === 0) return candidatePort;
|
|
136
|
-
throw new Error(`No available port found from ${startPort}`);
|
|
137
|
-
}
|
|
138
|
-
async fileExists(filePath) {
|
|
139
|
-
try {
|
|
140
|
-
await fs$1.access(filePath);
|
|
141
|
-
return true;
|
|
142
|
-
} catch {
|
|
143
|
-
return false;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
async resolveCliPath() {
|
|
147
|
-
const currentDir = path.dirname(fileURLToPath(import.meta.url));
|
|
148
|
-
const sameDirCliPath = path.resolve(currentDir, "cli.mjs");
|
|
149
|
-
if (await this.fileExists(sameDirCliPath)) return {
|
|
150
|
-
cliPath: sameDirCliPath,
|
|
151
|
-
useLoader: false
|
|
152
|
-
};
|
|
153
|
-
const parentDirCliPath = path.resolve(currentDir, "..", "cli.mjs");
|
|
154
|
-
if (await this.fileExists(parentDirCliPath)) return {
|
|
155
|
-
cliPath: parentDirCliPath,
|
|
156
|
-
useLoader: false
|
|
157
|
-
};
|
|
158
|
-
for (const relPath of [path.resolve(currentDir, "cli.ts"), path.resolve(currentDir, "..", "cli.ts")]) if (await this.fileExists(relPath)) return {
|
|
159
|
-
cliPath: relPath,
|
|
160
|
-
useLoader: true
|
|
161
|
-
};
|
|
162
|
-
const repoDistCliPath = path.join(this.repositoryPath, "packages", "mcp", "model-proxy-mcp", "dist", "cli.mjs");
|
|
163
|
-
if (await this.fileExists(repoDistCliPath)) return {
|
|
164
|
-
cliPath: repoDistCliPath,
|
|
165
|
-
useLoader: false
|
|
166
|
-
};
|
|
167
|
-
const repoSrcCliPath = path.join(this.repositoryPath, "packages", "mcp", "model-proxy-mcp", "src", "cli.ts");
|
|
168
|
-
if (await this.fileExists(repoSrcCliPath)) return {
|
|
169
|
-
cliPath: repoSrcCliPath,
|
|
170
|
-
useLoader: true
|
|
171
|
-
};
|
|
172
|
-
throw new Error("Cannot find model-proxy-mcp CLI");
|
|
173
|
-
}
|
|
174
|
-
async startHttpServer(port) {
|
|
175
|
-
const { cliPath, useLoader } = await this.resolveCliPath();
|
|
176
|
-
const child = spawn("node", useLoader ? [
|
|
177
|
-
"--loader",
|
|
178
|
-
"ts-node/esm",
|
|
179
|
-
cliPath,
|
|
180
|
-
"http-serve",
|
|
181
|
-
"--port",
|
|
182
|
-
String(port)
|
|
183
|
-
] : [
|
|
184
|
-
cliPath,
|
|
185
|
-
"http-serve",
|
|
186
|
-
"--port",
|
|
187
|
-
String(port)
|
|
188
|
-
], {
|
|
189
|
-
detached: true,
|
|
190
|
-
stdio: "ignore",
|
|
191
|
-
env: {
|
|
192
|
-
...process.env,
|
|
193
|
-
NODE_ENV: process.env.NODE_ENV || "development"
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
child.unref();
|
|
197
|
-
if (!child.pid) throw new Error("Failed to spawn HTTP server");
|
|
198
|
-
return child.pid;
|
|
199
|
-
}
|
|
200
|
-
async killProcess(pid) {
|
|
201
|
-
try {
|
|
202
|
-
process.kill(pid, SIGTERM_SIGNAL);
|
|
203
|
-
await new Promise((resolve) => setTimeout(resolve, PROCESS_SHUTDOWN_WAIT_MS));
|
|
204
|
-
try {
|
|
205
|
-
process.kill(pid, 0);
|
|
206
|
-
process.kill(pid, SIGKILL_SIGNAL);
|
|
207
|
-
} catch {
|
|
208
|
-
return;
|
|
209
|
-
}
|
|
210
|
-
} catch {
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
async waitForHealthy(port) {
|
|
215
|
-
const deadline = Date.now() + HEALTH_CHECK_STABILIZE_MS;
|
|
216
|
-
let lastError = "Server failed health check after startup";
|
|
217
|
-
while (Date.now() < deadline) {
|
|
218
|
-
const health = await this.healthCheck.check(port);
|
|
219
|
-
if (health.healthy && health.serviceName === this.serviceName) return { healthy: true };
|
|
220
|
-
lastError = health.error || `Unexpected service on port ${port}`;
|
|
221
|
-
await new Promise((resolve) => setTimeout(resolve, HEALTH_CHECK_POLL_INTERVAL_MS));
|
|
222
|
-
}
|
|
223
|
-
return {
|
|
224
|
-
healthy: false,
|
|
225
|
-
error: lastError
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
async ensureRunning(port = DEFAULT_HTTP_PORT) {
|
|
229
|
-
try {
|
|
230
|
-
const healthyPort = await this.findHealthyServicePort(port);
|
|
231
|
-
if (healthyPort !== null) {
|
|
232
|
-
const healthyPid = (await this.listListeningProcesses(healthyPort))[0]?.pid;
|
|
233
|
-
await this.registerService(healthyPort, healthyPid ?? process.pid);
|
|
234
|
-
return this.createEmptyStatus({
|
|
235
|
-
running: true,
|
|
236
|
-
port: healthyPort,
|
|
237
|
-
pid: healthyPid
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
const existing = await this.getRegistration();
|
|
241
|
-
if (existing) {
|
|
242
|
-
const health$1 = await this.healthCheck.check(existing.port);
|
|
243
|
-
if (health$1.healthy && health$1.serviceName === this.serviceName) return this.createEmptyStatus({
|
|
244
|
-
running: true,
|
|
245
|
-
port: existing.port,
|
|
246
|
-
pid: existing.pid
|
|
247
|
-
});
|
|
248
|
-
if (existing.pid) await this.killProcess(existing.pid);
|
|
249
|
-
await this.clearPortListeners(existing.port, existing.pid);
|
|
250
|
-
await this.releaseService(existing.pid);
|
|
251
|
-
}
|
|
252
|
-
await this.clearPortListeners(port);
|
|
253
|
-
const availablePort = await this.findAvailablePort(port);
|
|
254
|
-
const pid = await this.startHttpServer(availablePort);
|
|
255
|
-
const health = await this.waitForHealthy(availablePort);
|
|
256
|
-
if (!health.healthy) {
|
|
257
|
-
await this.killProcess(pid);
|
|
258
|
-
await this.clearPortListeners(availablePort, pid);
|
|
259
|
-
await this.releaseService(pid);
|
|
260
|
-
return this.createEmptyStatus({ error: health.error || "Server failed health check after startup" });
|
|
261
|
-
}
|
|
262
|
-
await this.registerService(availablePort, pid);
|
|
263
|
-
return this.createEmptyStatus({
|
|
264
|
-
running: true,
|
|
265
|
-
port: availablePort,
|
|
266
|
-
pid
|
|
267
|
-
});
|
|
268
|
-
} catch (error) {
|
|
269
|
-
return this.createEmptyStatus({ error: error instanceof Error ? error.message : String(error) });
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
async stop() {
|
|
273
|
-
const registration = await this.getRegistration();
|
|
274
|
-
let stopped = false;
|
|
275
|
-
if (registration?.pid) {
|
|
276
|
-
await this.killProcess(registration.pid);
|
|
277
|
-
stopped = true;
|
|
278
|
-
}
|
|
279
|
-
if (registration) {
|
|
280
|
-
await this.clearPortListeners(registration.port, registration.pid);
|
|
281
|
-
await this.releaseService(registration.pid);
|
|
282
|
-
}
|
|
283
|
-
const healthyPort = await this.findHealthyServicePort(DEFAULT_HTTP_PORT);
|
|
284
|
-
if (healthyPort !== null) {
|
|
285
|
-
const listeners = await this.listListeningProcesses(healthyPort);
|
|
286
|
-
for (const listener of listeners) {
|
|
287
|
-
await this.killProcess(listener.pid);
|
|
288
|
-
stopped = true;
|
|
289
|
-
}
|
|
290
|
-
await this.releaseService();
|
|
291
|
-
}
|
|
292
|
-
return stopped;
|
|
293
|
-
}
|
|
294
|
-
async getStatus() {
|
|
295
|
-
const registration = await this.getRegistration();
|
|
296
|
-
if (registration) {
|
|
297
|
-
if ((await this.healthCheck.check(registration.port)).healthy) return this.createEmptyStatus({
|
|
298
|
-
running: true,
|
|
299
|
-
port: registration.port,
|
|
300
|
-
pid: registration.pid
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
const healthyPort = await this.findHealthyServicePort(DEFAULT_HTTP_PORT);
|
|
304
|
-
if (healthyPort !== null) {
|
|
305
|
-
const pid = (await this.listListeningProcesses(healthyPort))[0]?.pid;
|
|
306
|
-
if (pid) await this.registerService(healthyPort, pid);
|
|
307
|
-
return this.createEmptyStatus({
|
|
308
|
-
running: true,
|
|
309
|
-
port: healthyPort,
|
|
310
|
-
pid
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
return this.createEmptyStatus({ error: registration ? "Registered server is unhealthy" : "No HTTP server registered" });
|
|
314
|
-
}
|
|
315
|
-
};
|
|
316
|
-
|
|
317
|
-
//#endregion
|
|
318
|
-
//#region src/commands/claude.ts
|
|
319
|
-
const CLAUDE_BINARY = "claude";
|
|
320
|
-
const DEFAULT_SCOPE$2 = "default";
|
|
321
|
-
const SESSIONS_DIRECTORY_NAME = ".claude-sessions";
|
|
322
|
-
const RANDOM_SCOPE_PREFIX = "scope";
|
|
323
|
-
const RANDOM_SCOPE_BYTES = 3;
|
|
324
|
-
const TEXT_ENCODING = "utf8";
|
|
325
|
-
const STDIO_INHERIT = "inherit";
|
|
326
|
-
const DECIMAL_RADIX = 10;
|
|
327
|
-
const LOG_PREFIX = "[model-proxy-mcp]";
|
|
328
|
-
const RECOVERY_MESSAGE = `Recovery: verify HOME, proxy port, and that \`${CLAUDE_BINARY}\` is on PATH.`;
|
|
329
|
-
const ARG_RESUME = "--resume";
|
|
330
|
-
const ARG_SESSION_ID = "--session-id";
|
|
331
|
-
const ARG_SKIP_PERMISSIONS = "--dangerously-skip-permissions";
|
|
332
|
-
const MODEL_ALIAS_OPUS = "ccproxy-opus";
|
|
333
|
-
const MODEL_ALIAS_SONNET = "ccproxy-sonnet";
|
|
334
|
-
const MODEL_ALIAS_HAIKU = "ccproxy-haiku";
|
|
335
|
-
const MODEL_ALIAS_SUBAGENT = "ccproxy-subagent";
|
|
336
|
-
const DEFAULT_SCOPE_SEED_FILE = "model-proxy-mcp.yaml";
|
|
337
|
-
const MODEL_PROXY_SCOPE_ENV$1 = "MODEL_PROXY_MCP_SCOPE";
|
|
338
|
-
const MODEL_PROXY_SLOT_ENV = "MODEL_PROXY_MCP_SLOT";
|
|
339
|
-
const DEFAULT_MODEL_PROXY_SLOT = "default";
|
|
340
|
-
var ClaudeCommandError = class extends Error {
|
|
341
|
-
constructor(message, code, options) {
|
|
342
|
-
super(message, options);
|
|
343
|
-
this.code = code;
|
|
344
|
-
this.name = "ClaudeCommandError";
|
|
345
|
-
}
|
|
346
|
-
};
|
|
347
|
-
var ClaudeCommandConfigError = class extends ClaudeCommandError {
|
|
348
|
-
constructor(message, options) {
|
|
349
|
-
super(message, "CLAUDE_COMMAND_CONFIG_ERROR", options);
|
|
350
|
-
this.name = "ClaudeCommandConfigError";
|
|
351
|
-
}
|
|
352
|
-
};
|
|
353
|
-
var ClaudeCommandValidationError = class extends ClaudeCommandError {
|
|
354
|
-
constructor(message, options) {
|
|
355
|
-
super(message, "CLAUDE_COMMAND_VALIDATION_ERROR", options);
|
|
356
|
-
this.name = "ClaudeCommandValidationError";
|
|
357
|
-
}
|
|
358
|
-
};
|
|
359
|
-
var ClaudeCommandLaunchError = class extends ClaudeCommandError {
|
|
360
|
-
constructor(message, options) {
|
|
361
|
-
super(message, "CLAUDE_COMMAND_LAUNCH_ERROR", options);
|
|
362
|
-
this.name = "ClaudeCommandLaunchError";
|
|
363
|
-
}
|
|
364
|
-
};
|
|
365
|
-
function sanitizeScope(scope) {
|
|
366
|
-
return scope.trim().replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || DEFAULT_SCOPE$2;
|
|
367
|
-
}
|
|
368
|
-
function generateScopeName() {
|
|
369
|
-
return `${RANDOM_SCOPE_PREFIX}-${randomBytes(RANDOM_SCOPE_BYTES).toString("hex")}`;
|
|
370
|
-
}
|
|
371
|
-
function buildClaudeEnvironment(port, scope, baseEnvironment = process.env) {
|
|
372
|
-
return {
|
|
373
|
-
...baseEnvironment,
|
|
374
|
-
ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}/scopes/${scope}`,
|
|
375
|
-
ANTHROPIC_DEFAULT_OPUS_MODEL: baseEnvironment.ANTHROPIC_DEFAULT_OPUS_MODEL || MODEL_ALIAS_OPUS,
|
|
376
|
-
ANTHROPIC_DEFAULT_SONNET_MODEL: baseEnvironment.ANTHROPIC_DEFAULT_SONNET_MODEL || MODEL_ALIAS_SONNET,
|
|
377
|
-
ANTHROPIC_DEFAULT_HAIKU_MODEL: baseEnvironment.ANTHROPIC_DEFAULT_HAIKU_MODEL || MODEL_ALIAS_HAIKU,
|
|
378
|
-
CLAUDE_CODE_SUBAGENT_MODEL: baseEnvironment.CLAUDE_CODE_SUBAGENT_MODEL || MODEL_ALIAS_SUBAGENT,
|
|
379
|
-
MODEL_PROXY_MCP_SCOPE: baseEnvironment[MODEL_PROXY_SCOPE_ENV$1] || scope,
|
|
380
|
-
MODEL_PROXY_MCP_SLOT: baseEnvironment[MODEL_PROXY_SLOT_ENV] || DEFAULT_MODEL_PROXY_SLOT
|
|
381
|
-
};
|
|
382
|
-
}
|
|
383
|
-
async function resolveScopeSeedConfigPath(configFile, workingDirectory = process.cwd()) {
|
|
384
|
-
const candidate = configFile ? path.resolve(workingDirectory, configFile) : path.join(workingDirectory, DEFAULT_SCOPE_SEED_FILE);
|
|
385
|
-
try {
|
|
386
|
-
if (!(await fs$1.stat(candidate)).isFile()) {
|
|
387
|
-
if (configFile) throw new ClaudeCommandConfigError(`Scope seed config path is not a file: ${candidate}`);
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
return candidate;
|
|
391
|
-
} catch (error) {
|
|
392
|
-
if (error.code === "ENOENT") {
|
|
393
|
-
if (configFile) throw new ClaudeCommandConfigError(`Scope seed config file not found: ${candidate}`, { cause: error });
|
|
394
|
-
return;
|
|
395
|
-
}
|
|
396
|
-
if (error instanceof ClaudeCommandConfigError) throw error;
|
|
397
|
-
throw new ClaudeCommandConfigError(`Failed to read scope seed config file: ${candidate}`, { cause: error });
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
function getSessionsDirectory() {
|
|
401
|
-
const homeDirectory = process.env.HOME || process.env.USERPROFILE;
|
|
402
|
-
if (!homeDirectory) throw new ClaudeCommandConfigError("HOME or USERPROFILE is not set");
|
|
403
|
-
return path.join(homeDirectory, SESSIONS_DIRECTORY_NAME);
|
|
404
|
-
}
|
|
405
|
-
async function ensureSessionsDirectory() {
|
|
406
|
-
const sessionsDirectory = getSessionsDirectory();
|
|
407
|
-
await fs$1.mkdir(sessionsDirectory, { recursive: true });
|
|
408
|
-
return sessionsDirectory;
|
|
409
|
-
}
|
|
410
|
-
async function readSessionId(sessionFile) {
|
|
411
|
-
try {
|
|
412
|
-
return (await fs$1.readFile(sessionFile, TEXT_ENCODING)).trim() || null;
|
|
413
|
-
} catch (error) {
|
|
414
|
-
if (error.code === "ENOENT") return null;
|
|
415
|
-
throw new ClaudeCommandConfigError(`Failed to read Claude session file: ${sessionFile}`, { cause: error });
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
async function resolveSessionId(scope, clearSession) {
|
|
419
|
-
const sessionsDirectory = await ensureSessionsDirectory();
|
|
420
|
-
const sessionFile = path.join(sessionsDirectory, scope);
|
|
421
|
-
if (clearSession) try {
|
|
422
|
-
await fs$1.rm(sessionFile, { force: true });
|
|
423
|
-
} catch (error) {
|
|
424
|
-
throw new ClaudeCommandConfigError(`Failed to clear Claude session file: ${sessionFile}`, { cause: error });
|
|
425
|
-
}
|
|
426
|
-
const existingSessionId = await readSessionId(sessionFile);
|
|
427
|
-
if (existingSessionId) return {
|
|
428
|
-
sessionId: existingSessionId,
|
|
429
|
-
resume: true
|
|
430
|
-
};
|
|
431
|
-
const sessionId = randomUUID().toLowerCase();
|
|
432
|
-
try {
|
|
433
|
-
await fs$1.writeFile(sessionFile, `${sessionId}\n`, TEXT_ENCODING);
|
|
434
|
-
} catch (error) {
|
|
435
|
-
throw new ClaudeCommandConfigError(`Failed to write Claude session file: ${sessionFile}`, { cause: error });
|
|
436
|
-
}
|
|
437
|
-
return {
|
|
438
|
-
sessionId,
|
|
439
|
-
resume: false
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
async function launchClaude(scope, port, clearSession, claudeArgs, configFile) {
|
|
443
|
-
const scopeSeedConfigPath = await resolveScopeSeedConfigPath(configFile);
|
|
444
|
-
await new ProfileStore().ensureConfig(scope, scopeSeedConfigPath);
|
|
445
|
-
const status = await new HttpServerManager().ensureRunning(port);
|
|
446
|
-
if (!status.running || !status.port) throw new ClaudeCommandLaunchError(status.error || "Failed to start model proxy HTTP server");
|
|
447
|
-
const { sessionId, resume } = await resolveSessionId(scope, clearSession);
|
|
448
|
-
const env = buildClaudeEnvironment(status.port, scope);
|
|
449
|
-
const args = [
|
|
450
|
-
ARG_SKIP_PERMISSIONS,
|
|
451
|
-
...resume ? [ARG_RESUME, sessionId] : [ARG_SESSION_ID, sessionId],
|
|
452
|
-
...claudeArgs
|
|
453
|
-
];
|
|
454
|
-
console.log(`${LOG_PREFIX} Scope: ${scope}`);
|
|
455
|
-
console.log(`${LOG_PREFIX} Proxy: ${env.ANTHROPIC_BASE_URL}`);
|
|
456
|
-
console.log(`${LOG_PREFIX} Session: ${sessionId}${resume ? " (resume)" : " (new)"}`);
|
|
457
|
-
if (scopeSeedConfigPath) console.log(`${LOG_PREFIX} Scope config seed: ${scopeSeedConfigPath}`);
|
|
458
|
-
return new Promise((resolve, reject) => {
|
|
459
|
-
const child = spawn(CLAUDE_BINARY, args, {
|
|
460
|
-
stdio: STDIO_INHERIT,
|
|
461
|
-
env
|
|
462
|
-
});
|
|
463
|
-
child.on("error", (error) => {
|
|
464
|
-
reject(new ClaudeCommandLaunchError(`Failed to launch ${CLAUDE_BINARY}`, { cause: error }));
|
|
465
|
-
});
|
|
466
|
-
child.on("exit", (code, signal) => {
|
|
467
|
-
if (signal) {
|
|
468
|
-
reject(new ClaudeCommandLaunchError(`${CLAUDE_BINARY} exited with signal ${signal}`));
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
resolve(code ?? 0);
|
|
472
|
-
});
|
|
473
|
-
});
|
|
474
|
-
}
|
|
475
|
-
const claudeCommand = new 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(DEFAULT_HTTP_PORT)).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", false).allowUnknownOption(true).allowExcessArguments(true).argument("[claudeArgs...]").action(async (claudeArgs, options) => {
|
|
476
|
-
try {
|
|
477
|
-
const resolvedScope = sanitizeScope(options.scope || generateScopeName());
|
|
478
|
-
const port = Number.parseInt(options.port, DECIMAL_RADIX);
|
|
479
|
-
if (!Number.isInteger(port) || port <= 0) throw new ClaudeCommandValidationError(`Invalid port: ${options.port}`);
|
|
480
|
-
const exitCode = await launchClaude(resolvedScope, port, options.clearSession, claudeArgs, options.configFile ?? options.config);
|
|
481
|
-
process.exit(exitCode);
|
|
482
|
-
} catch (error) {
|
|
483
|
-
const commandError = error instanceof ClaudeCommandError ? error : new ClaudeCommandLaunchError("Failed to launch Claude", { cause: error });
|
|
484
|
-
console.error(`${LOG_PREFIX} ${commandError.code}: ${commandError.message}`);
|
|
485
|
-
console.error(`${LOG_PREFIX} ${RECOVERY_MESSAGE}`);
|
|
486
|
-
if (commandError.cause) console.error(`${LOG_PREFIX} Cause:`, commandError.cause);
|
|
487
|
-
process.exit(1);
|
|
488
|
-
}
|
|
489
|
-
});
|
|
490
|
-
|
|
491
|
-
//#endregion
|
|
492
|
-
//#region src/commands/http-serve.ts
|
|
493
|
-
const LOCAL_HOST = "127.0.0.1";
|
|
494
|
-
const httpServeCommand = new Command("http-serve").description("Start the Claude-compatible HTTP model proxy server").option("-p, --port <port>", "Port to listen on", String(DEFAULT_HTTP_PORT)).action(async (options) => {
|
|
495
|
-
try {
|
|
496
|
-
const port = Number.parseInt(options.port, 10);
|
|
497
|
-
if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid port: ${options.port}`);
|
|
498
|
-
const gatewayService = new GatewayService();
|
|
499
|
-
await gatewayService.ensureConfig();
|
|
500
|
-
const server = serve({
|
|
501
|
-
fetch: createHttpServer(gatewayService).fetch,
|
|
502
|
-
port,
|
|
503
|
-
hostname: LOCAL_HOST
|
|
504
|
-
});
|
|
505
|
-
console.log(`model-proxy-mcp listening on http://${LOCAL_HOST}:${port}`);
|
|
506
|
-
console.log(`Claude base URL: http://${LOCAL_HOST}:${port}`);
|
|
507
|
-
const shutdown = (signal) => {
|
|
508
|
-
console.log(`\n${signal} received. Shutting down...`);
|
|
509
|
-
server.close();
|
|
510
|
-
process.exit(0);
|
|
511
|
-
};
|
|
512
|
-
process.once("SIGINT", () => shutdown("SIGINT"));
|
|
513
|
-
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
|
514
|
-
} catch (error) {
|
|
515
|
-
console.error("Failed to start HTTP server:", error);
|
|
516
|
-
process.exit(1);
|
|
517
|
-
}
|
|
518
|
-
});
|
|
519
|
-
|
|
520
|
-
//#endregion
|
|
521
|
-
//#region src/commands/mcp-serve.ts
|
|
522
|
-
const DEFAULT_SCOPE$1 = "default";
|
|
523
|
-
const MODEL_PROXY_SCOPE_ENV = "MODEL_PROXY_MCP_SCOPE";
|
|
524
|
-
const mcpServeCommand = new Command("mcp-serve").description("Start MCP server with stdio transport").option("--cleanup", "Stop HTTP server on shutdown", false).option("-p, --port <port>", "Port for HTTP server", String(DEFAULT_HTTP_PORT)).action(async (options) => {
|
|
525
|
-
try {
|
|
526
|
-
const port = Number.parseInt(options.port, 10);
|
|
527
|
-
if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid port: ${options.port}`);
|
|
528
|
-
const gatewayService = new GatewayService();
|
|
529
|
-
await gatewayService.ensureConfig(process.env[MODEL_PROXY_SCOPE_ENV] || DEFAULT_SCOPE$1);
|
|
530
|
-
const manager = new HttpServerManager();
|
|
531
|
-
const httpStatus = await manager.ensureRunning(port);
|
|
532
|
-
if (!httpStatus.running) console.error(`Warning: HTTP server failed to start: ${httpStatus.error}`);
|
|
533
|
-
const handler = new StdioTransportHandler(createServer(gatewayService));
|
|
534
|
-
const shutdown = async (signal) => {
|
|
535
|
-
console.error(`\nReceived ${signal}, shutting down gracefully...`);
|
|
536
|
-
await handler.stop();
|
|
537
|
-
if (options.cleanup && httpStatus.running) await manager.stop();
|
|
538
|
-
process.exit(0);
|
|
539
|
-
};
|
|
540
|
-
process.once("SIGINT", () => void shutdown("SIGINT").catch((error) => {
|
|
541
|
-
console.error("Failed to shut down after SIGINT:", error);
|
|
542
|
-
process.exit(1);
|
|
543
|
-
}));
|
|
544
|
-
process.once("SIGTERM", () => void shutdown("SIGTERM").catch((error) => {
|
|
545
|
-
console.error("Failed to shut down after SIGTERM:", error);
|
|
546
|
-
process.exit(1);
|
|
547
|
-
}));
|
|
548
|
-
await handler.start();
|
|
549
|
-
} catch (error) {
|
|
550
|
-
console.error("Failed to start MCP server:", error);
|
|
551
|
-
process.exit(1);
|
|
552
|
-
}
|
|
553
|
-
});
|
|
554
|
-
|
|
555
|
-
//#endregion
|
|
556
|
-
//#region src/commands/start.ts
|
|
557
|
-
const startCommand = new Command("start").description("Start HTTP and/or MCP server for the model proxy").option("--mcp-only", "Start only the MCP server", false).option("--http-only", "Start only the HTTP server", false).option("-p, --port <port>", "Port for HTTP server", String(DEFAULT_HTTP_PORT)).action(async (options) => {
|
|
558
|
-
try {
|
|
559
|
-
const httpServerManager = new HttpServerManager();
|
|
560
|
-
const port = Number.parseInt(options.port, 10);
|
|
561
|
-
const startHttp = !options.mcpOnly;
|
|
562
|
-
const startMcp = !options.httpOnly;
|
|
563
|
-
if (startHttp) {
|
|
564
|
-
const status = await httpServerManager.ensureRunning(port);
|
|
565
|
-
if (!status.running) {
|
|
566
|
-
console.error(`HTTP server failed to start: ${status.error}`);
|
|
567
|
-
process.exit(1);
|
|
568
|
-
}
|
|
569
|
-
console.log(`HTTP server running on http://127.0.0.1:${status.port}`);
|
|
570
|
-
}
|
|
571
|
-
if (startMcp) {
|
|
572
|
-
const handler = new StdioTransportHandler(createServer());
|
|
573
|
-
await handler.start();
|
|
574
|
-
const shutdown = async (signal) => {
|
|
575
|
-
console.error(`\n${signal} received. Shutting down...`);
|
|
576
|
-
await handler.stop();
|
|
577
|
-
process.exit(0);
|
|
578
|
-
};
|
|
579
|
-
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
580
|
-
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
581
|
-
} else process.exit(0);
|
|
582
|
-
} catch (error) {
|
|
583
|
-
console.error("Failed to start services:", error);
|
|
584
|
-
process.exit(1);
|
|
585
|
-
}
|
|
586
|
-
});
|
|
587
|
-
|
|
588
|
-
//#endregion
|
|
589
|
-
//#region src/commands/status.ts
|
|
590
|
-
const DEFAULT_SCOPE = "default";
|
|
591
|
-
const STATUS_COMMAND_NAME = "status";
|
|
592
|
-
const STATUS_COMMAND_DESCRIPTION = "Show proxy server and profile status";
|
|
593
|
-
const STATUS_ERROR_MESSAGE = "Failed to read status";
|
|
594
|
-
var StatusCommandError = class extends Error {
|
|
595
|
-
code = "STATUS_CHECK_FAILED";
|
|
596
|
-
constructor(cause) {
|
|
597
|
-
super(STATUS_ERROR_MESSAGE, { cause: cause instanceof Error ? cause : new Error(String(cause)) });
|
|
598
|
-
this.name = "StatusCommandError";
|
|
599
|
-
}
|
|
600
|
-
};
|
|
601
|
-
const statusCommand = new Command(STATUS_COMMAND_NAME).description(STATUS_COMMAND_DESCRIPTION).option("-s, --scope <scope>", "Configuration scope", DEFAULT_SCOPE).action(async (options) => {
|
|
602
|
-
try {
|
|
603
|
-
const serverStatus = await new HttpServerManager().getStatus();
|
|
604
|
-
const status = await new GatewayService().getStatus(options.scope, serverStatus.port, serverStatus.pid);
|
|
605
|
-
status.running = serverStatus.running;
|
|
606
|
-
status.error = serverStatus.error;
|
|
607
|
-
consoleLogger.info(JSON.stringify(status, null, 2));
|
|
608
|
-
process.exit(0);
|
|
609
|
-
} catch (error) {
|
|
610
|
-
const statusError = new StatusCommandError(error);
|
|
611
|
-
consoleLogger.error(STATUS_ERROR_MESSAGE, {
|
|
612
|
-
command: STATUS_COMMAND_NAME,
|
|
613
|
-
code: statusError.code,
|
|
614
|
-
scope: options.scope,
|
|
615
|
-
cause: statusError.cause
|
|
616
|
-
});
|
|
617
|
-
process.exit(1);
|
|
618
|
-
}
|
|
619
|
-
});
|
|
620
|
-
|
|
621
|
-
//#endregion
|
|
622
|
-
//#region src/commands/stop.ts
|
|
623
|
-
const stopCommand = new Command("stop").description("Stop the background HTTP server").action(async () => {
|
|
624
|
-
try {
|
|
625
|
-
const stopped = await new HttpServerManager().stop();
|
|
626
|
-
console.log(stopped ? "HTTP server stopped" : "No HTTP server running");
|
|
627
|
-
process.exit(0);
|
|
628
|
-
} catch (error) {
|
|
629
|
-
console.error("Failed to stop HTTP server:", error);
|
|
630
|
-
process.exit(1);
|
|
631
|
-
}
|
|
632
|
-
});
|
|
633
|
-
|
|
634
|
-
//#endregion
|
|
635
|
-
//#region src/cli.ts
|
|
636
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
637
|
-
const packageJson = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
|
|
638
|
-
async function main() {
|
|
639
|
-
const program = new Command();
|
|
640
|
-
program.name("model-proxy-mcp").description("Claude-compatible model proxy MCP").version(packageJson.version);
|
|
641
|
-
program.addCommand(startCommand);
|
|
642
|
-
program.addCommand(stopCommand);
|
|
643
|
-
program.addCommand(statusCommand);
|
|
644
|
-
program.addCommand(claudeCommand);
|
|
645
|
-
program.addCommand(httpServeCommand);
|
|
646
|
-
program.addCommand(mcpServeCommand);
|
|
647
|
-
await program.parseAsync(process.argv);
|
|
648
|
-
}
|
|
649
|
-
main();
|
|
650
|
-
|
|
651
|
-
//#endregion
|
|
652
|
-
export { };
|
|
2
|
+
import{c as e,i as t,l as n,n as r,o as i,r as a,s as o,t as s}from"./stdio-xpvsxU_k.mjs";import{existsSync as c,readFileSync as l}from"node:fs";import u,{dirname as d,join as f}from"node:path";import{fileURLToPath as p}from"node:url";import{Command as m}from"commander";import{execFile as h,spawn as g}from"node:child_process";import{randomBytes as _,randomUUID as v}from"node:crypto";import y from"node:fs/promises";import b from"node:os";import{promisify as x}from"node:util";import{serve as S}from"@hono/node-server";var C=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 w=[`pnpm-workspace.yaml`,`nx.json`,`.git`],T=`utf8`,E=x(h);function D(e=process.cwd()){let t=u.resolve(e);for(;;){for(let e of w)if(c(u.join(t,e)))return t;let e=u.dirname(t);if(e===t)return process.cwd();t=e}}var O=class{repositoryPath=D(process.cwd());serviceName=n;stateFilePath=u.join(b.tmpdir(),`model-proxy-mcp-http-${Buffer.from(D(process.cwd())).toString(`hex`)}.json`);constructor(e=new C){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 y.readFile(this.stateFilePath,T),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 y.rm(this.stateFilePath,{force:!0})}async listListeningProcesses(e){try{let{stdout:t}=await E(`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 y.writeFile(this.stateFilePath,JSON.stringify({port:e,pid:t}),T)}async findAvailablePort(t){let n=Math.min(e,t),r=Math.max(e+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 y.access(e),!0}catch{return!1}}async resolveCliPath(){let e=u.dirname(p(import.meta.url)),t=u.resolve(e,`cli.mjs`);if(await this.fileExists(t))return{cliPath:t,useLoader:!1};let n=u.resolve(e,`..`,`cli.mjs`);if(await this.fileExists(n))return{cliPath:n,useLoader:!1};for(let t of[u.resolve(e,`cli.ts`),u.resolve(e,`..`,`cli.ts`)])if(await this.fileExists(t))return{cliPath:t,useLoader:!0};let r=u.join(this.repositoryPath,`packages`,`mcp`,`model-proxy-mcp`,`dist`,`cli.mjs`);if(await this.fileExists(r))return{cliPath:r,useLoader:!1};let i=u.join(this.repositoryPath,`packages`,`mcp`,`model-proxy-mcp`,`src`,`cli.ts`);if(await this.fileExists(i))return{cliPath:i,useLoader:!0};throw Error(`Cannot find model-proxy-mcp CLI`)}async startHttpServer(e){let{cliPath:t,useLoader:n}=await this.resolveCliPath(),r=g(`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){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);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);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 k=`claude`,A=`utf8`,j=`[model-proxy-mcp]`,M=`Recovery: verify HOME, proxy port, and that \`${k}\` is on PATH.`;var N=class extends Error{constructor(e,t,n){super(e,n),this.code=t,this.name=`ClaudeCommandError`}},P=class extends N{constructor(e,t){super(e,`CLAUDE_COMMAND_CONFIG_ERROR`,t),this.name=`ClaudeCommandConfigError`}},F=class extends N{constructor(e,t){super(e,`CLAUDE_COMMAND_VALIDATION_ERROR`,t),this.name=`ClaudeCommandValidationError`}},I=class extends N{constructor(e,t){super(e,`CLAUDE_COMMAND_LAUNCH_ERROR`,t),this.name=`ClaudeCommandLaunchError`}};function L(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)||`default`}function R(){return`scope-${_(3).toString(`hex`)}`}function z(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 B(e,t=process.cwd()){let n=e?u.resolve(t,e):u.join(t,`model-proxy-mcp.yaml`);try{if(!(await y.stat(n)).isFile()){if(e)throw new P(`Scope seed config path is not a file: ${n}`);return}return n}catch(t){if(t.code===`ENOENT`){if(e)throw new P(`Scope seed config file not found: ${n}`,{cause:t});return}throw t instanceof P?t:new P(`Failed to read scope seed config file: ${n}`,{cause:t})}}function V(){let e=process.env.HOME||process.env.USERPROFILE;if(!e)throw new P(`HOME or USERPROFILE is not set`);return u.join(e,`.claude-sessions`)}async function H(){let e=V();return await y.mkdir(e,{recursive:!0}),e}async function U(e){try{return(await y.readFile(e,A)).trim()||null}catch(t){if(t.code===`ENOENT`)return null;throw new P(`Failed to read Claude session file: ${e}`,{cause:t})}}async function W(e,t){let n=await H(),r=u.join(n,e);if(t)try{await y.rm(r,{force:!0})}catch(e){throw new P(`Failed to clear Claude session file: ${r}`,{cause:e})}let i=await U(r);if(i)return{sessionId:i,resume:!0};let a=v().toLowerCase();try{await y.writeFile(r,`${a}\n`,A)}catch(e){throw new P(`Failed to write Claude session file: ${r}`,{cause:e})}return{sessionId:a,resume:!1}}async function G(e,t,n,r,a){let o=await B(a);await new i().ensureConfig(e,o);let s=await new O().ensureRunning(t);if(!s.running||!s.port)throw new I(s.error||`Failed to start model proxy HTTP server`);let{sessionId:c,resume:l}=await W(e,n),u=z(s.port,e),d=[`--dangerously-skip-permissions`,...l?[`--resume`,c]:[`--session-id`,c],...r];return console.log(`${j} Scope: ${e}`),console.log(`${j} Proxy: ${u.ANTHROPIC_BASE_URL}`),console.log(`${j} Session: ${c}${l?` (resume)`:` (new)`}`),o&&console.log(`${j} Scope config seed: ${o}`),new Promise((e,t)=>{let n=g(k,d,{stdio:`inherit`,env:u});n.on(`error`,e=>{t(new I(`Failed to launch ${k}`,{cause:e}))}),n.on(`exit`,(n,r)=>{if(r){t(new I(`${k} exited with signal ${r}`));return}e(n??0)})})}const K=new m(`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)).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=L(t.scope||R()),r=Number.parseInt(t.port,10);if(!Number.isInteger(r)||r<=0)throw new F(`Invalid port: ${t.port}`);let i=await G(n,r,t.clearSession,e,t.configFile??t.config);process.exit(i)}catch(e){let t=e instanceof N?e:new I(`Failed to launch Claude`,{cause:e});console.error(`${j} ${t.code}: ${t.message}`),console.error(`${j} ${M}`),t.cause&&console.error(`${j} Cause:`,t.cause),process.exit(1)}}),q=`127.0.0.1`,J=new m(`http-serve`).description(`Start the Claude-compatible HTTP model proxy server`).option(`-p, --port <port>`,`Port to listen on`,String(e)).action(async e=>{try{let n=Number.parseInt(e.port,10);if(!Number.isInteger(n)||n<=0)throw Error(`Invalid port: ${e.port}`);let r=new t;await r.ensureConfig();let i=S({fetch:a(r).fetch,port:n,hostname:q});console.log(`model-proxy-mcp listening on http://${q}:${n}`),console.log(`Claude base URL: http://${q}:${n}`);let o=e=>{console.log(`\n${e} received. Shutting down...`),i.close(),process.exit(0)};process.once(`SIGINT`,()=>o(`SIGINT`)),process.once(`SIGTERM`,()=>o(`SIGTERM`))}catch(e){console.error(`Failed to start HTTP server:`,e),process.exit(1)}}),Y=new m(`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)).action(async e=>{try{let n=Number.parseInt(e.port,10);if(!Number.isInteger(n)||n<=0)throw Error(`Invalid port: ${e.port}`);let i=new t;await i.ensureConfig(process.env.MODEL_PROXY_MCP_SCOPE||`default`);let a=new O,o=await a.ensureRunning(n);o.running||console.error(`Warning: HTTP server failed to start: ${o.error}`);let c=new s(r(i)),l=async t=>{console.error(`\nReceived ${t}, shutting down gracefully...`),await c.stop(),e.cleanup&&o.running&&await a.stop(),process.exit(0)};process.once(`SIGINT`,()=>void l(`SIGINT`).catch(e=>{console.error(`Failed to shut down after SIGINT:`,e),process.exit(1)})),process.once(`SIGTERM`,()=>void l(`SIGTERM`).catch(e=>{console.error(`Failed to shut down after SIGTERM:`,e),process.exit(1)})),await c.start()}catch(e){console.error(`Failed to start MCP server:`,e),process.exit(1)}}),X=new m(`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)).action(async e=>{try{let t=new O,n=Number.parseInt(e.port,10),i=!e.mcpOnly,a=!e.httpOnly;if(i){let e=await t.ensureRunning(n);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 e=new s(r());await e.start();let t=async t=>{console.error(`\n${t} received. Shutting down...`),await e.stop(),process.exit(0)};process.on(`SIGINT`,()=>t(`SIGINT`)),process.on(`SIGTERM`,()=>t(`SIGTERM`))}else process.exit(0)}catch(e){console.error(`Failed to start services:`,e),process.exit(1)}}),Z=`status`,Q=`Failed to read status`;var $=class extends Error{code=`STATUS_CHECK_FAILED`;constructor(e){super(Q,{cause:e instanceof Error?e:Error(String(e))}),this.name=`StatusCommandError`}};const ee=new m(Z).description(`Show proxy server and profile status`).option(`-s, --scope <scope>`,`Configuration scope`,`default`).action(async e=>{try{let n=await new O().getStatus(),r=await new t().getStatus(e.scope,n.port,n.pid);r.running=n.running,r.error=n.error,o.info(JSON.stringify(r,null,2)),process.exit(0)}catch(t){let n=new $(t);o.error(Q,{command:Z,code:n.code,scope:e.scope,cause:n.cause}),process.exit(1)}}),te=new m(`stop`).description(`Stop the background HTTP server`).action(async()=>{try{let e=await new O().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)}}),ne=d(p(import.meta.url)),re=JSON.parse(l(f(ne,`../package.json`),`utf-8`));async function ie(){let e=new m;e.name(`model-proxy-mcp`).description(`Claude-compatible model proxy MCP`).version(re.version),e.addCommand(X),e.addCommand(te),e.addCommand(ee),e.addCommand(K),e.addCommand(J),e.addCommand(Y),await e.parseAsync(process.argv)}ie();export{};
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./stdio-BKQRhaEs.cjs`);exports.ConversationHistoryService=e.a,exports.GatewayService=e.i,exports.ProfileStore=e.o,exports.StdioTransportHandler=e.t,exports.createHttpServer=e.r,exports.createServer=e.n;
|