Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(laya-ts): validate hooksTimeout against the shared hooks.json contract
Aashishae0ceff7b147
diff --git a/laya-ts/src/agent.ts b/laya-ts/src/agent.tsindex e6d96659..4b439b1f 100644--- a/laya-ts/src/agent.ts+++ b/laya-ts/src/agent.ts@@ -32,6 +32,7 @@ import {defaultsAlreadyRan,dispatchAsync,normaliseHooks,+ validateHooksTimeout,type HookArg,type PredictHook,} from "./hooks.js";@@ -451,7 +452,7 @@ export class Agent extends HookRegistry {// Hooks are opt-in; an unset hook list is a no-op. See hooks.ts.this.hooks = normaliseHooks(opts.hooks, opts.onPredictStart, opts.onPredictEnd);this.hooksRaise = opts.hooksRaise ?? true;- this.hooksTimeout = opts.hooksTimeout ?? null;+ this.hooksTimeout = validateHooksTimeout(opts.hooksTimeout ?? null);const cfg = { ...(opts.cfg ?? {}) } as AgentCfg;if (opts.max_len !== undefined) cfg.max_len = opts.max_len;if (opts.head_max_len !== undefined) cfg.head_max_len = opts.head_max_len;@@ -560,8 +561,8 @@ export class Agent extends HookRegistry {? [...this.hooks, ...normaliseHooks(opts.hooks, opts.onPredictStart, opts.onPredictEnd)]: composeHooks(this.hooks, opts.hooks, opts.onPredictStart, opts.onPredictEnd);const raiseErrors = opts.hooksRaise ?? this.hooksRaise;- const hooksTimeout = opts.hooksTimeout ?? this.hooksTimeout;- const timeoutMs = typeof hooksTimeout === "number" ? hooksTimeout * 1000 : null;+ const hooksTimeout = validateHooksTimeout(opts.hooksTimeout ?? this.hooksTimeout);+ const timeoutMs = hooksTimeout === null ? null : hooksTimeout * 1000;const ctx = new PredictContext({states,questions: questions as Record<string, unknown>,diff --git a/laya-ts/src/common.ts b/laya-ts/src/common.tsindex d99553ea..b262f088 100644--- a/laya-ts/src/common.ts+++ b/laya-ts/src/common.ts@@ -244,7 +244,13 @@ export function answerConfidence(p: number[]): number {return Math.min(1, Math.max(0, Math.max(...p)));}-function pyRepr(v: unknown): string {+/**+ * The value as CPython's `repr` renders it, for a refusal that has to name what was passed.+ *+ * Exported because `hooks.ts` needs it for the `hooks_timeout` refusals, whose messages are+ * compared against `laya/hooks.py::validate_timeout` character for character.+ */+export function pyRepr(v: unknown): string {if (typeof v === "boolean") return v ? "True" : "False";if (v === null || v === undefined) return "None";if (typeof v === "number") {@@ -253,7 +259,7 @@ function pyRepr(v: unknown): string {if (v === -Infinity) return "-inf";return String(v);}- if (typeof v === "string") return JSON.stringify(v);+ if (typeof v === "string") return pyStrRepr(v);if (Array.isArray(v)) return `[${v.map(pyRepr).join(", ")}]`;if (typeof v === "object") {const entries = Object.entries(v as Record<string, unknown>).map(@@ -264,6 +270,27 @@ function pyRepr(v: unknown): string {return String(v);}+/**+ * CPython's `repr` of a str: `'quoted'`, unless the text holds a `'` and no `"`, where it flips to+ * double quotes to avoid escaping. `JSON.stringify` always double-quotes, so a container rendered+ * through it -- `['a']`, `{'a': 1}` -- shows the wrong quotes for its strings, and a refusal+ * naming the value stops being comparable to the oracle's. See `laya-java/fixtures/+ * confidence_gate.json`, which records the reference's `got '0.5'` for a string value.+ */+function pyStrRepr(s: string): string {+ const quote = s.includes("'") && !s.includes('"') ? '"' : "'";+ let out = "";+ for (const ch of s) {+ if (ch === quote || ch === "\\") out += `\\${ch}`;+ else if (ch === "\n") out += "\\n";+ else if (ch === "\r") out += "\\r";+ else if (ch === "\t") out += "\\t";+ else if (ch < " " || ch === "\x7f") out += `\\x${ch.charCodeAt(0).toString(16).padStart(2, "0")}`;+ else out += ch;+ }+ return `${quote}${out}${quote}`;+}+/** The option types and option-count sizes `optionBucket`/`tempBucket` can produce. The bucket* type and the runtime `BUCKET_KEY` check below are both derived from these, so what the type* accepts cannot drift from the keys the runtime produces. */diff --git a/laya-ts/src/hooks.ts b/laya-ts/src/hooks.tsindex 58e55fe5..ff9e109a 100644--- a/laya-ts/src/hooks.ts+++ b/laya-ts/src/hooks.ts@@ -6,6 +6,8 @@* overridden per call. Port of `laya/hooks.py`.*/+import { pyRepr } from "./common.js";+/** Mutable state passed to every hook for one call. */export class PredictContext {/** `states` / `questions` may be rewritten by `onPredictStart`. */@@ -338,6 +340,81 @@ function isThenable(value: unknown): value is PromiseLike<unknown> {return typeof (value as PromiseLike<unknown> | null | undefined)?.then === "function";}+/**+ * Python's `float()` read of a string, or null for a string `float()` rejects.+ *+ * `Number()` is looser in both directions: it reads `"inf"` as NaN where `float()` reads infinity,+ * and it reads `"0x10"` as 16 where `float()` raises. Decimal, exponent and the `inf`/`nan`+ * spellings are what a JSON body can hold; a `_`-grouped digit like `"1_000"`, which CPython does+ * read, is refused here as unconvertible rather than passed through `Number()`, which gives NaN.+ */+function floatFromText(text: string): number | null {+ const body = text.trim().toLowerCase();+ if (body === "nan" || body === "+nan" || body === "-nan") return NaN;+ if (/^[+-]?(inf|infinity)$/.test(body)) return body.startsWith("-") ? -Infinity : Infinity;+ if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(body)) return null;+ return Number(body);+}++/**+ * The `hooksTimeout` of one call, in seconds: a positive finite number, or null for "no limit".+ * Port of `laya/hooks.py::validate_timeout` (hooks.py:251-285), whose refusals+ * `laya-java/fixtures/hooks.json` records under `timeouts`.+ *+ * The port had no gate at all -- `typeof value === "number" ? value * 1000 : null` -- so it+ * installed deadlines the reference refuses to install, and skipped the deadline for everything+ * not already a number. Measured on the built port with a hook whose `onPredictStart` never+ * settles, against the same table CPython's `validate_timeout` answers:+ *+ * hooksTimeout the reference laya-ts (before)+ * 0 ValueError, `got 0` TimeoutError at 1 ms; the hook never ran+ * -1 ValueError, `got -1` TimeoutError at 2 ms+ * NaN ValueError, `got nan` TimeoutError at 2 ms+ * Infinity ValueError, `got inf` TimeoutError at 1 ms+ * true ValueError, `not a bool; got True` no deadline, the hook runs unbounded+ * [1] ValueError, `got [1]` no deadline+ * {"a": 1} ValueError, `got {'a': 1}` no deadline+ * "0.5" a 0.5 s deadline no deadline+ *+ * `setTimeout(0)` fires on the next tick and `setTimeout(-1000)` fires after 1 ms (Node warns+ * `TimeoutNegativeWarning` and clamps), so a zero or negative timeout is not a missing deadline+ * but an instant one: every hook call fails with a `TimeoutError` naming a deadline of `0s` that+ * no caller asked for, and with `hooksRaise: false` the prediction still completes and reports the+ * fake timeout as a warning. That is exactly the race Python's docstring refuses to leave to+ * `thread.join`. The non-number rows are the quieter half: a `hooksTimeout` read from a config+ * body as a string or a nested object silently became "no limit".+ */+export function validateHooksTimeout(value: unknown): number | null {+ if (value === null || value === undefined) return null;+ if (typeof value === "boolean") {+ // `float(True)` is 1.0, so a bool would otherwise install a one-second deadline on every+ // hook call. Refused as a wrong type, not as a non-positive number.+ throw new Error(+ `hooks_timeout must be a positive finite number or None, not a bool; got ${pyRepr(value)}`,+ );+ }+ let seconds: number | null;+ if (typeof value === "number") seconds = value;+ else if (typeof value === "bigint") seconds = Number(value);+ else if (typeof value === "string") {+ const read = floatFromText(value);+ if (read === null) {+ // The message `float()` itself raises; the reference lets it escape from the coercion.+ throw new Error(`could not convert string to float: ${pyRepr(value)}`);+ }+ seconds = read;+ } else seconds = null;+ if (seconds === null) {+ // A list, an object, a function: `float()` raises TypeError, which the reference catches and+ // re-raises as the same ValueError every other bad timeout gets.+ throw new Error(`hooks_timeout must be a positive finite number or None; got ${pyRepr(value)}`);+ }+ if (!Number.isFinite(seconds) || seconds <= 0) {+ throw new Error(`hooks_timeout must be a positive finite number or None; got ${pyRepr(value)}`);+ }+ return seconds;+}+function trimTrailingZeros(decimal: string): string {const dot = decimal.indexOf(".");if (dot < 0) return decimal;diff --git a/laya-ts/tests/hooks.test.ts b/laya-ts/tests/hooks.test.tsindex 75eb5d7a..3335ba44 100644--- a/laya-ts/tests/hooks.test.ts+++ b/laya-ts/tests/hooks.test.ts@@ -1,3 +1,4 @@+import { readFileSync } from "node:fs";import { describe, expect, it, vi } from "vitest";import { Agent, defaultTokenizer } from "../src/agent.js";import { Router } from "../src/router.js";@@ -9,6 +10,7 @@ import {defaultHooks,normaliseHooks,setDefaultHooks,+ validateHooksTimeout,type Hook,type PredictContext,} from "../src/hooks.js";@@ -651,4 +653,153 @@ describe("hook timeout", () => {vi.useRealTimers();}});++ // `laya-java/fixtures/hooks.json` records `laya/hooks.py::validate_timeout` answering every+ // value in `HOOK_TIMEOUT_VALUES` (`gen_fixtures.py:4719`, recorded at :5009-5024): the accepted+ // seconds or the `ValueError` text. `laya-java` replays those rows in `HooksTest.timeoutsMatch()`;+ // until now the TypeScript port had no test that consulted the file, and no gate either --+ // `typeof value === "number" ? value * 1000 : null` installed the deadline for a number and+ // treated everything else as "no limit", so the reference's refusals arrived here as either an+ // instant `TimeoutError` (0, -1, NaN, Infinity) or a missing deadline (a bool, a string, a list).+ //+ // `input` is the Python `repr` of the value, and is the key this test maps on purpose: a value+ // added to the reference's list must land here deliberately rather than fall through untested.+ const TIMEOUT_ROWS = JSON.parse(+ readFileSync(new URL("../../laya-java/fixtures/hooks.json", import.meta.url), "utf8"),+ ).timeouts as {+ input: string;+ accepted: boolean;+ value: number | null;+ seconds: string | null;+ error: string | null;+ }[];++ const TIMEOUT_INPUTS: Record<string, unknown> = {+ None: null,+ "1": 1,+ "2": 2,+ "10": 10,+ "60": 60,+ "1.5": 1.5,+ "0.05": 0.05,+ "1e-07": 1e-7,+ "'0.5'": "0.5",+ "0": 0,+ "0.0": 0,+ "-1": -1,+ "-0.5": -0.5,+ nan: NaN,+ inf: Infinity,+ "-inf": -Infinity,+ };++ /** JavaScript has one number where the reference recorded a Python `int` and a Python `float`.+ * Both rows still assert the refusal; only the `repr` in its text cannot be reproduced. */+ const REPR_AMBIGUOUS = new Set(["0", "0.0"]);++ /** The message a call refuses with, or a test failure if it did not refuse. `toThrowError` with+ * a string matches a substring, and the whole point of these rows is the exact text. */+ function refusalOf(build: () => unknown): string {+ try {+ build();+ } catch (err) {+ return (err as Error).message;+ }+ throw new Error("expected a refusal");+ }++ for (const row of TIMEOUT_ROWS) {+ if (!(row.input in TIMEOUT_INPUTS)) {+ it(`${row.input} (UNRECORDED)`, () => {+ throw new Error(+ `hooks.json records the timeout value ${row.input}, which this test maps to no JavaScript ` ++ "value. Add it to TIMEOUT_INPUTS -- leaving it out stops the port being tested for it.",+ );+ });+ continue;+ }+ const value = TIMEOUT_INPUTS[row.input];+ if (row.accepted) {+ it(`${row.input} is accepted as ${row.value}`, () => {+ expect(validateHooksTimeout(value)).toBe(row.value);+ });+ continue;+ }+ it(`${row.input} is refused`, () => {+ expect(refusalOf(() => validateHooksTimeout(value))).toBe(+ REPR_AMBIGUOUS.has(row.input) ? row.error!.replace(/got .*$/, "got 0") : row.error!,+ );+ });+ }++ // Shapes the reference's list does not carry, measured from `validate_timeout` directly.+ it("refuses the shapes a JSON body can hold, naming them as the reference does", () => {+ const PREFIX = "hooks_timeout must be a positive finite number or None";+ expect(refusalOf(() => validateHooksTimeout(true))).toBe(`${PREFIX}, not a bool; got True`);+ expect(refusalOf(() => validateHooksTimeout(false))).toBe(`${PREFIX}, not a bool; got False`);+ expect(refusalOf(() => validateHooksTimeout([1]))).toBe(`${PREFIX}; got [1]`);+ expect(refusalOf(() => validateHooksTimeout({ a: 1 }))).toBe(`${PREFIX}; got {'a': 1}`);+ // A string `float()` cannot read leaks its own message, which the reference does not wrap.+ expect(refusalOf(() => validateHooksTimeout(" "))).toBe("could not convert string to float: ' '");+ expect(refusalOf(() => validateHooksTimeout("abc"))).toBe(+ "could not convert string to float: 'abc'",+ );+ // A spelling `float()` does read is then refused for what it reads, and names the string.+ expect(refusalOf(() => validateHooksTimeout("inf"))).toBe(`${PREFIX}; got 'inf'`);+ expect(refusalOf(() => validateHooksTimeout("0"))).toBe(`${PREFIX}; got '0'`);+ expect(validateHooksTimeout("1e-7")).toBe(1e-7);+ });++ it("refuses a bad timeout when the agent is built, not at the first hook", () => {+ expect(refusalOf(() => makeAgent([], { hooksTimeout: 0 }))).toBe(+ "hooks_timeout must be a positive finite number or None; got 0",+ );+ expect(refusalOf(() => makeAgent([], { hooksTimeout: true }))).toBe(+ "hooks_timeout must be a positive finite number or None, not a bool; got True",+ );+ });++ it("refuses a bad per-call override instead of firing an instant deadline", async () => {+ class NeverHook {+ async onPredictStart(): Promise<void> {+ return new Promise(() => {});+ }+ }+ vi.useFakeTimers();+ try {+ const settled = capture(+ makeAgent([], { hooks: [new NeverHook()] }).systemOne("hi", QUESTIONS, { hooksTimeout: 0 }),+ );+ await vi.advanceTimersByTimeAsync(50);+ const err = await settled;+ expect((err as Error).message).toBe(+ "hooks_timeout must be a positive finite number or None; got 0",+ );+ } finally {+ vi.useRealTimers();+ }+ });++ it("reads a string timeout the reference reads and sets that deadline", async () => {+ vi.useFakeTimers();+ try {+ const settled = capture(+ makeAgent([], { hooks: [new SlowHook()], hooksTimeout: "0.5" }).systemOne("hi", QUESTIONS),+ );+ let done = false;+ settled.then(() => {+ done = true;+ });+ await vi.advanceTimersByTimeAsync(400);+ // Half a second has not passed, and before this gate a string timeout never armed a timer+ // at all, so nothing would have fired at any point.+ expect(done).toBe(false);+ await vi.advanceTimersByTimeAsync(100);+ const err = await settled;+ expect((err as Error).name).toBe("TimeoutError");+ expect((err as Error).message).toBe("laya: hook SlowHook.onPredictStart exceeded 0.5s");+ } finally {+ vi.useRealTimers();+ }+ });});