Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: count UTF-8 bytes in the held result budget

Afloat8fe3d015936b
diff --git a/server/mcp-gate.ts b/server/mcp-gate.ts
index 8fd667ff37..7e8bd872e8 100644
--- a/server/mcp-gate.ts
+++ b/server/mcp-gate.ts
@@ -126,7 +126,7 @@ function hold(tool: string, text: string): HeldResult | undefined {
return undefined;
}
if (value === null || typeof value !== "object") return undefined;
- const handle = store.put(tool, value, text.length);
+ const handle = store.put(tool, value, Buffer.byteLength(text, "utf8"));
return { handle, shape: describeShape(value), example: exampleQuery(value) };
}
diff --git a/server/mcp-result-store-bytes.test.ts b/server/mcp-result-store-bytes.test.ts
new file mode 100644
index 0000000000..13ecdec378
--- /dev/null
+++ b/server/mcp-result-store-bytes.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+
+import { ResultStore } from "./mcp-shape.ts";
+
+describe("held result byte accounting", () => {
+ it.each(["界", "é", "😀"])("counts UTF-8 bytes for %s when deciding which result to evict", (character) => {
+ const value = { text: character.repeat(100) };
+ const bytes = Buffer.byteLength(JSON.stringify(value), "utf8");
+ const store = new ResultStore({ maxBytes: bytes * 2 - 1 });
+ const first = store.put("search", value);
+ const second = store.put("search", value);
+ expect(store.get(first)).toBeUndefined();
+ expect(store.get(second)).toEqual({ tool: "search", value });
+ });
+
+ it("keeps results exactly at the byte budget", () => {
+ const value = { text: "界".repeat(100) };
+ const bytes = Buffer.byteLength(JSON.stringify(value), "utf8");
+ const store = new ResultStore({ maxBytes: bytes * 2 });
+ const first = store.put("search", value);
+ const second = store.put("search", value);
+ expect(store.get(first)).toBeDefined();
+ expect(store.get(second)).toBeDefined();
+ });
+
+ it("uses the caller's serialized byte size, including whitespace", () => {
+ const value = { text: "界" };
+ const bytes = Buffer.byteLength(JSON.stringify(value, null, 2), "utf8");
+ const store = new ResultStore({ maxBytes: bytes * 2 - 1 });
+ const first = store.put("search", value, bytes);
+ const second = store.put("search", value, bytes);
+ expect(store.get(first)).toBeUndefined();
+ expect(store.get(second)).toBeDefined();
+ });
+});
diff --git a/server/mcp-shape.ts b/server/mcp-shape.ts
index 07a0f239b0..5b7c027392 100644
--- a/server/mcp-shape.ts
+++ b/server/mcp-shape.ts
@@ -103,7 +103,7 @@ export class ResultStore {
put(tool: string, value: unknown, bytes?: number): string {
const handle = `r${this.#next++}`;
- const size = bytes ?? (JSON.stringify(value)?.length ?? 0);
+ const size = bytes ?? Buffer.byteLength(JSON.stringify(value) ?? "", "utf8");
this.#entries.set(handle, { tool, value, bytes: size });
this.#bytes += size;
for (const [oldest, held] of this.#entries) {