Skip to content

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

fix: retain connector numeric text before precision is lost

Afloat683d1fe6c6fd
diff --git a/server/connector-arguments.test.ts b/server/connector-arguments.test.ts
index bd45cdfb7b..39ba36ee96 100644
--- a/server/connector-arguments.test.ts
+++ b/server/connector-arguments.test.ts
@@ -106,3 +106,108 @@ describe("what a bot is told", () => {
expect(ARGUMENT_REFUSAL.test("The calendar has no events that day.")).toBe(false);
});
});
+
+describe("numeric text preservation", () => {
+ it.each(["number", "integer"])("keeps nonzero decimal text that underflows for %s", (type) => {
+ const schema = { type: "object", properties: { value: { type } } };
+ const tiny = "0." + "0".repeat(323) + "1";
+ for (const value of [tiny, "-" + tiny]) {
+ const args = { value };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ expect(fitArguments(args, schema).args).toBe(args);
+ }
+ });
+
+ it("keeps fractional text that rounds to an integer", () => {
+ const schema = { type: "object", properties: { value: { type: "integer" } } };
+ for (const value of ["1.0000000000000001", "-1.0000000000000001", "9007199254740991.1"]) {
+ const args = { value };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ }
+ });
+
+ it("keeps decimal text whose significant digits would be rounded", () => {
+ const schema = { type: "object", properties: { value: { type: "number" } } };
+ for (const value of ["0.10000000000000001", "1.234567890123456789", "-1.234567890123456789"]) {
+ const args = { value };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ }
+ });
+
+ it.each([
+ "9007199254740993", "-9007199254740993", "1e400", "-1e400",
+ "1e-400", "-1e-400", "1.0000000000000001", "9007199254740993e-1",
+ ])("keeps root JSON text containing the unsafe numeric token %s", (token) => {
+ const args = '{"value":' + token + "}";
+ const schema = { type: "object", properties: { value: { type: "number" } } };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ });
+
+ it.each([
+ { type: "object", properties: { value: { type: "number" } } },
+ { type: "object" },
+ ])("keeps unsafe nested object text for schema %j", (objectSchema) => {
+ const args = { payload: '{"value":9007199254740993}' };
+ const schema = { type: "object", properties: { payload: objectSchema } };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ });
+
+ it.each([
+ { name: "numeric items", items: { type: "number" }, value: "[9007199254740993]" },
+ { name: "string items", items: { type: "string" }, value: "[9007199254740993]" },
+ { name: "one-field objects", items: { type: "object", properties: { use_case: { type: "string" } }, required: ["use_case"] }, value: '[{"use_case":"x","limit":9007199254740993}]' },
+ ])("keeps unsafe array text without a fallback wrapper for $name", ({ items, value }) => {
+ const args = { values: value };
+ const schema = { type: "object", properties: { values: { type: "array", items } } };
+ expect(fitArguments(args, schema)).toEqual({ args, changed: [] });
+ expect(fitArguments(args, schema).args).toBe(args);
+ });
+
+ it("keeps unsafe nested text when a separate safe field is fitted", () => {
+ const payload = '{"limit":1e400}';
+ const schema = { type: "object", properties: { payload: { type: "object" }, timeout: { type: "number" } } };
+ expect(fitArguments({ payload, timeout: "42" }, schema)).toEqual({
+ args: { payload, timeout: 42 },
+ changed: ["timeout as a number"],
+ });
+ });
+
+ it("still fits exact numeric text including zero-only fractional digits", () => {
+ for (const type of ["number", "integer"]) {
+ const schema = { type: "object", properties: { value: { type } } };
+ for (const value of [" 42 ", "-12", "42.000", "00042.000", "-0.000", "9007199254740991"]) {
+ expect(fitArguments({ value }, schema)).toEqual({ args: { value: Number(value) }, changed: ["value as a number"] });
+ }
+ }
+ });
+
+ it("still parses equivalent decimal and exponent JSON spellings", () => {
+ const schema = { type: "object", properties: { value: { type: "number" } } };
+ for (const token of ["0.1", "1.50", "4.2e1", "1e-7", "0e400", "-0.000e-400", "9007199254740991.0"]) {
+ const args = '{"value":' + token + "}";
+ expect(fitArguments(args, schema)).toEqual({
+ args: { value: Number(token) },
+ changed: ["the arguments from text to an object"],
+ });
+ }
+ });
+
+ it("does not interpret numeric-looking quoted strings as numeric tokens", () => {
+ const value = '9007199254740993 and 1e400, with "quoted" text';
+ const schema = { type: "object", properties: { value: { type: "string" }, enabled: { type: "boolean" }, extra: {} } };
+ const args = { value, enabled: false, extra: null };
+ expect(fitArguments(JSON.stringify(args), schema)).toEqual({
+ args,
+ changed: ["the arguments from text to an object"],
+ });
+ });
+
+ it("keeps ordinary text fallback and malformed JSON behavior", () => {
+ expect(fitArguments({ queries: "read my calendar" }, SEARCH)).toEqual({
+ args: { queries: [{ use_case: "read my calendar" }] },
+ changed: ['queries as [{"use_case": …}]'],
+ });
+ const args = '{"value": 12,}';
+ expect(fitArguments(args, { type: "object", properties: { value: { type: "number" } } })).toEqual({ args, changed: [] });
+ });
+});
diff --git a/server/connector-arguments.ts b/server/connector-arguments.ts
index 6718ec0b58..d1b0e615b5 100644
--- a/server/connector-arguments.ts
+++ b/server/connector-arguments.ts
@@ -37,9 +37,34 @@ function soleStringField(node: Json | null, root: Json): string | null {
return typeOf(resolved(node!.properties[keys[0]!], root)) === "string" ? keys[0]! : null;
}
+function decimalValue(text: string): string | null {
+ const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text);
+ if (!match) return null;
+ const fraction = match[3] ?? "";
+ const coefficient = (match[2] + fraction).replace(/^0+/, "");
+ if (!coefficient) return "0";
+ const digits = coefficient.replace(/0+$/, "");
+ const exponent = Number(match[4] ?? "0") - fraction.length + coefficient.length - digits.length;
+ if (!Number.isSafeInteger(exponent)) return null;
+ return `${match[1]}${digits}e${exponent}`;
+}
+
+function preservesNumericText(text: string, value: number): boolean {
+ if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) return false;
+ const original = decimalValue(text);
+ return original !== null && original === decimalValue(String(value));
+}
+
+const UNSAFE_JSON_NUMBER = Symbol("unsafe-json-number");
+
function parsedJson(text: string): unknown {
try {
- return JSON.parse(text);
+ let unsafe = false;
+ const parsed = JSON.parse(text, (_key: string, value: unknown, context?: { source?: string }) => {
+ if (typeof value === "number" && (context?.source === undefined || !preservesNumericText(context.source, value))) unsafe = true;
+ return value;
+ });
+ return unsafe ? UNSAFE_JSON_NUMBER : parsed;
} catch {
return undefined;
}
@@ -53,6 +78,7 @@ function coerce(value: unknown, node: Json | null, root: Json, path: string, cha
const field = soleStringField(items, root);
if (typeof value === "string") {
const parsed = parsedJson(value);
+ if (parsed === UNSAFE_JSON_NUMBER) return value;
if (Array.isArray(parsed)) {
changed.push(`${path} from text to a list`);
return parsed.map((item, index) => coerce(item, items, root, `${path}[${index}]`, []));
@@ -80,6 +106,7 @@ function coerce(value: unknown, node: Json | null, root: Json, path: string, cha
}
if (type === "object") {
const parsed = typeof value === "string" ? parsedJson(value) : undefined;
+ if (parsed === UNSAFE_JSON_NUMBER) return value;
if (isObject(parsed)) changed.push(`${path} from text to an object`);
const object = isObject(parsed) ? parsed : value;
if (!isObject(object) || !isObject(node!.properties)) return object;
@@ -89,8 +116,7 @@ function coerce(value: unknown, node: Json | null, root: Json, path: string, cha
}
if ((type === "number" || type === "integer") && typeof value === "string" && /^-?\d+(?:\.\d+)?$/.test(value.trim())) {
const number = Number(value.trim());
- if (!Number.isFinite(number) || (Number.isInteger(number) && !Number.isSafeInteger(number)) ||
- (type === "integer" && !Number.isInteger(number))) return value;
+ if (!preservesNumericText(value.trim(), number) || (type === "integer" && !Number.isInteger(number))) return value;
changed.push(`${path} as a number`);
return number;
}
@@ -127,6 +153,7 @@ export function fitArguments(args: unknown, schema: unknown): { args: unknown; c
if (!root || typeOf(root) !== "object" || !isObject(root.properties)) return { args, changed: [] };
const changed: string[] = [];
const parsed = typeof args === "string" ? parsedJson(args) : args;
+ if (parsed === UNSAFE_JSON_NUMBER) return { args, changed: [] };
if (typeof args === "string" && isObject(parsed)) changed.push("the arguments from text to an object");
if (!isObject(parsed)) return { args, changed: [] };
const properties = root.properties;
diff --git a/server/connector-proxy.test.ts b/server/connector-proxy.test.ts
index e77fa40a56..5d0ff5e0f8 100644
--- a/server/connector-proxy.test.ts
+++ b/server/connector-proxy.test.ts
@@ -590,4 +590,47 @@ describe("connected-app tools by name", () => {
expect(refused.result.content[1].text).toContain('Call it again with the arguments its schema names, for example {"code_to_execute":"…"} with your own values.');
expect(refused.result.content[1].text).toContain("it says nothing about which apps or tools exist, so do not tell the person a tool is missing. Connected apps you can use: gemini, gmail.");
});
+
+ it("preserves unsafe numeric text on the upstream wire and still fits safe numeric arguments", async () => {
+ const calls: Array<{ params?: { arguments?: unknown } }> = [];
+ const upstream = await listen((request, response) => {
+ let body = "";
+ request.on("data", (chunk) => { body += chunk; });
+ request.on("end", () => {
+ const rpc = JSON.parse(body);
+ calls.push(rpc);
+ response.writeHead(200, { "content-type": "application/json" });
+ if (rpc.method === "tools/list") {
+ response.end(JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result: { tools: [
+ { name: "FIXTURE_NUMBER", inputSchema: { type: "object", properties: { value: { type: "number" }, payload: { type: "object" }, numbers: { type: "array", items: { type: "number" } } } } },
+ { name: "FIXTURE_INTEGER", inputSchema: { type: "object", properties: { value: { type: "integer" } } } },
+ ] } }));
+ return;
+ }
+ response.end(JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result: { content: [{ type: "text", text: "fixture reply" }] } }));
+ });
+ });
+ const lines = start({ OMB_CONNECTOR_UPSTREAM_URL: upstream });
+ const listReply = nextJson(lines);
+ child!.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }) + "\n");
+ await listReply;
+
+ const tiny = "0." + "0".repeat(323) + "1";
+ const cases: Array<{ name: string; args: unknown; expected: unknown }> = [
+ { name: "FIXTURE_NUMBER", args: { value: tiny }, expected: { value: tiny } },
+ { name: "FIXTURE_INTEGER", args: { value: "1.0000000000000001" }, expected: { value: "1.0000000000000001" } },
+ { name: "FIXTURE_NUMBER", args: '{"value":9007199254740993}', expected: '{"value":9007199254740993}' },
+ { name: "FIXTURE_NUMBER", args: { payload: '{"value":1e400}' }, expected: { payload: '{"value":1e400}' } },
+ { name: "FIXTURE_NUMBER", args: { numbers: "[9007199254740993]" }, expected: { numbers: "[9007199254740993]" } },
+ { name: "FIXTURE_NUMBER", args: '{"value":4.2e1}', expected: { value: 42 } },
+ { name: "FIXTURE_INTEGER", args: { value: "42.0" }, expected: { value: 42 } },
+ ];
+ for (const [index, sample] of cases.entries()) {
+ const reply = nextJson(lines);
+ child!.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: index + 2, method: "tools/call", params: { name: sample.name, arguments: sample.args } }) + "\n");
+ expect((await reply).id).toBe(index + 2);
+ expect(calls.at(-1)?.params?.arguments).toEqual(sample.expected);
+ }
+ });
+
});