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
feat(client): Update typescript sdk to laya-client and other fixes
BaniNaveen4fa7a42541e4
diff --git a/README.md b/README.mdindex 31700bf8..0008e787 100644--- a/README.md+++ b/README.md@@ -226,9 +226,10 @@ pins the device. See `python examples/server.py --help` for the rest.### JavaScript / TypeScript-The [TypeScript SDK](sdk/typescript/README.md) supports JavaScript and TypeScript-apps through the existing Jev-compatible `/v1/systemone` HTTP server. It includes inferred-answer types, all five question presets, ESM/CommonJS exports, and cancellation.+[`laya-client`](sdk/typescript/README.md) supports JavaScript and TypeScript+applications over HTTP to a self-hosted `laya-serve` `/v1/systemone` server. It+includes inferred answer types, all five question presets, ESM/CommonJS exports,+and cancellation.```bash# From this checkout, install and start the Python inference service:@@ -242,9 +243,10 @@ npm run buildnode examples/triage.mjs```-The npm package is named `@laya/typescript-sdk`.-The prediction API also accepts Jev's response format; see the SDK's-[Jev compatibility guide](sdk/typescript/README.md#jev-compatibility-and-model-selection).+The npm package is named `laya-client`. Use it when a JavaScript or TypeScript+application talks over HTTP to self-hosted Python `laya-serve`. Use `laya-ts`+when inference must run directly inside JavaScript through its local ONNX+runtime, without a Python server.See [installation, examples, and publishing](sdk/typescript/README.md) and the[repository analysis](docs/typescript-sdk.md) for architecture and scope.@@ -443,14 +445,11 @@ The hint only decides *English or not*: a code whose primary subtag is `en`, `en----## Self-Hosting: HTTP Server (Jev-compatible)+## Self-Hosting: HTTP Server-`laya.serve` exposes the `Router` over HTTP on the same `POST /v1/systemone`-wire protocol as TypeSafe's hosted Jev API. Laya's answer payload is already-schema-identical to what Jev returns (`choice`/`score`/`noul` answers and a-`{input_tokens, output_tokens}` usage block), so an existing Jev client — e.g.-the [`hs-jev`](https://github.com/getmissionctrl/hs-jev) Haskell client — just-needs its `baseUrl` repointed; nothing else changes.+`laya-serve` exposes the `Router` over its local `POST /v1/systemone` HTTP+endpoint. Responses contain `choice`/`score`/`noul` answers and an+`{input_tokens, output_tokens}` usage block.```bashpip install "laya[serve]" # adds fastapi + uvicorn + python-multipart@@ -473,11 +472,11 @@ send `Authorization: Bearer <key>`). A client's `model` field is honoured when inames a Laya checkpoint (`english`/`multilingual`/`typed-decisions`), otherwisethe router auto-selects by script/language.-Three things differ from Jev when you port a client:+For HTTP clients:-* **Options per question.** A question's options share the checkpoint's option budget, `head_max_len` (192 tokens on `laya`, 256 on the other two), not Jev's cap of 255 options. Once they overflow it, around 20 options with a short description each, every option is trimmed to fit, so long or similar labels can reach the model reading the same ([Where Jev leads](#where-jev-leads)). Once they no longer fit the window at all, the request is rejected with 422. With short labels such as `Queue 042: Tickets routed to queue 42` that happens above 126 options on `laya` and 254 on the other two; the exact point moves with the length of the instructions and labels. For more candidates, narrow them first with `predict_shortlist` ([Honest limits](#honest-limits)).+* **Options per question.** A question's options share the checkpoint's option budget, `head_max_len` (192 tokens on `laya`, 256 on the other two). Once they overflow it, around 20 options with a short description each, every option is trimmed to fit, so long or similar labels can reach the model reading the same. Once they no longer fit the window at all, the request is rejected with 422. With short labels such as `Queue 042: Tickets routed to queue 42` that happens above 126 options on `laya` and 254 on the other two; the exact point moves with the length of the instructions and labels. For more candidates, narrow them first with `predict_shortlist` ([Honest limits](#honest-limits)).* **Score levels.** Every level needs a description. A `null` level is rejected with 422 rather than scored and echoed back in `legend`.-* **`confidence`** on `choice` and `score` answers is 1 minus normalised entropy, a measure of how concentrated the distribution is, not Jev's `(n·p_max − 1)/(n − 1)`. A threshold carried over from Jev does not transfer. For one calibrated number on every question type, gate on `answer_confidence`, the probability of the reported answer.+* **`confidence`** on `choice` and `score` answers is 1 minus normalised entropy, a measure of how concentrated the distribution is. For one calibrated number on every question type, gate on `answer_confidence`, the probability of the reported answer.### Nix / NixOSdiff --git a/docs/typescript-sdk.md b/docs/typescript-sdk.mdindex 5f1ebecc..188de79d 100644--- a/docs/typescript-sdk.md+++ b/docs/typescript-sdk.md@@ -1,8 +1,8 @@-# TypeScript HTTP SDK design+# TypeScript SDK design-`@laya/typescript-sdk` is a dependency-free HTTP client for the existing-`laya.serve` server. It uses the Jev-compatible `POST /v1/systemone` endpoint-introduced in #31; it adds no Python production code or server dependencies.+`laya-client` is a dependency-free HTTP client for a self-hosted `laya-serve`+server. It uses the `POST /v1/systemone` endpoint and adds no Python production+code or server dependencies.The npm package starts at version `0.1.0`, independently of Python releases.## Boundaries@@ -17,35 +17,34 @@ The npm package starts at version `0.1.0`, independently of Python releases.```mermaidflowchart LR- A[JavaScript or TypeScript application] --> B[Laya HTTP SDK]+ A[JavaScript or TypeScript application] --> B[laya-client]B -->|POST /v1/systemone| C[Existing Laya server]- B -->|POST /v1/systemone| D[Jev API]C --> E[Router and local checkpoint]```The SDK exports `predict` and a Laya-only `health` probe. It ships ESM,CommonJS and declarations, retaining inferred question IDs and choice labels.-The separate `laya-ts` package runs local ONNX inference; this HTTP client has-no JavaScript model runtime dependency.+Use `laya-client` when a JavaScript or TypeScript application talks over HTTP to+self-hosted Python `laya-serve`. Use `laya-ts` when inference must run directly+inside JavaScript through its local ONNX runtime, without a Python server.## Shared contract-Requests contain `state`, `questions`, and `model`. The default `jev-latest`-selects Jev's default model when calling TypeSafe and automatic routing when-calling Laya, whose server ignores unrecognized model IDs. A client-wide or-per-call `model` can select a Laya checkpoint or a different Jev model. Choice-label arrays are normalized to maps with null descriptions before transport.+Requests contain `state` and `questions`. Unless configured or supplied for a+prediction, `laya-client` omits `model`, letting `laya-serve` select a local+checkpoint automatically. A client-wide or per-call `model` can select a local+checkpoint. Choice label arrays are normalized to maps with null descriptions+before transport.Responses preserve `model`, `answers`, and token `usage`. Laya's `routing` andanswer `action` fields are optional extensions; Noul confidence is optional too.Choice and Score confidence, distributions, and Score legends remain required.-Optional extensions are validated when present. See the-[official Jev API contract](https://docs.typesafe.ai/api).+Optional extensions are validated when present.`/v1/systemone` does not expose Python's standalone routing method or `task` and`lang` overrides. The SDK rejects those legacy options instead of silently-ignoring them. Laya's public `/health` returns `status`, `loaded`, and `device`;-it is not part of the shared Jev protocol. Prediction never probes health first.+ignoring them. Laya's public `/health` returns `status`, `loaded`, and `device`.+Prediction never probes health first.FastAPI detail strings and validation arrays are preserved as `LayaAPIError`messages/details. Structured error envelopes from compatible backends are also@@ -54,19 +53,17 @@ are never retried automatically.## Verification and release-Unit tests cover the shared request contract, all three Jev answer shapes,-Laya extensions, FastAPI errors, JSON validation, deadlines and cancellation.+Unit tests cover request construction, all answer shapes, Laya extensions,+FastAPI errors, JSON validation, deadlines and cancellation.Type checks cover optional metadata, rejected legacy methods/options, inferredanswer types, and ESM/CommonJS consumers. The live integration test starts theunchanged `laya.serve` application with a tiny offline checkpoint, compares SDKpredictions against direct Python inference, and exercises routing, presets,authentication and request limits. CI runs the SDK checks on Node.js 22 and 24.-Jev compatibility is checked against documented contract fixtures; no hosted-Jev request is made by the test suite. Tiny random weights verify transport and-numerical parity, not pretrained quality or performance.+Tiny random weights verify transport and numerical parity, not pretrained+quality or performance.See the [SDK guide](../sdk/typescript/README.md) for setup, examples, and npm-publishing. The package is configured for public `@laya/typescript-sdk` releases-but publishing requires access to that npm scope. Python release workflows are-unchanged.+publishing. The package is published as `laya-client`. Python release workflows+are unchanged.diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 69588710..b3c9b3b2 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1,12 +1,12 @@-# @laya/typescript-sdk+# laya-client-A dependency-free HTTP client for Laya's Jev-compatible `/v1/systemone` endpoint. Supports ESM and+A dependency-free HTTP client for a self-hosted Laya `laya-serve` `/v1/systemone` endpoint. Supports ESM andCommonJS on Node.js 22+, and browsers with `fetch`, `AbortController`, and`structuredClone`. TypeScript consumers need TypeScript 5 or newer.-Inference runs in Laya's existing `laya.serve` server or the Jev API. JavaScript clients do not need-Python, PyTorch, or model weights installed; the server does. This package does-not run models directly in a browser or Node.js.+Inference runs in your self-hosted `laya-serve` process. JavaScript clients do+not need Python, PyTorch, or model weights installed; the server does. This+package does not run models directly in a browser or Node.js.## Run from this repository@@ -45,11 +45,10 @@ configuration uses environment variables, not command-line flags. See the## Install in another JavaScript project-The npm package name is `@laya/typescript-sdk`. After the first release is-published, install it with:+After the first release is published, install `laya-client` with:```sh-npm install @laya/typescript-sdk+npm install laya-client```You can also install the locally built tarball before publication:@@ -59,11 +58,11 @@ You can also install the locally built tarball before publication:npm pack# From your app, substitute the actual checkout path:-npm install /path/to/laya/sdk/typescript/laya-typescript-sdk-0.1.0.tgz+npm install /path/to/laya/sdk/typescript/laya-client-0.1.0.tgz``````js-import { Laya, triageQuestions } from '@laya/typescript-sdk';+import { Laya, triageQuestions } from 'laya-client';const laya = new Laya({ baseURL: 'http://127.0.0.1:8000' });const result = await laya.predict(@@ -79,7 +78,7 @@ console.log(result.routing?.model); // Laya-only metadataCommonJS works too:```js-const { Laya, triageQuestions } = require('@laya/typescript-sdk');+const { Laya, triageQuestions } = require('laya-client');const laya = new Laya();laya.predict({ message: 'Please refund my order' }, triageQuestions()).then(result => console.log(result.answers));@@ -92,7 +91,7 @@ Question IDs, primitive types, and choice labels are inferred. UseInline schemas also infer automatically.```ts-import { Laya, defineQuestions } from '@laya/typescript-sdk';+import { Laya, defineQuestions } from 'laya-client';const laya = new Laya();const questions = defineQuestions({@@ -133,47 +132,33 @@ Response fields retain Python's spelling (`input_tokens`, `act_probability`,etc.). Scores use zero-based rubric levels. Confidence and accuracy have thesame calibration limits as the Python model; see the root README.-## Jev compatibility and model selection+## Local model selection-The same `predict` method calls [TypeSafe's System One API](https://docs.typesafe.ai/api):--```js-const jev = new Laya({- baseURL: 'https://api.typesafe.ai', // server root; do not append /v1- apiKey: process.env.TYPESAFE_API_KEY,-});-const result = await jev.predict('Please refund the duplicate charge.', triageQuestions());-console.log(result.answers.refund_requested.noul);-```--The default request model is `jev-latest`. Jev uses that model alias; Laya ignores-unrecognized model IDs and chooses a local checkpoint automatically. This lets-the same prediction code switch servers through `baseURL` and credentials.-Set a client-wide `model` or override it per prediction to select a checkpoint:+By default, `laya-client` sends no `model` property. `laya-serve` then chooses+the appropriate local checkpoint automatically. Set a client-wide `model` or+override it per prediction only when a specific local checkpoint is required:```jsconst laya = new Laya({ model: 'english' });await laya.predict(state, questions, { model: 'typed-decisions' });await laya.predict(state, questions, { model: 'multilingual' });-await jev.predict(state, questions, { model: 'jev-preview' });```-Laya accepts its checkpoint aliases and published multilingual/typed-decisions-model IDs. Use a Jev model ID when calling Jev. The HTTP endpoint supports-`model`; it does not expose standalone `route()`, `task`, or `lang` overrides.-Laya still detects language automatically; set `LAYA_AUTO_TASK=1` on the server-to enable automatic workflow routing.+Laya accepts its local checkpoint aliases. The HTTP endpoint supports `model`;+it does not expose standalone `route()`, `task`, or `lang` overrides. Laya+still detects language automatically; set `LAYA_AUTO_TASK=1` on the server to+enable automatic workflow routing.++Laya returns `model`, `answers`, and `usage`, with optional `routing`, answer+`action`, and Noul `confidence` metadata. Those fields are validated when+present. Choice and Score confidence remains required. `health()` is never+called by `predict()`.-Both servers return `model`, `answers`, and `usage`. Laya additionally returns-`routing`, answer `action`, and Noul `confidence`. Those extensions are optional-in the SDK types and validated when present. Choice and Score confidence remains-required. `health()` is a Laya-only probe and is never called by `predict()`.+## Which JavaScript client?-Jev compatibility is covered by fixtures based on its official API contract;-the automated suite does not call the hosted service. Jev also enforces its own-input limits (up to 255 Choice options and 2–10 Score levels). Use text/object/array-state for portability; null state and broader JSON scalar descriptions are Laya-extensions accepted by this SDK.+Use `laya-client` when a JavaScript or TypeScript application talks over HTTP to+self-hosted Python `laya-serve`. Use `laya-ts` when inference must run directly+inside JavaScript through its local ONNX runtime, without a Python server.## Presets@@ -182,14 +167,14 @@ Available preset functions: `triageQuestions()`, `emailQuestions(categories?)`,a fresh schema. Email categories can be customized:```js-import { emailQuestions } from '@laya/typescript-sdk';+import { emailQuestions } from 'laya-client';const questions = emailQuestions({ finance: 'payments', engineering: 'bugs' });```## Errors, cancellation, authentication```js-import { Laya, LayaAPIError, LayaTimeoutError } from '@laya/typescript-sdk';+import { Laya, LayaAPIError, LayaTimeoutError } from 'laya-client';const client = new Laya({baseURL: 'http://127.0.0.1:8000',@@ -227,8 +212,8 @@ and TLS at your application proxy or gateway.| Endpoint | Request | Response || --- | --- | --- |-| `GET /health` (Laya only) | None | `{status, loaded, device}` |-| `POST /v1/systemone` | `{state, questions, model}` | `{model, answers, usage}` plus optional Laya `routing` |+| `GET /health` | None | `{status, loaded, device}` |+| `POST /v1/systemone` | `{state, questions, model?}` | `{model, answers, usage}` plus optional `routing` |Laya errors use FastAPI's `{detail: ...}` body: 400 for malformed requests, 401for authentication, 413 for request limits, 422 for invalid questions, and 500@@ -272,9 +257,8 @@ with `python3 scripts/sync_presets.py` after editing that source.## Publishing-Publish from `sdk/typescript` using an npm account with publishing rights in the-`@laya` scope. npm uses `@scope/package` names; `laya/typescript-sdk` without `@`-is not this registry package. See [npm's scoped package guide](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/).+Publish `laya-client` from `sdk/typescript` using an npm account with publishing+rights for that package name.```shnpm login --registry=https://registry.npmjs.org@@ -300,6 +284,6 @@ package. npm does not allow republishing an already-used name/version pair.After publication, verify the release and install it into a clean project:```sh-npm view @laya/typescript-sdk version --registry=https://registry.npmjs.org-npm install @laya/typescript-sdk+npm view laya-client version --registry=https://registry.npmjs.org+npm install laya-client```diff --git a/sdk/typescript/examples/benchmark.ts b/sdk/typescript/examples/benchmark.tsdeleted file mode 100644index e0b1a783..00000000--- a/sdk/typescript/examples/benchmark.ts+++ /dev/null@@ -1,47 +0,0 @@-import {- Laya,- defineQuestions,-} from "@laya/typescript-sdk";-const laya = new Laya({- baseURL: "http://127.0.0.1:8000",- // Allow time for the first model download.- timeoutMs: 600_000,-});--const questions = defineQuestions({- refund: {- type: "noul",- instructions: "Does the customer request a refund?",- },-});--const state = {- message: "I was charged twice. Please refund it.",-};----async function main() {- const health = await laya.health();- console.log("Server:", health);-- for (let i = 1; i <= 10; i++) {- const start = performance.now();-- const result = await laya.predict(state, questions, {- model: "english", // prefer the "english" model for this test- });-- const elapsedMs = performance.now() - start;-- console.log(- `Request ${i}: ${elapsedMs.toFixed(2)} ms, ` +- `tokens=${result.usage.input_tokens}, ` +- `model=${result.routing?.model ?? result.model}`,- );-}-}--main().catch((error: unknown) => {- console.error(error);-});diff --git a/sdk/typescript/examples/triage.mjs b/sdk/typescript/examples/triage.mjsindex 17ea14d9..140b9414 100644--- a/sdk/typescript/examples/triage.mjs+++ b/sdk/typescript/examples/triage.mjs@@ -1,4 +1,4 @@-import { Laya, triageQuestions } from '@laya/typescript-sdk';+import { Laya, triageQuestions } from 'laya-client';const laya = new Laya({baseURL: process.env.LAYA_BASE_URL ?? 'http://127.0.0.1:8000',@@ -10,7 +10,6 @@ try {const result = await laya.predict({ message: 'I was billed twice for March. Please refund the duplicate today.' },triageQuestions(),- { model: 'english'});console.log(JSON.stringify(result, null, 2));} catch (error) {diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.jsonindex 61d00b16..958f88ba 100644--- a/sdk/typescript/package-lock.json+++ b/sdk/typescript/package-lock.json@@ -1,11 +1,11 @@{- "name": "@laya/typescript-sdk",+ "name": "laya-client","version": "0.1.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "@laya/typescript-sdk",+ "name": "laya-client","version": "0.1.0","license": "Apache-2.0","devDependencies": {diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 6fcc7de7..bf17cd6e 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -1,5 +1,5 @@{- "name": "@laya/typescript-sdk",+ "name": "laya-client","version": "0.1.0","description": "Typed JavaScript client for the self-hosted Laya decision engine","license": "Apache-2.0",diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 93547b0b..f75692d9 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -10,7 +10,7 @@ export interface LayaOptions {/** Server root URL, optionally including a reverse-proxy path prefix. */baseURL?: string;apiKey?: string;- /** Default jev-latest: used by Jev and treated as automatic routing by Laya. */+ /** Optional local checkpoint or alias to send with every prediction. */model?: string;/** Default 120000 ms; cold checkpoint downloads may require more. Zero disables. */timeoutMs?: number;@@ -24,7 +24,7 @@ export class Laya {private readonly timeoutMs: number;private readonly headers: Headers;private readonly fetcher: typeof globalThis.fetch;- private readonly model: string;+ private readonly model: string | undefined;constructor(options: LayaOptions = {}) {let url: URL;@@ -34,8 +34,8 @@ export class Laya {throw new LayaValidationError('baseURL must be HTTP(S), without credentials, query, or fragment');}this.baseURL = url.href.replace(/\/+$/, '');- this.model = options.model ?? 'jev-latest';- if (typeof this.model !== 'string' || !this.model.trim()) {+ this.model = options.model;+ if (this.model !== undefined && (typeof this.model !== 'string' || !this.model.trim())) {throw new LayaValidationError('model must be a nonempty string');}this.timeoutMs = options.timeoutMs ?? 120_000;@@ -55,7 +55,7 @@ export class Laya {return result;}- /** Query the self-hosted Laya server's health probe. Not supported by Jev. */+ /** Query the self-hosted Laya server's health probe. */async health(options: RequestOptions = {}): Promise<Health> {const result = await this.request<Health>('/health', undefined, options);validateHealth(result);@@ -70,15 +70,16 @@ export class Laya {if (key in options) throw new LayaValidationError(`${key} is not supported by /v1/systemone; use model instead`);}const model = options.model ?? this.model;- if (typeof model !== 'string' || !model.trim()) throw new LayaValidationError('model must be a nonempty string');- // Validate before normalizing so JSON-incompatible values cannot be hidden.- validateJson({ state, questions, model });+ if (model !== undefined && (typeof model !== 'string' || !model.trim())) {+ throw new LayaValidationError('model must be a nonempty string');+ }const wireQuestions = Object.fromEntries(Object.entries(questions).map(([id, question]) => [id,question.type === 'choice' && Array.isArray(question.criteria)? { ...question, criteria: Object.fromEntries(question.criteria.map(label => [label, null])) }: question,]));- const body = { state, questions: wireQuestions, model };+ const body: { state: State; questions: typeof wireQuestions; model?: string } = { state, questions: wireQuestions };+ if (model !== undefined) body.model = model;validateJson(body);return JSON.stringify(body);}diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 03891919..68fe12ce 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -30,12 +30,12 @@ export interface RequestOptions {timeoutMs?: number;}export interface PredictOptions extends RequestOptions {- /** Laya checkpoint/alias or Jev model ID. Overrides the client's default model. */+ /** Local Laya checkpoint or alias. Overrides the client's configured model. */model?: string;}interface AnswerBase {- /** Laya extension; absent from Jev responses. */+ /** Optional action metadata returned by Laya. */action?: { act_probability: number };}export interface ChoiceAnswer<Label extends string = string> extends AnswerBase {@@ -54,7 +54,7 @@ export interface ScoreAnswer extends AnswerBase {}export interface NoulAnswer extends AnswerBase {type: 'noul';- /** Laya extension; Jev returns only type and noul. */+ /** Optional confidence metadata returned by Laya. */confidence?: number;/** P(true), between 0 and 1. */noul: number;@@ -85,10 +85,10 @@ export interface Prediction<Q extends Questions = Questions> {model: string;answers: Answers<Q>;usage: { input_tokens: number; output_tokens: number };- /** Laya extension; absent from Jev responses. */+ /** Optional routing metadata returned by Laya. */routing?: RouteDecision;}-/** Laya's health probe; not part of the shared Jev protocol. */+/** Laya's self-hosted health probe. */export interface Health {status: 'ok';loaded: ModelName[];diff --git a/sdk/typescript/test/client.test.mjs b/sdk/typescript/test/client.test.mjsindex 748a9072..021fde6f 100644--- a/sdk/typescript/test/client.test.mjs+++ b/sdk/typescript/test/client.test.mjs@@ -4,7 +4,7 @@ import { test } from 'node:test';import {Laya, LayaAPIError, LayaAbortError, LayaConnectionError, LayaTimeoutError,LayaValidationError, LayaResponseError, emailQuestions, triageQuestions,-} from '@laya/typescript-sdk';+} from 'laya-client';const questions = { refund: { type: 'noul', instructions: 'Refund?' } };const json = (value, status = 200) => new Response(JSON.stringify(value), { status });@@ -14,7 +14,7 @@ const prediction = { model: 'laya-rl-agent', routing: route, usage: { input_tokeanswers: { refund: { type: 'noul', noul: 0.9, confidence: 0.9, action: { act_probability: 0.8 } } } };test('ESM and CommonJS exports can be consumed by ordinary JavaScript', () => {- const cjs = createRequire(import.meta.url)('@laya/typescript-sdk');+ const cjs = createRequire(import.meta.url)('laya-client');assert.equal(typeof cjs.Laya, 'function');assert.deepEqual(cjs.triageQuestions(), triageQuestions());});@@ -47,14 +47,13 @@ test('Laya health uses GET and accepts the existing server response', async () =assert.equal(client.route, undefined);});-// Contract fixtures based on https://docs.typesafe.ai/api (no live Jev credentials required).-const jevQuestions = {+const allAnswerQuestions = {team: { type: 'choice', instructions: 'Team?', criteria: ['billing', 'support'] },urgency: { type: 'score', instructions: 'Urgency?', criteria: ['low', 'high'] },refund: questions.refund,};-const jevPrediction = {- model: 'jev-1.13.0', usage: { input_tokens: 20, output_tokens: 10 },+const allAnswerPrediction = {+ model: 'english', usage: { input_tokens: 20, output_tokens: 10 },answers: {team: { type: 'choice', choice: 'billing', probabilities: { billing: 0.8, support: 0.2 }, confidence: 0.6 },urgency: { type: 'score', score: 0.7, probabilities: { '0': 0.3, '1': 0.7 }, legend: { '0': 'low', '1': 'high' }, confidence: 0.4 },@@ -62,31 +61,29 @@ const jevPrediction = {},};-test('shared protocol accepts all Jev answer types without Laya extensions', async () => {- for (const baseURL of ['http://127.0.0.1:8000', 'https://api.typesafe.ai']) {- const client = new Laya({ baseURL, apiKey: 'test-key', fetch: async (url, init) => {- assert.equal(url, `${baseURL}/v1/systemone`);- assert.equal(init.headers.get('Authorization'), 'Bearer test-key');- assert.deepEqual(JSON.parse(init.body), {- state: 'Refund please', model: 'jev-latest',- questions: { ...jevQuestions, team: { ...jevQuestions.team, criteria: { billing: null, support: null } } },- });- return json(jevPrediction);- } });- assert.deepEqual(await client.predict('Refund please', jevQuestions), jevPrediction);- }- assert.deepEqual(jevQuestions.team.criteria, ['billing', 'support'], 'normalization must not mutate the schema');+test('default request omits model and supports every Laya answer type', async () => {+ const client = new Laya({ baseURL: 'http://127.0.0.1:8000', apiKey: 'test-key', fetch: async (url, init) => {+ assert.equal(url, 'http://127.0.0.1:8000/v1/systemone');+ assert.equal(init.headers.get('Authorization'), 'Bearer test-key');+ assert.deepEqual(JSON.parse(init.body), {+ state: 'Refund please',+ questions: { ...allAnswerQuestions, team: { ...allAnswerQuestions.team, criteria: { billing: null, support: null } } },+ });+ return json(allAnswerPrediction);+ } });+ assert.deepEqual(await client.predict('Refund please', allAnswerQuestions), allAnswerPrediction);+ assert.deepEqual(allAnswerQuestions.team.criteria, ['billing', 'support'], 'normalization must not mutate the schema');});-test('client model default supports arbitrary Jev IDs and request overrides', async () => {+test('client model default and prediction overrides select local checkpoints', async () => {const models = [];- const client = new Laya({ model: 'jev-preview', fetch: async (_url, init) => {+ const client = new Laya({ model: 'english', fetch: async (_url, init) => {models.push(JSON.parse(init.body).model);return json(prediction);} });await client.predict('hello', questions);- await client.predict('hello', questions, { model: 'convaiinnovations/laya-multilingual' });- assert.deepEqual(models, ['jev-preview', 'convaiinnovations/laya-multilingual']);+ await client.predict('hello', questions, { model: 'multilingual' });+ assert.deepEqual(models, ['english', 'multilingual']);});test('unsupported routing options and invalid models fail before sending a request', async () => {@@ -140,7 +137,7 @@ test('structured API errors keep status, code and validation details; no retriestest('FastAPI errors preserve detail strings and validation arrays', async () => {for (const [status, detail] of [[401, 'invalid or missing bearer token'],- [422, [{ loc: ['body', 'model'], msg: 'Field required', type: 'missing' }]],+ [422, [{ loc: ['body', 'questions'], msg: 'Field required', type: 'missing' }]],[413, 'request body too large'], [500, 'inference failed']]) {await assert.rejects(new Laya({ fetch: async () => json({ detail }, status) }).predict('hello', questions), error => {assert.ok(error instanceof LayaAPIError);@@ -172,14 +169,14 @@ test('malformed answers cannot masquerade as typed predictions', async () => {}});-test('Jev compatibility still rejects malformed required fields and optional extensions', async () => {+test('prediction validation rejects malformed required fields and optional extensions', async () => {for (const mutate of [p => { delete p.answers.team.confidence; }, p => { delete p.answers.urgency.legend; },p => { p.answers.team.choice = 'unknown'; }, p => { delete p.answers.team.probabilities.billing; },p => { p.answers.urgency.score = 2; }, p => { p.answers.refund.confidence = 'high'; },p => { p.answers.refund.action = { act_probability: 2 }; }, p => { p.routing = null; }]) {- const payload = structuredClone(jevPrediction);+ const payload = structuredClone(allAnswerPrediction);mutate(payload);- await assert.rejects(new Laya({ fetch: async () => json(payload) }).predict('hello', jevQuestions), LayaResponseError);+ await assert.rejects(new Laya({ fetch: async () => json(payload) }).predict('hello', allAnswerQuestions), LayaResponseError);}});diff --git a/sdk/typescript/test/commonjs.cts b/sdk/typescript/test/commonjs.ctsindex 804876c8..1bb97929 100644--- a/sdk/typescript/test/commonjs.cts+++ b/sdk/typescript/test/commonjs.cts@@ -1,4 +1,4 @@-import sdk = require('@laya/typescript-sdk');+import sdk = require('laya-client');const client = new sdk.Laya();const questions = sdk.defineQuestions({ q: { type: 'noul', instructions: 'Does it work?' } });async function run() {diff --git a/sdk/typescript/test/integration.mjs b/sdk/typescript/test/integration.mjsindex f6067bc7..4233225a 100644--- a/sdk/typescript/test/integration.mjs+++ b/sdk/typescript/test/integration.mjs@@ -5,7 +5,7 @@ import { createInterface } from 'node:readline';import { fileURLToPath } from 'node:url';import { setTimeout as delay } from 'node:timers/promises';import { test } from 'node:test';-import { Laya, LayaAPIError, triageQuestions, emailQuestions, guardQuestions, moderationQuestions, routerQuestions } from '@laya/typescript-sdk';+import { Laya, LayaAPIError, triageQuestions, emailQuestions, guardQuestions, moderationQuestions, routerQuestions } from 'laya-client';test('JavaScript → HTTP → Python Router → real offline Agent inference', { timeout: 90_000 }, async t => {const script = fileURLToPath(new URL('../../../tests/sdk_server_fixture.py', import.meta.url));@@ -51,8 +51,6 @@ test('JavaScript → HTTP → Python Router → real offline Agent inference', {assert.equal(result.usage.output_tokens, 0);assert.equal((await client.predict({ text: 'मुझे पैसे वापस चाहिए' }, fixture.questions)).routing.model, 'multilingual');assert.equal((await client.predict('hello', fixture.questions, { model: 'typed_decisions' })).routing.model, 'typed-decisions');- assert.equal((await client.predict('hello', fixture.questions, { model: 'convaiinnovations/laya-multilingual' })).routing.model, 'multilingual');- assert.equal((await client.predict('hello', fixture.questions, { model: 'jev-preview' })).routing.model, 'english');for (const preset of [triageQuestions, emailQuestions, guardQuestions, moderationQuestions, routerQuestions]) {const questions = preset();diff --git a/sdk/typescript/test/types.ts b/sdk/typescript/test/types.tsindex 01105e30..51230d9f 100644--- a/sdk/typescript/test/types.ts+++ b/sdk/typescript/test/types.ts@@ -1,4 +1,4 @@-import { Laya, defineQuestions, emailQuestions, triageQuestions, type Questions, type Answer } from '@laya/typescript-sdk';+import { Laya, defineQuestions, emailQuestions, triageQuestions, type Questions, type Answer } from 'laya-client';const client = new Laya();const questions = defineQuestions({@@ -16,9 +16,9 @@ const noul: number = result.answers.refund.noul;const routingModel: string | undefined = result.routing?.model;const actionProbability: number | undefined = result.answers.team.action?.act_probability;const noulConfidence: number | undefined = result.answers.refund.confidence;-// @ts-expect-error Jev does not return Laya routing metadata.+// @ts-expect-error Routing metadata is optional.result.routing.model;-// @ts-expect-error Jev does not return action probabilities.+// @ts-expect-error Action metadata is optional.result.answers.team.action.act_probability;// @ts-expect-error /v1/systemone does not expose standalone routing.client.route('hello');@@ -26,8 +26,8 @@ client.route('hello');client.predict('hello', questions, { task: 'typed' });// @ts-expect-error /v1/systemone supports model, not lang.client.predict('hello', questions, { lang: 'hi' });-client.predict('hello', questions, { model: 'jev-preview' });-new Laya({ model: 'jev-latest' });+client.predict('hello', questions, { model: 'multilingual' });+new Laya({ model: 'english' });// @ts-expect-error A score answer has no choice field.result.answers.priority.choice;// @ts-expect-error Unknown question IDs are not valid.