diff --git a/typescript/README.md b/typescript/README.md index 493e8763..4493de7c 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -79,6 +79,29 @@ To customize both kinds, implement `getLegacyPromptParts()` instead of replacing `createRequestPrompt`. Validation, repair, and model retry settings are independent of layout. See the [TypeScript usage and migration examples](https://microsoft.github.io/TypeChat/docs/typescript/basic-usage/). +### Numeric model output + +The translator rejects JSON numbers that overflow JavaScript's finite number range, +such as `1e400`, including inside nested objects and arrays. JavaScript parses these +as `Infinity` or `-Infinity`, which would otherwise serialize as `null` during +TypeScript validation. They follow the JSON parse-failure path: one repair attempt +by default, or an immediate failure when `translator.attemptRepair` is `false`. +This does not add arbitrary-precision arithmetic or change JavaScript's normal +rounding of finite numbers. + +After installing development dependencies, run the focused offline regressions +from `typescript/`: + +```sh +npm run build +node --test tests/numeric-output.test.mjs +``` + +These tests exercise the real TypeScript validator through both CommonJS and ESM +entry points, including repair exhaustion after a schema error and rejection +before null stripping or application instance validation. Responses are mocked; +this is a parser/repair regression suite, not a model-quality or token-cost benchmark. + ### Model temperature The HTTP factories and configured-client adapter accept `temperature` in their diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index e5c102db..f1bc281e 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -221,7 +221,12 @@ export function createJsonTranslator( } else { try { - jsonObject = JSON.parse(jsonText) as object; + jsonObject = JSON.parse(jsonText, (key, value: unknown) => { + if (typeof value === "number" && !Number.isFinite(value)) { + throw new SyntaxError(`JSON number at property ${JSON.stringify(key)} must be finite.`); + } + return value; + }) as object; parsed = true; } catch (e) { diff --git a/typescript/tests/numeric-output.test.mjs b/typescript/tests/numeric-output.test.mjs new file mode 100644 index 00000000..0f7f9d8d --- /dev/null +++ b/typescript/tests/numeric-output.test.mjs @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +for (const [format, entry, validatorEntry] of [ + ["CommonJS", "../dist/index.js", "../dist/ts/index.js"], + ["ESM", "../dist/esm/index.mjs", "../dist/esm/ts/index.mjs"] +]) { + const { createJsonTranslator } = await import(entry); + const { createTypeScriptJsonValidator } = await import(validatorEntry); + + describe(`numeric model output (${format})`, () => { + numericOutputTests(createJsonTranslator, createTypeScriptJsonValidator); + }); +} + +function numericOutputTests(createJsonTranslator, createTypeScriptJsonValidator) { + function translatorFor(t, responses) { + const validator = createTypeScriptJsonValidator( + "export interface Output { value: number | null; nested?: (number | null)[][]; text?: string; }", + "Output" + ); + t.after(() => validator.close()); + const prompts = []; + const model = { + async complete(prompt) { + prompts.push(structuredClone(prompt)); + assert.ok(responses.length, "Unexpected model call"); + return { success: true, data: responses.shift() }; + } + }; + return { translator: createJsonTranslator(model, validator), prompts }; + } + + for (const responseText of [ + '{"value":1e400}', + '{"value":-1e400}', + '{"value":null,"nested":[[0,1e400]]}' + ]) { + it(`rejects overflowing JSON numbers without repair: ${responseText}`, async t => { + const { translator, prompts } = translatorFor(t, [responseText]); + translator.attemptRepair = false; + const result = await translator.translate("Return a number"); + assert.equal(result.success, false); + assert.match(result.message, /JSON number.*finite/); + assert.equal(result.responseText, responseText); + assert.equal(prompts.length, 1); + }); + } + + it("repairs an overflowing number using the original response and a finite-number diagnostic", async t => { + const responseText = '{"value":1e400}'; + const { translator, prompts } = translatorFor(t, [responseText, '{"value":42}']); + assert.deepEqual(await translator.translate("Return a number"), { + success: true, data: { value: 42 } + }); + assert.equal(prompts.length, 2); + assert.deepEqual(prompts[1].at(-2), { role: "assistant", content: responseText }); + assert.equal(prompts[1].at(-1).role, "user"); + assert.match(prompts[1].at(-1).content, /JSON number.*finite/); + }); + + for (const [failure, responseText, repairText] of [ + ["overflow", '{"value":1e400}', '{"value":-1e400}'], + ["a schema error", '{"value":"invalid"}', '{"value":1e400}'] + ]) { + it(`does not grant another repair when overflow follows ${failure}`, async t => { + const { translator, prompts } = translatorFor(t, [responseText, repairText]); + const result = await translator.translate("Return a number"); + assert.equal(result.success, false); + assert.match(result.message, /JSON number.*finite/); + assert.equal(result.responseText, repairText); + assert.equal(prompts.length, 2); + }); + } + + it("rejects overflow before null stripping or instance validation", async t => { + const { translator, prompts } = translatorFor(t, ['{"value":null,"nested":[[null,-1e400]]}']); + translator.attemptRepair = false; + translator.stripNulls = true; + translator.validateInstance = () => assert.fail("Overflow must fail before instance validation"); + const result = await translator.translate("Return a number"); + assert.equal(result.success, false); + assert.match(result.message, /JSON number.*finite/); + assert.equal(prompts.length, 1); + }); + + it("preserves finite numbers, nulls, and strings that look like overflowing numbers", async t => { + const { translator, prompts } = translatorFor(t, [ + '{"value":1.7976931348623157e308,"nested":[[-1.7976931348623157e308,null,0]],"text":"1e400"}' + ]); + assert.deepEqual(await translator.translate("Return a number"), { + success: true, + data: { value: Number.MAX_VALUE, nested: [[-Number.MAX_VALUE, null, 0]], text: "1e400" } + }); + assert.equal(prompts.length, 1); + }); +}