RegesCore-1.0-35 / lmstudio-grammar-fix-proxy.js
iBossonline's picture
Upload lmstudio-grammar-fix-proxy.js
582b0f5 verified
Raw History Blame Contribute Delete
5.63 kB
/*
* lmstudio-grammar-fix-proxy.js
* ------------------------------------------------------------------
* Transparent local proxy that lets Claude Code (full agent mode) talk
* to LM Studio's native Anthropic-compatible endpoint.
*
* THE PROBLEM IT FIXES
* Claude Code's `tools` array includes schemas whose size bounds blow
* up llama.cpp's GBNF grammar compiler when LM Studio compiles them
* to constrain tool-call output. Specifically:
* - Workflow.script: maxLength 524288 -> `char{0,524288}`
* - huge integer maximums on some fields
* GBNF caps repetitions at ~100000, so 524288 throws
* "number of repetitions exceeds sane defaults" / "failed to parse grammar"
* -> HTTP 400 on every tool turn -> the agent loop dies immediately.
*
* THE FIX
* Clamp every oversized bound in each tool's input_schema to a value
* the grammar compiler accepts, then forward unchanged to LM Studio.
* Responses stream straight back untouched.
*
* USAGE
* 1. Start LM Studio's server (port 2126) and load your model.
* 2. node lmstudio-grammar-fix-proxy.js
* 3. Point Claude Code desktop (Developer -> Configure Third-Party
* Inference) at http://localhost:2140 instead of LM Studio.
*
* Zero dependencies. Node 16+.
* ------------------------------------------------------------------ */
const http = require("http");
const UPSTREAM = { host: "127.0.0.1", port: 2126 }; // LM Studio
const PROXY_PORT = 2140; // what Claude Code hits
// Caps chosen to stay well under llama.cpp's GBNF repetition limit (~100000).
const MAX_STRING_LEN = 80000; // maxLength on string fields
const MAX_NUMBER = 1000000; // maximum on numeric fields
const MAX_ITEMS = 1000; // maxItems / maxProperties
function clamp(value, cap) {
return typeof value === "number" && value > cap ? cap : value;
}
// Recursively walk a JSON-schema-like object and shrink oversized bounds.
function sanitizeSchema(node) {
if (Array.isArray(node)) {
for (const item of node) sanitizeSchema(item);
return;
}
if (node && typeof node === "object") {
for (const [key, value] of Object.entries(node)) {
switch (key) {
case "maxLength":
case "minLength": // harmless to leave; only max matters for repetition
node[key] = clamp(value, MAX_STRING_LEN);
break;
case "maximum":
case "exclusiveMaximum":
node[key] = clamp(value, MAX_NUMBER);
break;
case "maxItems":
case "maxProperties":
node[key] = clamp(value, MAX_ITEMS);
break;
default:
if (value && typeof value === "object") sanitizeSchema(value);
}
}
}
}
// Rewrite a request body in place; returns the (possibly new) body string.
function sanitizeRequestBody(rawBody) {
try {
const payload = JSON.parse(rawBody);
// Anthropic-style: tools[].input_schema
if (Array.isArray(payload.tools)) {
for (const tool of payload.tools) {
if (tool && tool.input_schema) sanitizeSchema(tool.input_schema);
}
}
// OpenAI-style: tools[].function.parameters / functions[].parameters
const flattenOpenAITools = (tools) => {
if (Array.isArray(tools)) {
for (const t of tools) {
if (t && t.function && t.function.parameters) sanitizeSchema(t.function.parameters);
else if (t && t.parameters) sanitizeSchema(t.parameters);
}
}
};
flattenOpenAITools(payload.tools);
if (Array.isArray(payload.functions)) {
for (const f of payload.functions) {
if (f && f.parameters) sanitizeSchema(f.parameters);
}
}
return JSON.stringify(payload);
} catch {
return rawBody; // not JSON or unparseable -> forward untouched
}
}
const TOOL_BEARING = ["/v1/messages", "/v1/chat/completions"];
const server = http.createServer((clientReq, clientRes) => {
const chunks = [];
clientReq.on("data", (c) => chunks.push(c));
clientReq.on("end", () => {
let body = Buffer.concat(chunks);
const isToolBearing =
clientReq.method === "POST" && TOOL_BEARING.includes(clientReq.url.split("?")[0]);
if (isToolBearing && body.length) {
const sanitized = sanitizeRequestBody(body.toString("utf8"));
if (sanitized.length !== body.length || sanitized !== body.toString("utf8")) {
body = Buffer.from(sanitized, "utf8");
}
}
const headers = { ...clientReq.headers };
headers["content-length"] = Buffer.byteLength(body);
headers.host = `${UPSTREAM.host}:${UPSTREAM.port}`;
const upstreamReq = http.request(
{
host: UPSTREAM.host,
port: UPSTREAM.port,
method: clientReq.method,
path: clientReq.url,
headers,
},
(upstreamRes) => {
clientRes.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);
upstreamRes.pipe(clientRes); // stream SSE/text straight through, never buffer
}
);
upstreamReq.on("error", (err) => {
clientRes.writeHead(502, { "content-type": "application/json" });
clientRes.end(JSON.stringify({ error: { type: "proxy_error", message: err.message } }));
});
upstreamReq.end(body);
});
clientReq.on("error", () => {});
});
server.listen(PROXY_PORT, "127.0.0.1", () => {
console.log(`[grammar-fix-proxy] listening on http://127.0.0.1:${PROXY_PORT}`);
console.log(`[grammar-fix-proxy] forwarding to http://${UPSTREAM.host}:${UPSTREAM.port}`);
console.log(`[grammar-fix-proxy] clamping tools: maxLength<=${MAX_STRING_LEN}, maximum<=${MAX_NUMBER}`);
});