Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-22: Janas-LLM in Node.js - janas.node, the library as a module for Node.js with its types for TypeScript (Linux): a model opened inside the process, its replies read with for await as they are written, stopped by leaving the loop or by an AbortSignal, the same text byte for byte as the library's own in C (tests/node_check on Qwen3-0.6B, also under AddressSanitizer and ThreadSanitizer); examples/node-chat, a chat in TypeScript on it, server and page: the model inside the server's process, its replies streamed to the browser

camauriab7afa04c28a
diff --git a/ChangeLog.md b/ChangeLog.md
index 62a8f34..d41ca7d 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,11 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-21] - Janas-LLM in Node.js
+
+- **`janas.node`, the library as a module for Node.js** (Linux), made by `./build.sh` beside the programs, with its types for TypeScript (`janas.d.ts`): `open()` a model, `model.chat()`, then `chat.send(text)` or `chat.load(messages)` and the reply read with `for await`, piece by piece (the answer, the reasoning, how much of a long prompt is read), or whole with `reply.text()`, its counters with `reply.stats()`. Leaving the loop, `reply.stop()` or an `AbortSignal` stops it. Each model runs on a thread of its own, so JavaScript's thread never waits for it; a model's replies come one at a time, in the order asked; an idle model does not keep Node running, and one left open is closed when Node leaves. Written in C against Node-API (version 8), whose functions it declares itself: building it needs nothing of Node's (checked against Node's headers where they are installed). Tried with Node 20: `tests/test_node` without a model, in the suite, and `tests/node_check` on Qwen3-0.6B, where the replies through Node are the library's own in C, byte for byte; both also under AddressSanitizer and ThreadSanitizer. `docs/library.md`, "From Node.js".
+- **`examples/node-chat`, a chat in TypeScript on the module**: a server on `node:http` that opens the model in its own process and streams each reply to the browser as it is written (server-sent events), a page that keeps the conversation and shows the reasoning apart and what each reply cost, and the types of what goes between the two shared by both sides. A client that goes away stops its reply; requests from several pages wait in line, told how many are before them.
+
## [2026-10-21] - Intel's NPU reads the prompts
- **The NPU of Intel's Core Ultra processors reads a prompt's blocks** (Linux; tried on the first generation's, Meteor Lake, "Intel AI Boost"). Janas-LLM writes the NPU's graphs itself, in OpenVINO's IR format, and opens Intel's Level Zero driver when a model opens: nothing is linked against it, and without it nothing changes. The weights it takes are copied in eight bits with a scale for each row and computed in sixteen-bit floats, the norms in 32. A dense model whose layers fit in the NPU's memory, nine in ten at least, goes to it layer by layer, whole - Qwen3, Qwen3.5 and Gemma 4's dense models - each block of the prompt in two halves, the NPU computing a layer on one while the CPU computes the attention, or Qwen3.5's recurrence, on the other; a larger model, or a mixture of experts, gives it the products of the weights that stay in memory. On the development laptop, `janas-bench --prompt 1024 --gen 16 --rounds 2`, the best configuration with the NPU against the best without it (the GPU's fast prompt): Qwen3-0.6B 1,421 tok/s against 974, Qwen3.5-0.8B 1,403 against 950, Qwen3.5-2B 729 against 477, Gemma-4-E2B 508 against 196, Qwen3-4B 333 against 201, Gemma-4-E4B 245 against 129. A reply is written by the CPU as before.
diff --git a/README.md b/README.md
index 00b62d3..c0a1ef2 100644
--- a/README.md
+++ b/README.md
@@ -191,7 +191,8 @@ sudo pacman -S vulkan-headers glslang vulkan-tools # the same, Arch
- [docs/features.md](docs/features.md) — what Janas-LLM runs today, model by model and feature by feature
- [docs/models.md](docs/models.md) — getting a model: `janas-get`, or a GGUF file converted, and which files were checked
- [docs/chat.md](docs/chat.md) — `janas-chat`: its options and commands, the drafts, Janas's services, tools from MCP servers, a long prompt watched as it is read
-- [docs/library.md](docs/library.md) — using it from a program, in C or in FreeBASIC and BASIC MODERN, and MCP servers from a program
+- [docs/library.md](docs/library.md) — using it from a program, in C, in FreeBASIC and BASIC MODERN, or in Node.js and TypeScript, and MCP servers from a program
+- [examples/node-chat](examples/node-chat/README.md) — a chat in TypeScript on the module for Node.js: the model inside the server's process, its replies streamed to the browser
- [docs/serving.md](docs/serving.md) — the model as tools for Claude Code, editors and other MCP clients (`janas-mcp`), and over HTTP, an API that follows OpenAI's with a chat page to try it from a browser (`janas-server`)
- [docs/code-completion.md](docs/code-completion.md) — code filled in at an editor's cursor, in VSCodium and VS Code through `janas-server`: 1.5-2.2 s a proposal on a laptop, where a window slid a line was read again in 17 s
- [docs/tools.md](docs/tools.md) — the converters, checkers and benchmarks built beside the programs
diff --git a/build.sh b/build.sh
index 10ffb12..ca068d6 100755
--- a/build.sh
+++ b/build.sh
@@ -62,6 +62,9 @@ Output
under src/ goes into the library. The release build
also links libjanas_llm.so and libjanas_mcp.so, which export the public
APIs of include/janas/llm.h and include/janas/mcp.h and nothing else.
+ On Linux src/node/ becomes janas.node, the module for Node.js, with the
+ library inside (janas-<variant>.node for the other variants), and its
+ TypeScript declarations, janas.d.ts, beside it.
Environment
CC the compiler, gcc by default
@@ -201,13 +204,14 @@ clean()
{
rm -rf "$OBJ"
if [ -n "$SUFFIX" ]; then
- rm -f "$BIN"/*"$SUFFIX"
+ rm -f "$BIN"/*"$SUFFIX" "$BIN"/*"$SUFFIX".node
return
fi
for f in "$BIN"/*; do
[ -e "$f" ] || continue
case "$f" in
*-debug | *-asan | *-ubsan | *-tsan) continue ;;
+ *-debug.node | *-asan.node | *-ubsan.node | *-tsan.node) continue ;;
esac
rm -f "$f"
done
@@ -456,10 +460,11 @@ flags=$(tp_flags mbedtls) || exit 2
MBEDTLS_INC=($flags)
# A directory with a main.c is a program: its other .c files are its own.
-# Every other .c under src/ goes into the library.
+# Every other .c under src/ goes into the library, but the module for
+# Node.js (src/node/), which is linked on its own below.
tool_dirs=$(for m in src/*/main.c src/services/*/main.c; do dirname "$m"; done)
lib_list=$(sources src/ find src -name '*.c' ! -name main.c ! -name win_start.c \
- ! -path 'src/third_party/*') || exit 2
+ ! -path 'src/third_party/*' ! -path 'src/node/*') || exit 2
objs=()
while IFS= read -r src; do
grep -qx "$(dirname "$src")" <<<"$tool_dirs" && continue
@@ -515,6 +520,38 @@ if [ "$VARIANT" = release ]; then
"$OBJ/libjanas_third.a" "${LDLIBS[@]}" -o "$BIN/libjanas_mcp.so"
fi
fi
+# The module for Node.js: its own files and the library, in one janas.node
+# that Node loads. The functions of Node-API are the node process's, so they
+# stay undefined here - and only they: in release anything else undefined
+# stops the build, as --no-undefined does for the libraries above. Linux
+# only, for now: on Windows they would come from node.exe's import library.
+if [ "$OS" != windows ]; then
+ node_objs=()
+ node_list=$(sources src/node find src/node -maxdepth 1 -name '*.c') || exit 2
+ while IFS= read -r c; do
+ obj=$(objname "$c")
+ node_objs+=("$obj")
+ compile "$c" "$obj" "${CFLAGS[@]}"
+ done < <(sort <<<"$node_list")
+ addon="$BIN/janas$SUFFIX.node"
+ echo "LD $addon"
+ "$CC" "${CFLAGS[@]}" -shared "${node_objs[@]}" "$OBJ/libjanas.a" \
+ "${LDLIBS[@]}" -o "$addon"
+ if [ "$VARIANT" = release ]; then
+ if ! missing=$(nm -D --undefined-only "$addon" |
+ awk '$1 == "U" && $2 !~ /@/ && $2 !~ /^napi_/ { print $2 }'); then
+ echo "build.sh: cannot list what $addon needs (nm)" >&2
+ exit 2
+ fi
+ if [ -n "$missing" ]; then
+ echo "build.sh: $addon needs what it does not have:" $missing >&2
+ exit 2
+ fi
+ fi
+ [ "$BIN/janas.d.ts" -nt src/node/janas.d.ts ] ||
+ cp src/node/janas.d.ts "$BIN/janas.d.ts"
+fi
+
THIRD=()
[ -f "$OBJ/libjanas_third.a" ] && THIRD=("$OBJ/libjanas_third.a")
# Windows: every program starts with the console made ready for UTF-8 and
diff --git a/docs/library.md b/docs/library.md
index 432b784..0d64618 100644
--- a/docs/library.md
+++ b/docs/library.md
@@ -1,6 +1,6 @@
# Using it from a program
-The library is shaped for foreign-function interfaces from the start: opaque handles, fixed-width types, nothing passed by value that is not a number, parameter blocks that carry their own size, error codes as `int32`, and reply text returned on request as whole UTF-8 characters. It is declared for **C** and for **FreeBASIC**.
+The library is shaped for foreign-function interfaces from the start: opaque handles, fixed-width types, nothing passed by value that is not a number, parameter blocks that carry their own size, error codes as `int32`, and reply text returned on request as whole UTF-8 characters. It is declared for **C** and for **FreeBASIC**, and it is a module for **Node.js** too, with its types for TypeScript.
## From C
@@ -63,6 +63,28 @@ echo "Hello! Introduce yourself." | LD_LIBRARY_PATH=bin/x86_64-linux ./janas-cha
Two things to know. FreeBASIC does not tell names apart by their case, so the constant the C header calls `JANAS_LLM_ABI_VERSION` is `JANAS_LLM_ABI` there — it would otherwise collide with the function `janas_llm_abi_version()`. And its `line input` reads the terminal, not the standard input: to work in a pipe too, `chat.bas` asks `isatty` and reads a pipe through the `CONS` device.
+## From Node.js
+
+`janas.node` is the library as a module for Node.js, made by `./build.sh` on Linux beside the programs (`bin/x86_64-linux/janas.node`), with its types for TypeScript beside it (`janas.d.ts`). It is written in C against Node-API, version 8, whose functions it declares itself: building it needs nothing of Node's. It was tried with Node 20. Each model runs on a thread of its own, so JavaScript's thread never waits for it, and a reply is read as it is written:
+
+```ts
+import { createRequire } from "node:module";
+import type * as Janas from "./janas.js"; // janas.d.ts
+
+const janas = createRequire(import.meta.url)("./janas.node") as typeof Janas;
+const model = await janas.open("qwen3-next.jns", { context: 8192 });
+const chat = await model.chat({ thinking: false });
+for await (const piece of chat.send("Hello! Introduce yourself."))
+ if (piece.type === "text") process.stdout.write(piece.text);
+await model.close();
+```
+
+A piece is the model's text (`reasoning` says whether it is its reasoning or its answer), or, while a long prompt is read, how much of it is (`type: "progress"`, `read` of `total` tokens). `chat.load(messages)` takes a whole conversation, as a server gets it from its client; what it shares with the conversation already computed is not read again. A reply stops when the loop is left (`break`, `return`, an exception), with `reply.stop()`, or with an `AbortSignal` given as `{ signal }` - the client of a request gone. `reply.text()` gives the whole answer, its reasoning left out, and `reply.stats()` the counters (tokens, seconds, how much of the prompt was already read, why it ended). A model holds one conversation, and one chat: replies asked for while another is written wait for it, in order. `model.status()` says, without waiting for the engine, how the expert cache fills and the NPU is made ready. Wrong arguments throw a `TypeError` that names them; what fails in the engine rejects with an `Error` whose `code` says what (`EOPEN`, `EBUSY`, `EFULL`, ...: the suffixes of the library's `JANAS_LLM_E...`). An idle model does not keep Node running, and a model left open is closed when Node leaves.
+
+What has been run: `tests/test_node`, among the tests `./build.sh test` runs (the module without a model: its classes, its errors, engine threads started and ended), and `tests/node_check` on Qwen3-0.6B: the replies through Node the same text, byte for byte, as the library's own in C, streamed and read whole, after a reset and in a new chat; a reply stopped by leaving the loop, by a signal fired and by one aborted before; two replies asked at once; a prompt of several blocks; reasoning on and off; closing twice; a model left open when Node leaves. Both also under AddressSanitizer and ThreadSanitizer, the sanitizer's runtime preloaded into node. The module is not built for Windows yet.
+
+[`examples/node-chat`](../examples/node-chat/README.md) is a chat in TypeScript on it, server and page: the model inside the server's process, its replies streamed to the browser as they are written, the types of what goes between the two shared by both sides.
+
## MCP servers from a program
[`include/janas/mcp.h`](../include/janas/mcp.h) is the MCP client the chat uses, as a library of its own, `libjanas_mcp`, which needs nothing of `libjanas_llm`; [`include/janas/mcp.bi`](../include/janas/mcp.bi) declares it for FreeBASIC. It fits the model's side of the tools: `janas_mcp_tools` gives a server's tools as the JSON `janas_llm_chat_tools` takes, the calls the model writes go to `janas_mcp_call`, and what `janas_mcp_result` returns goes back with `janas_llm_chat_send_results`.
diff --git a/examples/node-chat/.gitignore b/examples/node-chat/.gitignore
new file mode 100644
index 0000000..b947077
--- /dev/null
+++ b/examples/node-chat/.gitignore
@@ -0,0 +1,2 @@
+node_modules/
+dist/
diff --git a/examples/node-chat/README.md b/examples/node-chat/README.md
new file mode 100644
index 0000000..7a87ff7
--- /dev/null
+++ b/examples/node-chat/README.md
@@ -0,0 +1,45 @@
+# A chat in TypeScript on Janas-LLM in Node.js
+
+The model runs inside the server's own Node.js process, through `janas.node`, the module for Node.js that Janas's `build.sh` makes beside its programs: no other server, no port of its own, no HTTP between the two. The browser gets each reply as the model writes it.
+
+```
+browser (TypeScript) --POST /api/chat--> Node.js server (TypeScript) --chat.load()--> janas.node --> Janas-LLM
+ <--server-sent events, piece by piece-- <--for await (const piece of reply)--
+```
+
+- `src/shared/` is compiled for both sides: the protocol's types (`ChatRequest`, `StreamEvent`, ...), the check of a request, and the coding of the events on the wire.
+- `src/server/` opens the model (`janas.open()`), keeps one chat, and answers `POST /api/chat` with the reply streamed: `chat.load(messages, { signal })` and `for await` over its pieces. A page that stops or goes away aborts the request, and the reply stops with it.
+- `src/web/` is the page: the conversation kept there and sent whole each time (the engine reads again only what is new), the reasoning apart from the answer, and under every reply what it cost (tokens per second, the first token's time, how much of the prompt was already read).
+- The types of the module are Janas's own `src/node/janas.d.ts`.
+
+## What it needs
+
+- Linux x86-64 and Node.js 20 or later.
+- Janas built (`./build.sh` in the repository's root), which makes `bin/x86_64-linux/janas.node`.
+- A model converted for Janas-LLM (`.jns`), such as `models/jns/qwen3-4b-q4km.jns`.
+
+## Building and running
+
+```sh
+npm install # TypeScript and Node's types, for building only
+npm run build # dist/node/ for the server, dist/web/ for the page
+npm start -- --model ../../models/jns/qwen3-4b-q4km.jns
+```
+
+Then open `http://127.0.0.1:8090/`. The options: `--port` (8090), `--host` (127.0.0.1: this machine only), `--cache` (GiB for the expert cache; by default the free memory, less a margin), `--context` (tokens, 8192), `--mtp` (the model's MTP block, looked for beside it), `--addon` (another `janas.node`, or the `JANAS_NODE` variable). The engine's own variables apply as in Janas's programs (`JANAS_GPU=0`, `JANAS_NPU=0`, `JANAS_PROMPT_ON`, ...).
+
+The model holds one conversation: requests from several pages wait in line, and the page says how many are before its own.
+
+## The module in a few lines
+
+```ts
+import { createRequire } from "node:module";
+import type * as Janas from "../../src/node/janas.js";
+
+const janas = createRequire(import.meta.url)("./janas.node") as typeof Janas;
+const model = await janas.open("qwen3-4b-q4km.jns");
+const chat = await model.chat({ thinking: false });
+for await (const piece of chat.send("Explain how bread is made at home."))
+ if (piece.type === "text") process.stdout.write(piece.text);
+await model.close();
+```
diff --git a/examples/node-chat/package-lock.json b/examples/node-chat/package-lock.json
new file mode 100644
index 0000000..f59a415
--- /dev/null
+++ b/examples/node-chat/package-lock.json
@@ -0,0 +1,389 @@
+{
+ "name": "janas-chat-demo",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "janas-chat-demo",
+ "version": "0.1.0",
+ "license": "GPL-3.0-or-later",
+ "devDependencies": {
+ "@types/node": "^20.19.43",
+ "typescript": "^7.0.2"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "20.19.43",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",
+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",
+ "dev": true,
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+ "dev": true,
+ "bin": {
+ "tsc": "bin/tsc"
+ },
+ "engines": {
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true
+ }
+ }
+}
diff --git a/examples/node-chat/package.json b/examples/node-chat/package.json
new file mode 100644
index 0000000..20cb137
--- /dev/null
+++ b/examples/node-chat/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "janas-chat-demo",
+ "private": true,
+ "version": "0.1.0",
+ "description": "A chat in TypeScript on Janas-LLM inside Node.js: the model in the server's process, its replies streamed to the browser",
+ "license": "GPL-3.0-or-later",
+ "type": "module",
+ "engines": {
+ "node": ">=20"
+ },
+ "scripts": {
+ "build": "tsc -p tsconfig.server.json && tsc -p tsconfig.web.json",
+ "check": "tsc -p tsconfig.server.json --noEmit && tsc -p tsconfig.web.json --noEmit",
+ "start": "node dist/node/server/main.js"
+ },
+ "devDependencies": {
+ "@types/node": "^20.19.43",
+ "typescript": "^7.0.2"
+ }
+}
diff --git a/examples/node-chat/public/index.html b/examples/node-chat/public/index.html
new file mode 100644
index 0000000..4a8d72f
--- /dev/null
+++ b/examples/node-chat/public/index.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<!-- SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri -->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Janas-LLM in Node.js</title>
+<link rel="stylesheet" href="/style.css">
+<script type="module" src="/app/web/app.js"></script>
+</head>
+<body>
+<header>
+ <div class="brand">
+ <span class="logo">J</span>
+ <div>
+ <div id="model-name" class="name">…</div>
+ <div id="model-desc" class="desc">the model is opening</div>
+ </div>
+ </div>
+ <button id="new" type="button" class="ghost">New chat</button>
+</header>
+
+<main id="log" aria-live="polite"></main>
+
+<footer>
+ <details id="settings">
+ <summary>Settings</summary>
+ <label for="system">System message</label>
+ <textarea id="system" rows="3"></textarea>
+ <div class="row">
+ <label id="thinking-row" hidden><input id="thinking" type="checkbox"> reasoning before the answer</label>
+ <label>temperature
+ <input id="temperature" type="range" min="0" max="1.5" step="0.1" value="0.7">
+ <output id="temperature-value"></output>
+ </label>
+ </div>
+ </details>
+ <div class="composer">
+ <textarea id="input" rows="2" placeholder="Write a message (Enter sends, Shift+Enter a new line)"></textarea>
+ <button id="send" type="button">Send</button>
+ <button id="stop" type="button" class="ghost" hidden>Stop</button>
+ </div>
+ <div id="versions" class="versions"></div>
+</footer>
+</body>
+</html>
diff --git a/examples/node-chat/public/style.css b/examples/node-chat/public/style.css
new file mode 100644
index 0000000..99e504e
--- /dev/null
+++ b/examples/node-chat/public/style.css
@@ -0,0 +1,130 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+:root {
+ --bg: #f7f7f5;
+ --panel: #ffffff;
+ --text: #1d1d1f;
+ --muted: #6b6b70;
+ --line: #e2e2e0;
+ --accent: #c2410c;
+ --accent-text: #ffffff;
+ --user: #fff1e8;
+ --code: #f1f1ef;
+ --error: #b91c1c;
+ color-scheme: light dark;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #141416;
+ --panel: #1d1d20;
+ --text: #ececee;
+ --muted: #9a9aa2;
+ --line: #2e2e33;
+ --accent: #f97316;
+ --accent-text: #141416;
+ --user: #2a1d14;
+ --code: #26262b;
+ --error: #f87171;
+ }
+}
+* { box-sizing: border-box; }
+html, body { height: 100%; margin: 0; }
+body {
+ display: flex;
+ flex-direction: column;
+ background: var(--bg);
+ color: var(--text);
+ font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
+}
+header, footer {
+ background: var(--panel);
+ border-color: var(--line);
+ padding: 10px 16px;
+}
+header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ border-bottom: 1px solid var(--line);
+}
+.brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
+.logo {
+ flex: none;
+ display: grid;
+ place-items: center;
+ width: 36px;
+ height: 36px;
+ border-radius: 10px;
+ background: var(--accent);
+ color: var(--accent-text);
+ font-weight: 700;
+}
+.name { font-weight: 600; }
+.desc, .versions, .meta { color: var(--muted); font-size: 13px; }
+.desc { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+main {
+ flex: 1;
+ overflow-y: auto;
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.message { max-width: 760px; width: 100%; margin: 0 auto; }
+.message.user {
+ background: var(--user);
+ border-radius: 14px;
+ padding: 10px 14px;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.message.user.unanswered { opacity: 0.6; }
+.answer p { margin: 0 0 0.6em; }
+.answer pre {
+ background: var(--code);
+ border-radius: 8px;
+ padding: 10px 12px;
+ overflow-x: auto;
+ font-size: 14px;
+}
+.answer code { font-family: ui-monospace, "Cascadia Code", Menlo, monospace; }
+.answer p code { background: var(--code); border-radius: 4px; padding: 0 4px; }
+.reasoning { color: var(--muted); font-size: 14px; margin-bottom: 6px; }
+.reasoning summary { cursor: pointer; }
+.reasoning-text { white-space: pre-wrap; border-left: 2px solid var(--line); padding-left: 10px; }
+.meta.error { color: var(--error); }
+footer { border-top: 1px solid var(--line); }
+.composer { display: flex; gap: 8px; max-width: 760px; margin: 8px auto 4px; }
+textarea {
+ width: 100%;
+ resize: vertical;
+ font: inherit;
+ color: var(--text);
+ background: var(--bg);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 8px 10px;
+}
+button {
+ font: inherit;
+ border: 0;
+ border-radius: 10px;
+ padding: 8px 16px;
+ background: var(--accent);
+ color: var(--accent-text);
+ cursor: pointer;
+}
+button.ghost { background: transparent; color: var(--text); border: 1px solid var(--line); }
+button:disabled { opacity: 0.5; cursor: default; }
+#settings { max-width: 760px; margin: 0 auto; font-size: 14px; }
+#settings summary { cursor: pointer; color: var(--muted); }
+#settings label { display: block; margin: 6px 0 2px; }
+.row { display: flex; flex-wrap: wrap; gap: 4px 24px; align-items: center; }
+.versions { max-width: 760px; margin: 0 auto; }
+@media (max-width: 520px) {
+ .composer { flex-wrap: wrap; }
+ .composer button { flex: 1; }
+ header { padding: 8px 12px; }
+ main { padding: 12px; }
+}
diff --git a/examples/node-chat/src/server/janas.ts b/examples/node-chat/src/server/janas.ts
new file mode 100644
index 0000000..ae23941
--- /dev/null
+++ b/examples/node-chat/src/server/janas.ts
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// Janas-LLM in this process: janas.node, the module build.sh makes beside
+// Janas's programs, with the types of its janas.d.ts. A native module is
+// loaded with require, here through createRequire.
+
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+import type * as Janas from "../../../../src/node/janas.js";
+
+export type { Chat, Model, Piece, Reply, ReplyStats } from "../../../../src/node/janas.js";
+
+/** the module: the path given, JANAS_NODE, or the build's own */
+export function loadJanas(path?: string): typeof Janas {
+ const where =
+ path ??
+ process.env["JANAS_NODE"] ??
+ fileURLToPath(new URL("../../../../../bin/x86_64-linux/janas.node", import.meta.url));
+ return createRequire(import.meta.url)(where) as typeof Janas;
+}
diff --git a/examples/node-chat/src/server/line.ts b/examples/node-chat/src/server/line.ts
new file mode 100644
index 0000000..283d8df
--- /dev/null
+++ b/examples/node-chat/src/server/line.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// One reply at a time, in the order asked: the model holds one
+// conversation. The engine keeps its own order too; the line here makes a
+// request's parameters and its reply one step, and says how many wait.
+
+export class Line {
+ private tail: Promise<void> = Promise.resolve();
+ private count = 0;
+
+ /** requests waiting or running */
+ get length(): number {
+ return this.count;
+ }
+
+ async run<T>(job: () => Promise<T>): Promise<T> {
+ this.count++;
+ const before = this.tail;
+ let done!: () => void;
+ this.tail = new Promise<void>((resolve) => (done = resolve));
+ try {
+ await before;
+ return await job();
+ } finally {
+ this.count--;
+ done();
+ }
+ }
+}
diff --git a/examples/node-chat/src/server/main.ts b/examples/node-chat/src/server/main.ts
new file mode 100644
index 0000000..a7298db
--- /dev/null
+++ b/examples/node-chat/src/server/main.ts
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// The chat's server: the model opened inside this process with janas.node,
+// the page and its scripts served, and each reply streamed to the browser
+// as it is written (server-sent events). The page keeps the conversation and
+// sends it whole; the engine reads again only what is new.
+//
+// npm start -- --model path/to/model.jns [--port 8090] [--host 127.0.0.1]
+// [--cache GiB] [--context tokens] [--mtp] [--addon janas.node]
+
+import http from "node:http";
+import { readFile } from "node:fs/promises";
+import { extname, join, normalize, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+
+import { parseChatRequest, type ModelInfo, type ReplyCost, type StreamEvent } from "../shared/protocol.js";
+import { encodeEvent } from "../shared/sse.js";
+import { loadJanas, type ReplyStats } from "./janas.js";
+import { Line } from "./line.js";
+
+const { values: args } = parseArgs({
+ options: {
+ model: { type: "string" },
+ port: { type: "string", default: "8090" },
+ host: { type: "string", default: "127.0.0.1" },
+ cache: { type: "string" },
+ context: { type: "string", default: "8192" },
+ mtp: { type: "boolean", default: false },
+ addon: { type: "string" },
+ },
+});
+if (!args.model) {
+ console.error(
+ "usage: npm start -- --model path/to/model.jns [--port 8090] [--host 127.0.0.1]\n" +
+ " [--cache GiB] [--context tokens] [--mtp] [--addon janas.node]",
+ );
+ process.exit(2);
+}
+
+const janas = loadJanas(args.addon);
+console.log(`Janas ${janas.version}, Node ${process.version}: opening ${args.model}`);
+const opened = performance.now();
+const model = await janas.open(args.model, {
+ context: Number(args.context),
+ mtp: args.mtp,
+ ...(args.cache !== undefined ? { cacheGiB: Number(args.cache) } : {}),
+});
+console.log(`${model.name || model.path}: ${model.description}, open in ${seconds(performance.now() - opened)} s`);
+const chat = await model.chat({ keep: 4 });
+const line = new Line();
+let applied: { thinking: boolean | null; temperature: number } | null = null;
+
+const root = fileURLToPath(new URL("../../../", import.meta.url));
+const info: ModelInfo = {
+ name: model.name,
+ description: model.description,
+ reasons: model.reasons,
+ defaultSystem: model.defaultSystem,
+ mtp: model.mtp !== false,
+ janas: janas.version,
+ node: process.version,
+};
+
+function seconds(ms: number): string {
+ return (ms / 1000).toFixed(1);
+}
+
+function cost(s: ReplyStats): ReplyCost {
+ return {
+ finish: s.finish,
+ promptTokens: s.promptTokens,
+ cachedTokens: s.cachedTokens,
+ outputTokens: s.outputTokens,
+ reasoningTokens: s.reasoningTokens,
+ drafted: s.drafted,
+ accepted: s.accepted,
+ firstTokenSeconds: s.firstTokenSeconds,
+ inputSeconds: s.inputSeconds,
+ outputSeconds: s.outputSeconds,
+ totalSeconds: s.totalSeconds,
+ };
+}
+
+const HEADERS = {
+ "Content-Security-Policy": "default-src 'self'; img-src 'self' data:",
+ "X-Content-Type-Options": "nosniff",
+};
+
+function json(res: http.ServerResponse, status: number, body: unknown): void {
+ res.writeHead(status, { ...HEADERS, "Content-Type": "application/json; charset=utf-8" });
+ res.end(JSON.stringify(body));
+}
+
+const TYPES: Record<string, string> = {
+ ".html": "text/html; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".svg": "image/svg+xml",
+};
+
+/** a file of the page, never outside its directory */
+async function file(res: http.ServerResponse, dir: string, name: string): Promise<void> {
+ const base = join(root, dir);
+ const path = normalize(join(base, name));
+ const type = TYPES[extname(path)];
+ if (!path.startsWith(base + sep) || !type) return json(res, 404, { error: "not found" });
+ try {
+ const body = await readFile(path);
+ res.writeHead(200, { ...HEADERS, "Content-Type": type, "Cache-Control": "no-cache" });
+ res.end(body);
+ } catch {
+ json(res, 404, { error: "not found" });
+ }
+}
+
+function body(req: http.IncomingMessage, limit: number): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const parts: Buffer[] = [];
+ let size = 0;
+ req.on("data", (b: Buffer) => {
+ size += b.length;
+ if (size > limit) {
+ reject(new Error(`a request over ${limit} bytes`));
+ req.destroy();
+ } else parts.push(b);
+ });
+ req.on("end", () => resolve(Buffer.concat(parts).toString("utf8")));
+ req.on("error", reject);
+ });
+}
+
+async function reply(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(await body(req, 4 << 20));
+ } catch (e) {
+ return json(res, 400, { error: `not a request: ${(e as Error).message}` });
+ }
+ const request = parseChatRequest(parsed);
+ if (typeof request === "string") return json(res, 400, { error: request });
+
+ res.writeHead(200, {
+ ...HEADERS,
+ "Content-Type": "text/event-stream; charset=utf-8",
+ "Cache-Control": "no-cache",
+ });
+ const gone = new AbortController();
+ res.on("close", () => gone.abort()); // the page stopped it, or went away
+ const send = (e: StreamEvent): void => {
+ if (!res.writableEnded && !res.destroyed) res.write(encodeEvent(e));
+ };
+ if (line.length > 0) send({ type: "queued", ahead: line.length });
+
+ await line.run(async () => {
+ if (gone.signal.aborted) return;
+ const want = {
+ thinking: model.reasons ? (request.options?.thinking ?? false) : null,
+ temperature: request.options?.temperature ?? 0.7,
+ };
+ if (!applied || applied.thinking !== want.thinking || applied.temperature !== want.temperature) {
+ await chat.set(want);
+ applied = want;
+ }
+ const r = chat.load(request.messages, { signal: gone.signal });
+ // the first prompt of a session waits while the NPU is made ready
+ let writing = false;
+ const watch = setInterval(() => {
+ const s = model.status();
+ if (!writing && s.npu.preparing)
+ send({ type: "preparing", done: s.npu.done, total: s.npu.total, seconds: s.npu.seconds });
+ }, 500);
+ try {
+ for await (const piece of r) {
+ if (piece.type === "progress") send(piece);
+ else {
+ writing = true;
+ send({ type: "text", text: piece.text, reasoning: piece.reasoning });
+ }
+ }
+ const c = cost(await r.stats());
+ send({ type: "done", cost: c });
+ const rate = c.outputSeconds > 0 ? (c.outputTokens / c.outputSeconds).toFixed(1) : "-";
+ console.log(
+ `reply: ${c.promptTokens} prompt tokens (${c.cachedTokens} kept), ` +
+ `${c.outputTokens} written at ${rate} tok/s, ${c.finish ?? "-"}`,
+ );
+ } catch (e) {
+ const err = e as { code?: string; message?: string };
+ send({ type: "error", code: err.code ?? "ERROR", message: err.message ?? String(e) });
+ } finally {
+ clearInterval(watch);
+ }
+ });
+ res.end();
+}
+
+async function route(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const path = url.pathname;
+ if (req.method === "POST" && path === "/api/chat") return reply(req, res);
+ if (req.method !== "GET") return json(res, 405, { error: "GET or POST /api/chat" });
+ if (path === "/api/model") return json(res, 200, info);
+ if (path === "/api/status") return json(res, 200, model.status());
+ if (path === "/") return file(res, "public", "index.html");
+ if (path === "/style.css") return file(res, "public", "style.css");
+ if (path.startsWith("/app/")) return file(res, "dist/web", path.slice(5));
+ return json(res, 404, { error: "not found" });
+}
+
+const server = http.createServer((req, res) => {
+ route(req, res).catch((e: unknown) => {
+ console.error(e);
+ if (!res.headersSent) json(res, 500, { error: String(e) });
+ else res.end();
+ });
+});
+server.listen(Number(args.port), args.host, () => console.log(`the chat: http://${args.host}:${args.port}/`));
+
+for (const signal of ["SIGINT", "SIGTERM"] as const)
+ process.on(signal, () => {
+ console.log("closing the model");
+ server.close();
+ model.close().then(() => process.exit(0));
+ });
diff --git a/examples/node-chat/src/shared/protocol.ts b/examples/node-chat/src/shared/protocol.ts
new file mode 100644
index 0000000..c0e1dc6
--- /dev/null
+++ b/examples/node-chat/src/shared/protocol.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// What the server and the page say to each other: the same types on both
+// sides, and the check of a request, which the server runs on what it is
+// sent and the page could run on what it sends.
+
+export type Role = "system" | "user" | "assistant";
+
+export interface Message {
+ role: Role;
+ content: string;
+}
+
+export interface ChatOptions {
+ /** reasoning before the answer, on the models that do it */
+ thinking?: boolean;
+ /** 0: always the most likely token */
+ temperature?: number;
+}
+
+/** POST /api/chat: the whole conversation, the page keeps it */
+export interface ChatRequest {
+ messages: Message[];
+ options?: ChatOptions;
+}
+
+/** GET /api/model */
+export interface ModelInfo {
+ name: string;
+ description: string;
+ reasons: boolean;
+ defaultSystem: string;
+ mtp: boolean;
+ /** the build of Janas, and of Node, the server runs */
+ janas: string;
+ node: string;
+}
+
+/** what a reply cost, from the engine's counters */
+export interface ReplyCost {
+ finish: string | null;
+ promptTokens: number;
+ cachedTokens: number;
+ outputTokens: number;
+ reasoningTokens: number;
+ drafted: number;
+ accepted: number;
+ firstTokenSeconds: number;
+ inputSeconds: number;
+ outputSeconds: number;
+ totalSeconds: number;
+}
+
+/** the reply, as the server streams it (server-sent events) */
+export type StreamEvent =
+ | { type: "queued"; ahead: number }
+ | { type: "preparing"; done: number; total: number; seconds: number }
+ | { type: "progress"; read: number; total: number }
+ | { type: "text"; text: string; reasoning: boolean }
+ | { type: "done"; cost: ReplyCost }
+ | { type: "error"; code: string; message: string };
+
+const ROLES: readonly Role[] = ["system", "user", "assistant"];
+
+/** A request as JSON.parse gave it: the request, or what is wrong with it. */
+export function parseChatRequest(v: unknown): ChatRequest | string {
+ if (typeof v !== "object" || v === null) return "the body must be an object";
+ const { messages, options } = v as { messages?: unknown; options?: unknown };
+ if (!Array.isArray(messages) || messages.length === 0)
+ return "messages must be an array, one message at least";
+ const out: Message[] = [];
+ for (const [i, m] of messages.entries()) {
+ if (typeof m !== "object" || m === null) return `message ${i} is not an object`;
+ const { role, content } = m as { role?: unknown; content?: unknown };
+ if (typeof role !== "string" || !ROLES.includes(role as Role))
+ return `message ${i}: role must be one of ${ROLES.join(", ")}`;
+ if (typeof content !== "string") return `message ${i}: content must be a string`;
+ if (role === "system" && i > 0) return `message ${i}: only the first may be the system's`;
+ out.push({ role: role as Role, content });
+ }
+ if (out[out.length - 1]?.role !== "user") return "the last message must be the user's";
+ const request: ChatRequest = { messages: out };
+ if (options !== undefined) {
+ if (typeof options !== "object" || options === null) return "options must be an object";
+ const { thinking, temperature } = options as { thinking?: unknown; temperature?: unknown };
+ if (thinking !== undefined && typeof thinking !== "boolean") return "options.thinking must be a boolean";
+ if (temperature !== undefined && (typeof temperature !== "number" || !(temperature >= 0 && temperature <= 2)))
+ return "options.temperature must be a number from 0 to 2";
+ request.options = {
+ ...(thinking !== undefined ? { thinking } : {}),
+ ...(temperature !== undefined ? { temperature } : {}),
+ };
+ }
+ return request;
+}
diff --git a/examples/node-chat/src/shared/sse.ts b/examples/node-chat/src/shared/sse.ts
new file mode 100644
index 0000000..8038b4a
--- /dev/null
+++ b/examples/node-chat/src/shared/sse.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// The reply's events on the wire, as server-sent events: the server writes
+// them with encodeEvent, the page reads them back with EventDecoder from
+// the chunks fetch() gives it. One file, both sides.
+
+import type { StreamEvent } from "./protocol.js";
+
+export function encodeEvent(e: StreamEvent): string {
+ return `data: ${JSON.stringify(e)}\n\n`;
+}
+
+export class EventDecoder {
+ private buffer = "";
+
+ /** the events completed by this chunk; comments (": ...") are skipped */
+ push(chunk: string): StreamEvent[] {
+ this.buffer += chunk;
+ const events: StreamEvent[] = [];
+ let end: number;
+ while ((end = this.buffer.indexOf("\n\n")) >= 0) {
+ const block = this.buffer.slice(0, end);
+ this.buffer = this.buffer.slice(end + 2);
+ for (const line of block.split("\n"))
+ if (line.startsWith("data: ")) events.push(JSON.parse(line.slice(6)) as StreamEvent);
+ }
+ return events;
+ }
+}
diff --git a/examples/node-chat/src/web/app.ts b/examples/node-chat/src/web/app.ts
new file mode 100644
index 0000000..23c481c
--- /dev/null
+++ b/examples/node-chat/src/web/app.ts
@@ -0,0 +1,221 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// The chat's page: the conversation kept here and sent whole with each
+// message, the reply read as the server streams it, its reasoning apart, and
+// what it cost under it. The types of what goes to the server and back are
+// the server's own (../shared/).
+
+import type { ChatRequest, Message, ModelInfo, ReplyCost, StreamEvent } from "../shared/protocol.js";
+import { EventDecoder } from "../shared/sse.js";
+import { markdown } from "./markdown.js";
+
+function $<T extends HTMLElement>(id: string): T {
+ const node = document.getElementById(id);
+ if (!node) throw new Error(`the page has no #${id}`);
+ return node as T;
+}
+
+function element<K extends keyof HTMLElementTagNameMap>(tag: K, className: string): HTMLElementTagNameMap[K] {
+ const node = document.createElement(tag);
+ node.className = className;
+ return node;
+}
+
+const log = $<HTMLElement>("log");
+const input = $<HTMLTextAreaElement>("input");
+const sendButton = $<HTMLButtonElement>("send");
+const stopButton = $<HTMLButtonElement>("stop");
+const newButton = $<HTMLButtonElement>("new");
+const system = $<HTMLTextAreaElement>("system");
+const thinking = $<HTMLInputElement>("thinking");
+const thinkingRow = $<HTMLElement>("thinking-row");
+const temperature = $<HTMLInputElement>("temperature");
+const temperatureValue = $<HTMLOutputElement>("temperature-value");
+
+const conversation: Message[] = [];
+let running: AbortController | null = null;
+
+/** a reply on the page, as it comes */
+class ReplyView {
+ readonly box = element("div", "message assistant");
+ private readonly reasoningBox = element("details", "reasoning");
+ private readonly reasoningText = element("div", "reasoning-text");
+ private readonly answerBox = element("div", "answer");
+ private readonly meta = element("div", "meta");
+ reasoning = "";
+ answer = "";
+
+ constructor() {
+ const summary = element("summary", "");
+ summary.textContent = "reasoning";
+ this.reasoningBox.append(summary, this.reasoningText);
+ this.reasoningBox.hidden = true;
+ this.meta.textContent = "…";
+ this.box.append(this.reasoningBox, this.answerBox, this.meta);
+ }
+
+ add(text: string, isReasoning: boolean): void {
+ if (isReasoning) {
+ this.reasoning += text;
+ this.reasoningBox.hidden = false;
+ this.reasoningBox.open = this.answer === "";
+ this.reasoningText.textContent = this.reasoning;
+ } else {
+ if (this.answer === "") this.reasoningBox.open = false;
+ this.answer += text;
+ this.answerBox.innerHTML = markdown(this.answer);
+ }
+ this.meta.textContent = "writing…";
+ }
+
+ status(text: string): void {
+ this.meta.textContent = text;
+ }
+
+ done(cost: ReplyCost): void {
+ this.meta.textContent = describe(cost);
+ }
+
+ fail(text: string): void {
+ this.meta.textContent = text;
+ this.meta.classList.add("error");
+ }
+}
+
+function describe(c: ReplyCost): string {
+ const rate = c.outputSeconds > 0 ? c.outputTokens / c.outputSeconds : 0;
+ const parts = [
+ `${c.outputTokens} tokens at ${rate.toFixed(1)} tok/s`,
+ `the first after ${c.firstTokenSeconds.toFixed(2)} s`,
+ `prompt ${c.promptTokens} tokens, ${c.cachedTokens} of them already read`,
+ ];
+ if (c.reasoningTokens > 0) parts.push(`${c.reasoningTokens} of reasoning`);
+ if (c.drafted > 0) parts.push(`drafts kept ${c.accepted} of ${c.drafted}`);
+ if (c.finish === "stopped") parts.push("stopped");
+ else if (c.finish === "length") parts.push("cut at the limit");
+ return parts.join(" · ");
+}
+
+function scroll(): void {
+ log.scrollTop = log.scrollHeight;
+}
+
+function busy(on: boolean): void {
+ sendButton.disabled = on;
+ newButton.disabled = on;
+ stopButton.hidden = !on;
+}
+
+function show(view: ReplyView, e: StreamEvent): void {
+ switch (e.type) {
+ case "queued":
+ view.status(`waiting: ${e.ahead} before this one`);
+ break;
+ case "preparing":
+ view.status(`preparing the NPU ${e.done}/${e.total}, ${Math.round(e.seconds)} s (once a session)`);
+ break;
+ case "progress":
+ view.status(`reading the prompt: ${e.read} of ${e.total} tokens`);
+ break;
+ case "text":
+ view.add(e.text, e.reasoning);
+ scroll();
+ break;
+ case "done":
+ view.done(e.cost);
+ break;
+ case "error":
+ view.fail(`${e.code}: ${e.message}`);
+ break;
+ default: {
+ const unknown: never = e;
+ return unknown;
+ }
+ }
+}
+
+async function send(): Promise<void> {
+ const text = input.value.trim();
+ if (!text || running) return;
+ input.value = "";
+ conversation.push({ role: "user", content: text });
+ const mine = element("div", "message user");
+ mine.textContent = text;
+ const view = new ReplyView();
+ log.append(mine, view.box);
+ scroll();
+
+ const head: Message[] = system.value.trim() ? [{ role: "system", content: system.value.trim() }] : [];
+ const request: ChatRequest = {
+ messages: [...head, ...conversation],
+ options: { thinking: thinking.checked, temperature: Number(temperature.value) },
+ };
+ const ask = new AbortController();
+ running = ask;
+ busy(true);
+ try {
+ const res = await fetch("/api/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(request),
+ signal: ask.signal,
+ });
+ if (!res.ok || !res.body) {
+ const e = (await res.json().catch(() => ({}))) as { error?: string };
+ throw new Error(e.error ?? `HTTP ${res.status}`);
+ }
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
+ const decoder = new EventDecoder();
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ for (const e of decoder.push(value)) show(view, e);
+ }
+ } catch (e) {
+ if (ask.signal.aborted) view.status(view.answer ? "stopped" : "stopped before the answer");
+ else view.fail(`no reply: ${(e as Error).message}`);
+ } finally {
+ if (view.answer) conversation.push({ role: "assistant", content: view.answer });
+ else {
+ conversation.pop(); // unanswered: it leaves the conversation
+ mine.classList.add("unanswered");
+ }
+ running = null;
+ busy(false);
+ input.focus();
+ }
+}
+
+sendButton.addEventListener("click", () => void send());
+stopButton.addEventListener("click", () => running?.abort());
+newButton.addEventListener("click", () => {
+ conversation.length = 0;
+ log.replaceChildren();
+ input.focus();
+});
+input.addEventListener("keydown", (e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
+ e.preventDefault();
+ void send();
+ }
+});
+temperature.addEventListener("input", () => {
+ temperatureValue.value = temperature.value;
+});
+
+async function start(): Promise<void> {
+ const info = (await (await fetch("/api/model")).json()) as ModelInfo;
+ $("model-name").textContent = info.name || "a model";
+ $("model-desc").textContent = info.description;
+ $("versions").textContent = `Janas ${info.janas} · Node ${info.node}${info.mtp ? " · MTP" : ""}`;
+ system.value = info.defaultSystem;
+ thinkingRow.hidden = !info.reasons;
+ document.title = `${info.name || "Janas"} · Janas-LLM in Node.js`;
+ temperatureValue.value = temperature.value;
+ input.focus();
+}
+
+start().catch((e: unknown) => {
+ $("model-desc").textContent = `the server did not answer: ${(e as Error).message}`;
+});
diff --git a/examples/node-chat/src/web/markdown.ts b/examples/node-chat/src/web/markdown.ts
new file mode 100644
index 0000000..8fe8a2d
--- /dev/null
+++ b/examples/node-chat/src/web/markdown.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+//
+// The few marks a reply uses most, as HTML: fenced code, inline code, bold,
+// paragraphs and line breaks. Everything else stays text: the model's
+// words are escaped first, so nothing it writes becomes markup. A fence not
+// closed yet (a reply still being written) is code to the end.
+
+const ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
+
+function escape(s: string): string {
+ return s.replace(/[&<>"']/g, (c) => ESCAPES[c] ?? c);
+}
+
+function prose(text: string): string {
+ return text
+ .split(/\n{2,}/)
+ .filter((p) => p.trim() !== "")
+ .map((p) => {
+ const html = escape(p.trim())
+ .replace(/`([^`\n]+)`/g, "<code>$1</code>")
+ .replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
+ .replace(/\n/g, "<br>");
+ return `<p>${html}</p>`;
+ })
+ .join("");
+}
+
+export function markdown(text: string): string {
+ return text
+ .split("```")
+ .map((part, i) => {
+ if (i % 2 === 0) return prose(part);
+ const nl = part.indexOf("\n");
+ const code = nl >= 0 ? part.slice(nl + 1) : part;
+ return `<pre><code>${escape(code.replace(/\n$/, ""))}</code></pre>`;
+ })
+ .join("");
+}
diff --git a/examples/node-chat/tsconfig.base.json b/examples/node-chat/tsconfig.base.json
new file mode 100644
index 0000000..5f8e872
--- /dev/null
+++ b/examples/node-chat/tsconfig.base.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "strict": true,
+ "target": "es2022",
+ "noUncheckedIndexedAccess": true,
+ "noImplicitOverride": true,
+ "noFallthroughCasesInSwitch": true,
+ "verbatimModuleSyntax": true,
+ "isolatedModules": true,
+ "forceConsistentCasingInFileNames": true,
+ "skipLibCheck": true,
+ "rootDir": "src"
+ }
+}
diff --git a/examples/node-chat/tsconfig.server.json b/examples/node-chat/tsconfig.server.json
new file mode 100644
index 0000000..33db061
--- /dev/null
+++ b/examples/node-chat/tsconfig.server.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.base.json",
+ "compilerOptions": {
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "lib": ["es2022"],
+ "types": ["node"],
+ "outDir": "dist/node"
+ },
+ "include": ["src/server/**/*.ts", "src/shared/**/*.ts"]
+}
diff --git a/examples/node-chat/tsconfig.web.json b/examples/node-chat/tsconfig.web.json
new file mode 100644
index 0000000..8880d7d
--- /dev/null
+++ b/examples/node-chat/tsconfig.web.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.base.json",
+ "compilerOptions": {
+ "module": "es2022",
+ "moduleResolution": "bundler",
+ "lib": ["es2022", "dom", "dom.iterable"],
+ "types": [],
+ "outDir": "dist/web"
+ },
+ "include": ["src/web/**/*.ts", "src/shared/**/*.ts"]
+}
diff --git a/src/node/addon.c b/src/node/addon.c
new file mode 100644
index 0000000..6d16d30
--- /dev/null
+++ b/src/node/addon.c
@@ -0,0 +1,431 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * addon.c - the module for Node.js, janas.node: what Node calls when it
+ * loads it, the environment of each Node thread that does, and the small
+ * conversions between JavaScript's values and the library's.
+ */
+#include <math.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "node/node_impl.h"
+
+const napi_type_tag janas_node_model_tag = {0x6a616e61736d6f64ull,
+ 0x9c1f3b2a5e7d4c81ull};
+const napi_type_tag janas_node_chat_tag = {0x6a616e6173636874ull,
+ 0x2b8e4f7a1c3d5e90ull};
+const napi_type_tag janas_node_reply_tag = {0x6a616e6173726570ull,
+ 0x7d3a9e1b4c6f2a58ull};
+
+struct janas_node_env *janas_node_env(napi_env env)
+{
+ void *st = NULL;
+ if (napi_get_instance_data(env, &st) != napi_ok)
+ return NULL;
+ return st;
+}
+
+void janas_node_env_unref(struct janas_node_env *st)
+{
+ if (--st->refs == 0)
+ free(st);
+}
+
+/* Node is leaving the environment: the models close first, so that each
+ writes what it learnt, and their threads end */
+static void env_cleanup(void *arg)
+{
+ janas_node_teardown(arg);
+}
+
+static void env_free(napi_env env, void *data, void *hint)
+{
+ (void)env;
+ (void)hint;
+ janas_node_env_unref(data);
+}
+
+napi_value janas_node_undefined(napi_env env)
+{
+ napi_value v = NULL;
+ napi_get_undefined(env, &v);
+ return v;
+}
+
+napi_value janas_node_string(napi_env env, const char *s, size_t len)
+{
+ napi_value v = NULL;
+ if (napi_create_string_utf8(env, s ? s : "", s ? len : 0, &v) != napi_ok)
+ return janas_node_undefined(env);
+ return v;
+}
+
+napi_value janas_node_number(napi_env env, double x)
+{
+ napi_value v = NULL;
+ if (napi_create_double(env, x, &v) != napi_ok)
+ return janas_node_undefined(env);
+ return v;
+}
+
+napi_value janas_node_bool(napi_env env, int b)
+{
+ napi_value v = NULL;
+ napi_get_boolean(env, b != 0, &v);
+ return v;
+}
+
+void janas_node_put(napi_env env, napi_value obj, const char *name,
+ napi_value v)
+{
+ napi_set_named_property(env, obj, name, v);
+}
+
+/* the codes of the library's failures, as Node names a system's (ENOENT):
+ the suffix of JANAS_LLM_E..., in a namespace of their own - not JANAS_,
+ the environment's */
+const char *janas_node_code(int32_t rc)
+{
+ switch (rc) {
+ case JANAS_LLM_EINVAL:
+ return "EINVAL";
+ case JANAS_LLM_ENOMEM:
+ return "ENOMEM";
+ case JANAS_LLM_EOPEN:
+ return "EOPEN";
+ case JANAS_LLM_EMODEL:
+ return "EMODEL";
+ case JANAS_LLM_EFULL:
+ return "EFULL";
+ case JANAS_LLM_EBUSY:
+ return "EBUSY";
+ case JANAS_LLM_ESMALL:
+ return "ESMALL";
+ case JANAS_LLM_ELIMIT:
+ return "ELIMIT";
+ case JANAS_NODE_ECLOSED:
+ return "ECLOSED";
+ default:
+ return "EFAIL";
+ }
+}
+
+napi_value janas_node_error(napi_env env, int32_t rc, const char *msg)
+{
+ napi_value e = NULL;
+ if (!msg || !*msg)
+ msg = "janas: the engine failed, and did not say why";
+ napi_create_error(
+ env,
+ janas_node_string(env, janas_node_code(rc), JANAS_NAPI_AUTO_LENGTH),
+ janas_node_string(env, msg, JANAS_NAPI_AUTO_LENGTH), &e);
+ return e;
+}
+
+napi_value janas_node_throw(napi_env env, int32_t rc, const char *msg)
+{
+ napi_throw_error(env, janas_node_code(rc), msg);
+ return NULL;
+}
+
+napi_value janas_node_type_error(napi_env env, const char *fmt, ...)
+{
+ char buf[1024];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof(buf), fmt, ap);
+ va_end(ap);
+ napi_throw_type_error(env, NULL, buf);
+ return NULL;
+}
+
+napi_value janas_node_promise(napi_env env, napi_deferred *d)
+{
+ napi_value p = NULL;
+ if (napi_create_promise(env, d, &p) != napi_ok) {
+ *d = NULL;
+ return NULL;
+ }
+ return p;
+}
+
+napi_value janas_node_resolved(napi_env env, napi_value v)
+{
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p)
+ napi_resolve_deferred(env, d, v ? v : janas_node_undefined(env));
+ return p;
+}
+
+napi_value janas_node_rejected(napi_env env, napi_value err)
+{
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p)
+ napi_reject_deferred(env, d, err ? err : janas_node_undefined(env));
+ return p;
+}
+
+napi_value janas_node_new(napi_env env, napi_ref cls, const napi_type_tag *tag,
+ void *native, napi_finalize fin)
+{
+ struct janas_node_env *st = janas_node_env(env);
+ napi_value ctor, obj = NULL;
+ if (!st || napi_get_reference_value(env, cls, &ctor) != napi_ok)
+ return NULL;
+ st->constructing = 1;
+ napi_status s = napi_new_instance(env, ctor, 0, NULL, &obj);
+ st->constructing = 0;
+ if (s != napi_ok || napi_type_tag_object(env, obj, tag) != napi_ok ||
+ napi_wrap(env, obj, native, fin, NULL, NULL) != napi_ok)
+ return NULL;
+ return obj;
+}
+
+napi_value janas_node_constructor(napi_env env, napi_callback_info info)
+{
+ struct janas_node_env *st = janas_node_env(env);
+ napi_value self = NULL;
+ void *where = NULL;
+ napi_get_cb_info(env, info, NULL, NULL, &self, &where);
+ if (!st || !st->constructing)
+ return janas_node_type_error(env, "janas: %s",
+ where ? (const char *)where
+ : "not made with new");
+ return self;
+}
+
+void *janas_node_self(napi_env env, napi_callback_info info,
+ const napi_type_tag *tag, size_t *argc, napi_value *argv,
+ const char *what)
+{
+ napi_value self = NULL;
+ void *native = NULL;
+ size_t none = 0;
+ bool ours = false;
+ if (napi_get_cb_info(env, info, argc ? argc : &none, argv, &self, NULL) !=
+ napi_ok ||
+ napi_check_object_type_tag(env, self, tag, &ours) != napi_ok || !ours ||
+ napi_unwrap(env, self, &native) != napi_ok || !native) {
+ janas_node_type_error(env, "janas: %s called on another object", what);
+ return NULL;
+ }
+ return native;
+}
+
+char *janas_node_text(napi_env env, napi_value v, size_t *len)
+{
+ napi_valuetype t;
+ size_t n = 0;
+ *len = 0;
+ if (!v || napi_typeof(env, v, &t) != napi_ok || t != napi_string ||
+ napi_get_value_string_utf8(env, v, NULL, 0, &n) != napi_ok)
+ return NULL;
+ char *s = malloc(n + 1);
+ if (!s) {
+ *len = SIZE_MAX;
+ return NULL;
+ }
+ if (napi_get_value_string_utf8(env, v, s, n + 1, &n) != napi_ok) {
+ free(s);
+ return NULL;
+ }
+ *len = n;
+ return s;
+}
+
+int janas_node_options(napi_env env, napi_value obj, const char *what,
+ const char *const *known)
+{
+ napi_valuetype t;
+ if (!obj || napi_typeof(env, obj, &t) != napi_ok || t == napi_undefined ||
+ t == napi_null)
+ return 0;
+ if (t != napi_object) {
+ janas_node_type_error(env, "janas: %s: the options must be an object",
+ what);
+ return -1;
+ }
+ napi_value names;
+ uint32_t n = 0;
+ if (napi_get_property_names(env, obj, &names) != napi_ok ||
+ napi_get_array_length(env, names, &n) != napi_ok)
+ return 0;
+ for (uint32_t i = 0; i < n; i++) {
+ napi_value k;
+ char name[64];
+ size_t len = 0;
+ if (napi_get_element(env, names, i, &k) != napi_ok ||
+ napi_get_value_string_utf8(env, k, name, sizeof(name), &len) !=
+ napi_ok)
+ continue;
+ const char *const *p = known;
+ while (*p && strcmp(*p, name))
+ p++;
+ if (*p)
+ continue;
+ char list[512];
+ size_t at = 0;
+ list[0] = 0;
+ for (p = known; *p && at < sizeof(list); p++) {
+ int w = snprintf(list + at, sizeof(list) - at, "%s%s",
+ p == known ? "" : ", ", *p);
+ at += w > 0 ? (size_t)w : 0;
+ }
+ janas_node_type_error(env, "janas: %s: no option '%s' (there are %s)",
+ what, name, list);
+ return -1;
+ }
+ return 0;
+}
+
+static const char *type_name(napi_valuetype type)
+{
+ switch (type) {
+ case napi_number:
+ return "a number";
+ case napi_boolean:
+ return "a boolean";
+ case napi_string:
+ return "a string";
+ default:
+ return "an object";
+ }
+}
+
+int janas_node_opt(napi_env env, napi_value obj, const char *what,
+ const char *name, napi_valuetype type, napi_value *v)
+{
+ napi_valuetype t;
+ if (!obj || napi_typeof(env, obj, &t) != napi_ok || t != napi_object ||
+ napi_get_named_property(env, obj, name, v) != napi_ok ||
+ napi_typeof(env, *v, &t) != napi_ok || t == napi_undefined)
+ return 0;
+ if (t != type) {
+ janas_node_type_error(env, "janas: %s: %s must be %s", what, name,
+ type_name(type));
+ return -1;
+ }
+ return 1;
+}
+
+int janas_node_opt_number(napi_env env, napi_value obj, const char *what,
+ const char *name, double lo, double hi, double *out)
+{
+ napi_value v;
+ int r = janas_node_opt(env, obj, what, name, napi_number, &v);
+ if (r <= 0)
+ return r;
+ double x = 0;
+ napi_get_value_double(env, v, &x);
+ if (!isfinite(x) || x < lo || x > hi) {
+ janas_node_type_error(env, "janas: %s: %s must be from %g to %g", what,
+ name, lo, hi);
+ return -1;
+ }
+ *out = x;
+ return 1;
+}
+
+int janas_node_opt_int(napi_env env, napi_value obj, const char *what,
+ const char *name, int64_t lo, int64_t hi, int64_t *out)
+{
+ double x;
+ int r =
+ janas_node_opt_number(env, obj, what, name, (double)lo, (double)hi, &x);
+ if (r <= 0)
+ return r;
+ if (x != floor(x)) {
+ janas_node_type_error(env, "janas: %s: %s must be a whole number", what,
+ name);
+ return -1;
+ }
+ *out = (int64_t)x;
+ return 1;
+}
+
+int janas_node_opt_bool(napi_env env, napi_value obj, const char *what,
+ const char *name, int *out)
+{
+ napi_value v;
+ int r = janas_node_opt(env, obj, what, name, napi_boolean, &v);
+ if (r <= 0)
+ return r;
+ bool b = false;
+ napi_get_value_bool(env, v, &b);
+ *out = b;
+ return 1;
+}
+
+int janas_node_opt_string(napi_env env, napi_value obj, const char *what,
+ const char *name, char **out)
+{
+ napi_value v;
+ int r = janas_node_opt(env, obj, what, name, napi_string, &v);
+ if (r <= 0)
+ return r;
+ size_t len;
+ *out = janas_node_text(env, v, &len);
+ if (!*out) {
+ janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ return -1;
+ }
+ return 1;
+}
+
+static napi_value abi_version(napi_env env, napi_callback_info info)
+{
+ (void)info;
+ return janas_node_number(env, janas_llm_abi_version());
+}
+
+static int keep_class(napi_env env, napi_value cls, napi_ref *ref)
+{
+ return cls && napi_create_reference(env, cls, 1, ref) == napi_ok;
+}
+
+/* What Node calls when it loads the module, once in each environment. */
+__attribute__((visibility("default"))) napi_value
+napi_register_module_v1(napi_env env, napi_value exports)
+{
+ struct janas_node_env *st = calloc(1, sizeof(*st));
+ if (!st)
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ st->refs = 1;
+ if (napi_set_instance_data(env, st, env_free, NULL) != napi_ok) {
+ free(st);
+ return janas_node_throw(env, JANAS_LLM_EFAIL,
+ "janas: the module cannot keep its data");
+ }
+ napi_value model = janas_node_model_class(env);
+ napi_value chat = janas_node_chat_class(env);
+ napi_value reply = janas_node_reply_class(env);
+ if (!keep_class(env, model, &st->model_class) ||
+ !keep_class(env, chat, &st->chat_class) ||
+ !keep_class(env, reply, &st->reply_class) ||
+ napi_add_env_cleanup_hook(env, env_cleanup, st) != napi_ok)
+ return janas_node_throw(env, JANAS_LLM_EFAIL,
+ "janas: the module cannot define its classes");
+ napi_property_descriptor d[] = {
+ {.utf8name = "open",
+ .method = janas_node_open,
+ .attributes = napi_enumerable},
+ {.utf8name = "abiVersion",
+ .method = abi_version,
+ .attributes = napi_enumerable},
+ {.utf8name = "version",
+ .value = janas_node_string(env, JANAS_VERSION, JANAS_NAPI_AUTO_LENGTH),
+ .attributes = napi_enumerable},
+ {.utf8name = "Model", .value = model, .attributes = napi_enumerable},
+ {.utf8name = "Chat", .value = chat, .attributes = napi_enumerable},
+ {.utf8name = "Reply", .value = reply, .attributes = napi_enumerable},
+ };
+ if (napi_define_properties(env, exports, sizeof(d) / sizeof(d[0]), d) !=
+ napi_ok)
+ return NULL;
+ return exports;
+}
diff --git a/src/node/chat.c b/src/node/chat.c
new file mode 100644
index 0000000..ffad4ca
--- /dev/null
+++ b/src/node/chat.c
@@ -0,0 +1,417 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * chat.c - the Chat class: a model's conversation (one at a time per model,
+ * as the library has it), its parameters, its system message, a reset, and
+ * the replies it asks for (reply.c).
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "node/node_impl.h"
+
+struct chat_job {
+ struct janas_node_chat *c; /* the chat's object owns it once made */
+ struct janas_llm_chat_params p;
+ char *system;
+ size_t system_len;
+ int32_t keep;
+ int has_keep;
+ int made; /* the engine made the chat (set on its thread) */
+};
+
+static void chat_job_drop(void *data)
+{
+ struct chat_job *cj = data;
+ if (!cj)
+ return;
+ free(cj->c);
+ free(cj->system);
+ free(cj);
+}
+
+static const char *const chat_known[] = {"system",
+ "temperature",
+ "topK",
+ "topP",
+ "minP",
+ "seed",
+ "speculate",
+ "maxReply",
+ "maxAnswer",
+ "maxReasoning",
+ "maxInput",
+ "thinking",
+ "recap",
+ "presencePenalty",
+ "frequencyPenalty",
+ "keep",
+ NULL};
+
+/* the options of model.chat() and chat.set() over cj->p */
+static int chat_options(napi_env env, napi_value o, const char *w,
+ struct chat_job *cj)
+{
+ struct janas_llm_chat_params *p = &cj->p;
+ double d;
+ int64_t i;
+ int b, r;
+ if (janas_node_options(env, o, w, chat_known) < 0)
+ return -1;
+#define NUMBER(name, field, lo, hi) \
+ if ((r = janas_node_opt_number(env, o, w, name, lo, hi, &d)) < 0) \
+ return -1; \
+ if (r) \
+ p->field = (float)d;
+#define WHOLE(name, field, type, lo, hi) \
+ if ((r = janas_node_opt_int(env, o, w, name, lo, hi, &i)) < 0) \
+ return -1; \
+ if (r) \
+ p->field = (type)i;
+ NUMBER("temperature", temperature, 0, 100)
+ NUMBER("topP", top_p, 0, 1)
+ NUMBER("minP", min_p, 0, 1)
+ NUMBER("presencePenalty", presence_penalty, -2, 2)
+ NUMBER("frequencyPenalty", frequency_penalty, -2, 2)
+ WHOLE("topK", top_k, int32_t, 0, INT32_MAX)
+ WHOLE("seed", seed, uint64_t, 0, 9007199254740991LL)
+ WHOLE("maxReply", max_reply, int32_t, 0, INT32_MAX)
+ WHOLE("maxAnswer", max_answer, int32_t, 0, INT32_MAX)
+ WHOLE("maxReasoning", max_reasoning, int32_t, 0, INT32_MAX)
+ WHOLE("maxInput", max_input, uint32_t, 0, UINT32_MAX)
+#undef NUMBER
+#undef WHOLE
+ if ((r = janas_node_opt_bool(env, o, w, "speculate", &b)) < 0)
+ return -1;
+ if (r)
+ p->speculate = b;
+ if ((r = janas_node_opt_bool(env, o, w, "recap", &b)) < 0)
+ return -1;
+ if (r)
+ p->recap = b;
+ /* thinking: true, false, or null for the model's own way */
+ napi_value v;
+ napi_valuetype t;
+ if (o && napi_typeof(env, o, &t) == napi_ok && t == napi_object &&
+ napi_get_named_property(env, o, "thinking", &v) == napi_ok &&
+ napi_typeof(env, v, &t) == napi_ok && t == napi_null)
+ p->thinking = -1;
+ else if ((r = janas_node_opt_bool(env, o, w, "thinking", &b)) < 0)
+ return -1;
+ else if (r)
+ p->thinking = b;
+ if ((r = janas_node_opt(env, o, w, "system", napi_string, &v)) < 0)
+ return -1;
+ if (r) {
+ cj->system = janas_node_text(env, v, &cj->system_len);
+ if (!cj->system) {
+ janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ return -1;
+ }
+ }
+ if ((r = janas_node_opt_int(env, o, w, "keep", 0, 64, &i)) < 0)
+ return -1;
+ if (r) {
+ cj->keep = (int32_t)i;
+ cj->has_keep = 1;
+ }
+ return 0;
+}
+
+static void failed(struct janas_node_job *j)
+{
+ snprintf(j->error, sizeof(j->error), "%s", janas_llm_last_error());
+}
+
+/* the system message and the conversations kept, after the parameters */
+static void chat_extras(struct janas_node_job *j, struct chat_job *cj)
+{
+ janas_llm_chat *c = j->m->chat;
+ if (j->rc == JANAS_LLM_OK && cj->system)
+ j->rc = janas_llm_chat_system(c, cj->system, (int32_t)cj->system_len);
+ if (j->rc == JANAS_LLM_OK && cj->has_keep)
+ j->rc = janas_llm_chat_keep(c, cj->keep, 0);
+ if (j->rc != JANAS_LLM_OK)
+ failed(j);
+}
+
+static void chat_run(struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ struct chat_job *cj = j->data;
+ j->rc = janas_llm_chat_create(m->llm, &cj->p, &m->chat);
+ if (j->rc != JANAS_LLM_OK) {
+ failed(j);
+ m->chat = NULL;
+ return;
+ }
+ chat_extras(j, cj);
+ if (j->rc != JANAS_LLM_OK) {
+ janas_llm_chat_destroy(m->chat);
+ m->chat = NULL;
+ } else
+ cj->made = 1;
+}
+
+static void destroy_run(struct janas_node_job *j)
+{
+ if (j->m->chat) {
+ janas_llm_chat_destroy(j->m->chat);
+ j->m->chat = NULL;
+ }
+}
+
+/* the chat ends: its replies stop, and the engine destroys it after them */
+static void chat_end(napi_env env, struct janas_node_chat *c, napi_deferred d)
+{
+ struct janas_node_model *m = c->m;
+ c->closed = 1;
+ if (m->closing || !m->engine || m->st->teardown) {
+ if (d)
+ napi_resolve_deferred(env, d, janas_node_undefined(env));
+ return;
+ }
+ m->has_chat = 0;
+ janas_node_stop_replies(m);
+ struct janas_node_job *j = janas_node_job(m, destroy_run);
+ if (!j) { /* the model's close destroys it then */
+ if (d)
+ napi_reject_deferred(env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM,
+ "janas: out of memory"));
+ return;
+ }
+ j->deferred = d;
+ janas_node_post(env, j);
+}
+
+static void chat_finalize(napi_env env, void *data, void *hint)
+{
+ (void)hint;
+ struct janas_node_chat *c = data;
+ struct janas_node_model *m = c->m;
+ if (!c->closed)
+ chat_end(env, c, NULL);
+ free(c);
+ janas_node_release(env, m);
+}
+
+static napi_value chat_value(napi_env env, struct janas_node_job *j)
+{
+ struct chat_job *cj = j->data;
+ napi_value obj = janas_node_new(env, j->m->st->chat_class,
+ &janas_node_chat_tag, cj->c, chat_finalize);
+ if (!obj)
+ return NULL;
+ cj->c = NULL; /* the object's now */
+ janas_node_hold(j->m);
+ return obj;
+}
+
+static void chat_after(napi_env env, struct janas_node_job *j)
+{
+ struct chat_job *cj = j->data;
+ struct janas_node_model *m = j->m;
+ if (!cj->c)
+ return; /* made */
+ /* not made, here or in the engine: the model is free for another, and
+ a chat the engine made for nobody is destroyed */
+ if (m->has_chat && !m->closing)
+ m->has_chat = 0;
+ if (cj->made && !m->closing) {
+ struct janas_node_job *d = janas_node_job(m, destroy_run);
+ if (d)
+ janas_node_post(env, d);
+ }
+}
+
+static napi_value closed(napi_env env, int promise, const char *what)
+{
+ char msg[160];
+ snprintf(msg, sizeof(msg), "janas: %s: the chat is closed", what);
+ if (!promise)
+ return janas_node_throw(env, JANAS_NODE_ECLOSED, msg);
+ return janas_node_rejected(env,
+ janas_node_error(env, JANAS_NODE_ECLOSED, msg));
+}
+
+napi_value janas_node_chat(napi_env env, struct janas_node_model *m,
+ napi_value options)
+{
+ if (m->closing)
+ return janas_node_rejected(
+ env, janas_node_error(env, JANAS_NODE_ECLOSED,
+ "janas: model.chat: the model is closed"));
+ if (m->has_chat)
+ return janas_node_rejected(
+ env, janas_node_error(env, JANAS_LLM_EBUSY,
+ "janas: model.chat: the model has a chat "
+ "already, and holds one at a time: close "
+ "it first"));
+ struct chat_job *cj = calloc(1, sizeof(*cj));
+ if (!cj)
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ janas_llm_chat_params_default(&cj->p);
+ if (chat_options(env, options, "model.chat", cj) < 0) {
+ chat_job_drop(cj);
+ return NULL;
+ }
+ cj->c = calloc(1, sizeof(*cj->c));
+ struct janas_node_job *j = cj->c ? janas_node_job(m, chat_run) : NULL;
+ napi_value p = j ? janas_node_promise(env, &j->deferred) : NULL;
+ if (!p) {
+ chat_job_drop(cj);
+ free(j);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ }
+ cj->c->m = m;
+ cj->c->p = cj->p;
+ j->data = cj;
+ j->drop = chat_job_drop;
+ j->value = chat_value;
+ j->after = chat_after;
+ m->has_chat = 1;
+ janas_node_post(env, j);
+ return p;
+}
+
+static void set_run(struct janas_node_job *j)
+{
+ struct chat_job *cj = j->data;
+ janas_llm_chat *c = j->m->chat;
+ if (!c) {
+ j->rc = JANAS_NODE_ECLOSED;
+ snprintf(j->error, sizeof(j->error), "janas: the chat is closed");
+ return;
+ }
+ j->rc = janas_llm_chat_set_params(c, &cj->p);
+ if (j->rc != JANAS_LLM_OK)
+ failed(j);
+ chat_extras(j, cj);
+}
+
+static napi_value chat_set(napi_env env, napi_callback_info info)
+{
+ size_t argc = 1;
+ napi_value argv[1] = {NULL};
+ struct janas_node_chat *c = janas_node_self(env, info, &janas_node_chat_tag,
+ &argc, argv, "Chat.set");
+ if (!c)
+ return NULL;
+ if (c->closed || c->m->closing)
+ return closed(env, 1, "chat.set");
+ struct chat_job *cj = calloc(1, sizeof(*cj));
+ if (!cj)
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ cj->p = c->p;
+ if (chat_options(env, argc ? argv[0] : NULL, "chat.set", cj) < 0) {
+ chat_job_drop(cj);
+ return NULL;
+ }
+ struct janas_node_job *j = janas_node_job(c->m, set_run);
+ napi_value p = j ? janas_node_promise(env, &j->deferred) : NULL;
+ if (!p) {
+ chat_job_drop(cj);
+ free(j);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ }
+ /* the next set() starts from these, whatever the engine makes of them:
+ the whole parameters go every time */
+ c->p = cj->p;
+ j->data = cj;
+ j->drop = chat_job_drop;
+ janas_node_post(env, j);
+ return p;
+}
+
+static void reset_run(struct janas_node_job *j)
+{
+ janas_llm_chat *c = j->m->chat;
+ if (!c) {
+ j->rc = JANAS_NODE_ECLOSED;
+ snprintf(j->error, sizeof(j->error), "janas: the chat is closed");
+ return;
+ }
+ j->rc = janas_llm_chat_reset(c);
+ if (j->rc != JANAS_LLM_OK)
+ failed(j);
+}
+
+static napi_value chat_reset(napi_env env, napi_callback_info info)
+{
+ struct janas_node_chat *c = janas_node_self(env, info, &janas_node_chat_tag,
+ NULL, NULL, "Chat.reset");
+ if (!c)
+ return NULL;
+ if (c->closed || c->m->closing)
+ return closed(env, 1, "chat.reset");
+ struct janas_node_job *j = janas_node_job(c->m, reset_run);
+ napi_value p = j ? janas_node_promise(env, &j->deferred) : NULL;
+ if (!p) {
+ free(j);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ }
+ janas_node_post(env, j);
+ return p;
+}
+
+static napi_value chat_close(napi_env env, napi_callback_info info)
+{
+ struct janas_node_chat *c = janas_node_self(env, info, &janas_node_chat_tag,
+ NULL, NULL, "Chat.close");
+ if (!c)
+ return NULL;
+ if (c->closed)
+ return janas_node_resolved(env, NULL);
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p)
+ chat_end(env, c, d);
+ return p;
+}
+
+static napi_value chat_reply(napi_env env, napi_callback_info info, int load)
+{
+ size_t argc = 2;
+ napi_value argv[2] = {NULL, NULL}, self = NULL;
+ const char *what = load ? "Chat.load" : "Chat.send";
+ struct janas_node_chat *c =
+ janas_node_self(env, info, &janas_node_chat_tag, &argc, argv, what);
+ if (!c)
+ return NULL;
+ if (c->closed || c->m->closing)
+ return closed(env, 0, load ? "chat.load" : "chat.send");
+ napi_get_cb_info(env, info, NULL, NULL, &self, NULL);
+ return janas_node_reply(env, c, self, load, argc ? argv[0] : NULL,
+ argc > 1 ? argv[1] : NULL);
+}
+
+static napi_value chat_send(napi_env env, napi_callback_info info)
+{
+ return chat_reply(env, info, 0);
+}
+
+static napi_value chat_load(napi_env env, napi_callback_info info)
+{
+ return chat_reply(env, info, 1);
+}
+
+napi_value janas_node_chat_class(napi_env env)
+{
+ const napi_property_attributes method = napi_writable | napi_configurable;
+ napi_property_descriptor d[] = {
+ {.utf8name = "send", .method = chat_send, .attributes = method},
+ {.utf8name = "load", .method = chat_load, .attributes = method},
+ {.utf8name = "set", .method = chat_set, .attributes = method},
+ {.utf8name = "reset", .method = chat_reset, .attributes = method},
+ {.utf8name = "close", .method = chat_close, .attributes = method},
+ };
+ napi_value cls = NULL;
+ if (napi_define_class(env, "Chat", JANAS_NAPI_AUTO_LENGTH,
+ janas_node_constructor,
+ (void *)"a Chat comes from model.chat()",
+ sizeof(d) / sizeof(d[0]), d, &cls) != napi_ok)
+ return NULL;
+ return cls;
+}
diff --git a/src/node/engine.c b/src/node/engine.c
new file mode 100644
index 0000000..d007612
--- /dev/null
+++ b/src/node/engine.c
@@ -0,0 +1,327 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * engine.c - a model's engine thread: the queue of the jobs JavaScript's
+ * thread posts, what the engine's gives back, and the model's life - open,
+ * held by JavaScript's objects, closed when asked or when none of them is
+ * left, and with the environment when Node leaves it.
+ *
+ * The engine's thread runs the jobs in the order they were posted, one at a
+ * time, so a reply asked for while another is written waits for it: the
+ * model holds one conversation. Every job comes back to JavaScript's thread
+ * through the thread-safe function, after the pieces of the reply it wrote;
+ * the last one (a close, or an open that failed) ends the thread, and
+ * JavaScript's thread joins it there.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "node/node_impl.h"
+
+/* the engine's thread's stack: as large as a program's main thread, where
+ the library otherwise runs */
+#define ENGINE_STACK (8u << 20)
+
+static void back_free(struct janas_node_back *b)
+{
+ if (b->kind != JANAS_NODE_BACK_JOB) {
+ free(b);
+ return;
+ }
+ struct janas_node_job *j = (struct janas_node_job *)b;
+ if (j->drop)
+ j->drop(j->data);
+ else
+ free(j->data);
+ free(j);
+}
+
+struct janas_node_job *janas_node_job(struct janas_node_model *m,
+ void (*run)(struct janas_node_job *j))
+{
+ struct janas_node_job *j = calloc(1, sizeof(*j));
+ if (!j)
+ return NULL;
+ j->back.kind = JANAS_NODE_BACK_JOB;
+ j->m = m;
+ j->run = run;
+ return j;
+}
+
+static void *engine_main(void *arg)
+{
+ struct janas_node_model *m = arg;
+ for (;;) {
+ pthread_mutex_lock(&m->mu);
+ while (!m->head)
+ pthread_cond_wait(&m->cv, &m->mu);
+ struct janas_node_job *j = m->head;
+ m->head = j->next;
+ if (!m->head)
+ m->tail = NULL;
+ pthread_mutex_unlock(&m->mu);
+ j->run(j);
+ int last = j->last; /* j is JavaScript's once given back */
+ janas_node_give(m, &j->back);
+ if (last)
+ return NULL;
+ }
+}
+
+void janas_node_give(struct janas_node_model *m, struct janas_node_back *b)
+{
+ if (napi_call_threadsafe_function(m->tsfn, b, napi_tsfn_nonblocking) ==
+ napi_ok)
+ return;
+ /* the environment is going away: freed after the thread is joined */
+ pthread_mutex_lock(&m->mu);
+ b->next = m->undelivered;
+ m->undelivered = b;
+ pthread_mutex_unlock(&m->mu);
+}
+
+void janas_node_post(napi_env env, struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ if (m->pending++ == 0 && !m->st->teardown)
+ napi_ref_threadsafe_function(env, m->tsfn);
+ pthread_mutex_lock(&m->mu);
+ j->next = NULL;
+ if (m->tail)
+ m->tail->next = j;
+ else
+ m->head = j;
+ m->tail = j;
+ pthread_cond_signal(&m->cv);
+ pthread_mutex_unlock(&m->mu);
+}
+
+void janas_node_ref(struct janas_node_model *m)
+{
+ m->refs++;
+}
+
+void janas_node_unref(napi_env env, struct janas_node_model *m)
+{
+ (void)env;
+ if (--m->refs > 0)
+ return;
+ struct janas_node_env *st = m->st;
+ free(m->close_job);
+ free(m->close_wait);
+ pthread_cond_destroy(&m->cv);
+ pthread_mutex_destroy(&m->mu);
+ free(m);
+ janas_node_env_unref(st);
+}
+
+void janas_node_hold(struct janas_node_model *m)
+{
+ m->holders++;
+ m->refs++;
+}
+
+void janas_node_release(napi_env env, struct janas_node_model *m)
+{
+ if (--m->holders == 0 && !m->closing && m->engine && !m->st->teardown)
+ janas_node_close(env, m, NULL);
+ janas_node_unref(env, m);
+}
+
+static void unlink_model(struct janas_node_model *m)
+{
+ for (struct janas_node_model **p = &m->st->models; *p; p = &(*p)->next)
+ if (*p == m) {
+ *p = m->next;
+ break;
+ }
+}
+
+/* After the thread is joined: whatever it left behind, that never came
+ back or never ran (the open failed with jobs queued after it, or the
+ environment went first). */
+static void leftovers(struct janas_node_model *m)
+{
+ while (m->undelivered) {
+ struct janas_node_back *b = m->undelivered;
+ m->undelivered = b->next;
+ back_free(b);
+ }
+ while (m->head) {
+ struct janas_node_job *j = m->head;
+ m->head = j->next;
+ back_free(&j->back);
+ }
+ m->tail = NULL;
+}
+
+/* JavaScript's thread, the last job back: the thread is ending */
+static void engine_ended(napi_env env, struct janas_node_model *m)
+{
+ pthread_join(m->thread, NULL);
+ m->engine = 0;
+ napi_release_threadsafe_function(m->tsfn, napi_tsfn_release);
+ leftovers(m);
+ unlink_model(m);
+ for (int i = 0; i < m->n_close_wait; i++)
+ napi_resolve_deferred(env, m->close_wait[i], janas_node_undefined(env));
+ m->n_close_wait = 0;
+ janas_node_unref(env, m); /* the engine's */
+}
+
+static void job_back(napi_env env, struct janas_node_model *m,
+ struct janas_node_job *j)
+{
+ if (j->deferred) {
+ napi_value v = NULL;
+ if (j->rc >= 0) {
+ v = j->value ? j->value(env, j) : janas_node_undefined(env);
+ if (!v) {
+ j->rc = JANAS_LLM_ENOMEM;
+ snprintf(j->error, sizeof(j->error),
+ "janas: the result could not be made");
+ }
+ }
+ if (v)
+ napi_resolve_deferred(env, j->deferred, v);
+ else
+ napi_reject_deferred(env, j->deferred,
+ janas_node_error(env, j->rc, j->error));
+ }
+ if (j->after)
+ j->after(env, j);
+ if (--m->pending == 0 && !j->last)
+ napi_unref_threadsafe_function(env, m->tsfn);
+ if (j->last)
+ engine_ended(env, m);
+ back_free(&j->back);
+}
+
+static void call_js(napi_env env, napi_value cb, void *context, void *data)
+{
+ (void)cb;
+ struct janas_node_back *b = data;
+ if (!env) { /* the environment went: the memory, and nothing it points to */
+ back_free(b);
+ return;
+ }
+ if (b->kind == JANAS_NODE_BACK_JOB)
+ job_back(env, context, (struct janas_node_job *)b);
+ else
+ janas_node_reply_back(env, (struct janas_node_msg *)b);
+}
+
+static void close_run(struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ if (m->chat) {
+ janas_llm_chat_destroy(m->chat);
+ m->chat = NULL;
+ }
+ if (m->llm) {
+ janas_llm_close(m->llm);
+ m->llm = NULL;
+ }
+ j->last = 1;
+}
+
+struct janas_node_model *janas_node_engine(napi_env env,
+ struct janas_node_env *st)
+{
+ struct janas_node_model *m = calloc(1, sizeof(*m));
+ if (!m)
+ return NULL;
+ m->st = st;
+ m->refs = 1; /* the engine's */
+ m->close_job = janas_node_job(m, close_run);
+ if (!m->close_job) {
+ free(m);
+ return NULL;
+ }
+ pthread_mutex_init(&m->mu, NULL);
+ pthread_cond_init(&m->cv, NULL);
+ pthread_attr_t attr;
+ int ok = pthread_attr_init(&attr) == 0;
+ if (ok)
+ pthread_attr_setstacksize(&attr, ENGINE_STACK);
+ if (!ok || napi_create_threadsafe_function(
+ env, NULL, NULL,
+ janas_node_string(env, "janas", JANAS_NAPI_AUTO_LENGTH), 0,
+ 1, NULL, NULL, m, call_js, &m->tsfn) != napi_ok) {
+ if (ok)
+ pthread_attr_destroy(&attr);
+ goto fail;
+ }
+ if (pthread_create(&m->thread, &attr, engine_main, m) != 0) {
+ pthread_attr_destroy(&attr);
+ napi_release_threadsafe_function(m->tsfn, napi_tsfn_abort);
+ goto fail;
+ }
+ pthread_attr_destroy(&attr);
+ m->engine = 1;
+ st->refs++;
+ m->next = st->models;
+ st->models = m;
+ /* nothing posted yet: an idle model does not keep Node running */
+ napi_unref_threadsafe_function(env, m->tsfn);
+ return m;
+fail:
+ pthread_cond_destroy(&m->cv);
+ pthread_mutex_destroy(&m->mu);
+ free(m->close_job);
+ free(m);
+ return NULL;
+}
+
+void janas_node_close(napi_env env, struct janas_node_model *m, napi_deferred d)
+{
+ if (d && !m->engine) {
+ napi_resolve_deferred(env, d, janas_node_undefined(env));
+ return;
+ }
+ if (d) {
+ napi_deferred *w =
+ realloc(m->close_wait, (size_t)(m->n_close_wait + 1) * sizeof(*w));
+ if (w) {
+ m->close_wait = w;
+ w[m->n_close_wait++] = d;
+ } else
+ napi_reject_deferred(
+ env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM,
+ "janas: out of memory; the model "
+ "closes all the same"));
+ }
+ if (m->closing)
+ return;
+ m->closing = 1;
+ m->has_chat = 0;
+ janas_node_stop_replies(m);
+ struct janas_node_job *j = m->close_job;
+ m->close_job = NULL;
+ janas_node_post(env, j);
+}
+
+void janas_node_teardown(struct janas_node_env *st)
+{
+ st->teardown = 1;
+ while (st->models) {
+ struct janas_node_model *m = st->models;
+ st->models = m->next;
+ janas_node_stop_replies(m);
+ if (!m->closing) {
+ m->closing = 1;
+ struct janas_node_job *j = m->close_job;
+ m->close_job = NULL;
+ janas_node_post(NULL, j);
+ }
+ /* what the thread gives back from now on is not delivered: it is
+ left for leftovers() */
+ napi_release_threadsafe_function(m->tsfn, napi_tsfn_abort);
+ pthread_join(m->thread, NULL);
+ m->engine = 0;
+ leftovers(m);
+ janas_node_unref(NULL, m); /* the engine's */
+ }
+}
diff --git a/src/node/janas.d.ts b/src/node/janas.d.ts
new file mode 100644
index 0000000..fe2fef7
--- /dev/null
+++ b/src/node/janas.d.ts
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 Maurizio Cammalleri
+/**
+ * janas.node - Janas-LLM in Node.js: a model opened inside the process, its
+ * replies read as they are written. Built by build.sh beside the programs
+ * (bin/x86_64-linux/janas.node), Linux for now. It speaks Node-API version
+ * 8, which Node has had since 12.22; it was tried with Node 20.
+ *
+ * It is a native module: load it with require, in an ES module through
+ * createRequire, and take its types from this file:
+ *
+ * import { createRequire } from "node:module";
+ * import type * as Janas from "./janas.js";
+ * const janas = createRequire(import.meta.url)("./janas.node") as typeof Janas;
+ *
+ * const model = await janas.open("qwen3-4b-q4km.jns");
+ * const chat = await model.chat({ thinking: false });
+ * for await (const piece of chat.send("Hello!"))
+ * if (piece.type === "text") process.stdout.write(piece.text);
+ * await model.close();
+ *
+ * Each model runs on a thread of its own, so JavaScript's thread never waits
+ * for it. A model holds one conversation: replies asked for while another is
+ * written wait for it, in the order they were asked. Wrong arguments throw a
+ * TypeError at once; what fails in the engine rejects the promise, or the
+ * reply's iteration, with a JanasError. An idle model does not keep Node
+ * running; one left open is closed when Node leaves.
+ *
+ * The engine's environment variables (JANAS_GPU, JANAS_NPU, JANAS_PROMPT_ON
+ * and the others of docs/chat.md) apply as in the programs, read when a model
+ * opens.
+ */
+
+/** The build of Janas it was made from (`git describe`). */
+export declare const version: string;
+
+/** The version of the library's ABI (JANAS_LLM_ABI_VERSION, 1). */
+export declare function abiVersion(): number;
+
+/**
+ * Opens a model file (.jns): the weights stay on disk, the experts are
+ * streamed from it and the most used kept in memory. Opening takes seconds:
+ * the expert cache is set up, and the engine reads what it learnt of this
+ * machine.
+ */
+export declare function open(path: string, options?: OpenOptions): Promise<Model>;
+
+export interface OpenOptions {
+ /** Context, in tokens (16384). */
+ context?: number;
+ /** Memory for the expert cache, GiB; 0 or absent: the free memory, less a margin. */
+ cacheGiB?: number;
+ /** Memory left to other programs when the cache takes the rest, GiB (a fifth of the machine's, 2 at least). */
+ reserveGiB?: number;
+ /** The model's multi-token prediction block, for faster replies: its path, or true to look beside the model. */
+ mtp?: string | boolean;
+ /** A small model of the same family that guesses the next tokens (Qwen3-0.6B for Qwen3-4B). */
+ draft?: string;
+ /** "auto" (default: max on mains power, eco on battery), "eco" (no GPU where it would only buy speed with power), "max". */
+ mode?: "auto" | "eco" | "max";
+ /** false: never give the GPU work. */
+ gpu?: boolean;
+ /** false: do not fill the expert cache, as the model opens, with the experts this machine used most. */
+ preload?: boolean;
+ /** Bits of the experts' down matrix read, for files that hold it in planes: 2, 4 or 6 (all of it). */
+ expertBits?: 2 | 4 | 6;
+ /** 4: the output head read at four bits (a few per cent faster, answers a little further from the weights). */
+ headBits?: 4 | 6;
+ /** How the attention scores are computed: "exact", "fast" (sixteen-bit integers), "auto". */
+ attention?: "auto" | "exact" | "fast";
+}
+
+/** An open model. */
+export declare class Model {
+ private constructor();
+ readonly path: string;
+ /** The name in its metadata ("Qwen3 4B"), empty if it has none. */
+ readonly name: string;
+ /** How it is made ("qwen3, 36 layers, ..."). */
+ readonly description: string;
+ /** The system message Janas's programs give it: its name is Janas, and it says which model it thinks with. */
+ readonly defaultSystem: string;
+ /** Whether it reasons before replying and can be told not to (ChatOptions.thinking). */
+ readonly reasons: boolean;
+ /** The MTP block opened with it, or false. */
+ readonly mtp: string | false;
+ /** Its conversation: one at a time per model (close it before asking another). */
+ chat(options?: ChatOptions): Promise<Chat>;
+ /** How its preparations go, without waiting for the engine: the expert cache filling, the NPU made ready. */
+ status(): ModelStatus;
+ /** Stops its replies, and closes it; called again, it waits for the same close. */
+ close(): Promise<void>;
+}
+
+export interface ModelStatus {
+ open: boolean;
+ /** a job is posted and not done: opening, a reply, a close */
+ busy: boolean;
+ /** the expert cache filled from this machine's profile: done of total experts */
+ preload: { done: number; total: number };
+ /** the NPU made ready (the first prompts of a session wait for it): graphs done of total, seconds */
+ npu: { preparing: boolean; done: number; total: number; seconds: number };
+}
+
+/** The parameters of a conversation, from the next reply on. */
+export interface ChatOptions {
+ /** The system message; only before the first message (or after reset). */
+ system?: string;
+ /** 0: always the most likely token (0.7). */
+ temperature?: number;
+ /** 0: no limit (20). */
+ topK?: number;
+ /** (0.8) */
+ topP?: number;
+ /** (0) */
+ minP?: number;
+ /** 0: a new one each chat (default). */
+ seed?: number;
+ /** Draft tokens ahead when it pays: the same text, sooner (true). */
+ speculate?: boolean;
+ /** Tokens of a reply, its reasoning included; 0: no limit. */
+ maxReply?: number;
+ /** Tokens of the answer, the reasoning not counted; 0: no limit. */
+ maxAnswer?: number;
+ /** Tokens of the reasoning, closed by the engine past them; 0: no limit. */
+ maxReasoning?: number;
+ /** The longest prompt, in tokens: a longer one fails with ELIMIT, nothing cut; 0: the context. */
+ maxInput?: number;
+ /** Reasoning before the reply, for the models that do it: true, false, or null for the model's own way. */
+ thinking?: boolean | null;
+ /** When the context fills, a recap of the oldest exchanges stays in it (true). */
+ recap?: boolean;
+ presencePenalty?: number;
+ frequencyPenalty?: number;
+ /** Conversations kept computed besides the current one, for load() switching between several (0). */
+ keep?: number;
+}
+
+export type Role = "system" | "user" | "assistant" | "tool";
+
+export interface Message {
+ role: Role;
+ content: string;
+}
+
+/** A model's conversation. */
+export declare class Chat {
+ private constructor();
+ /** A user message, in the conversation kept here; the reply follows. */
+ send(text: string, options?: ReplyOptions): Reply;
+ /**
+ * A whole conversation, as an HTTP client keeps it (only the first may be
+ * the system's; the last is the user's): what it shares with the one
+ * already computed is not read again.
+ */
+ load(messages: readonly Message[], options?: ReplyOptions): Reply;
+ /** New parameters, from the next reply on (and the system message, before the first). */
+ set(options: ChatOptions): Promise<void>;
+ /** Forgets the conversation, and the system message. */
+ reset(): Promise<void>;
+ /** Stops its replies and ends it: the model may have another. */
+ close(): Promise<void>;
+}
+
+export interface ReplyOptions {
+ /** Stops the reply when it aborts (the client of a request gone). */
+ signal?: AbortSignal;
+}
+
+/** A piece of the reply's text: the model's reasoning, or its answer. */
+export interface TextPiece {
+ readonly type: "text";
+ readonly text: string;
+ readonly reasoning: boolean;
+}
+
+/** How much of the prompt is read: one at each block of it. */
+export interface ProgressPiece {
+ readonly type: "progress";
+ readonly read: number;
+ readonly total: number;
+}
+
+export type Piece = TextPiece | ProgressPiece;
+
+/**
+ * A reply, as the model writes it: read it with for await, or whole with
+ * text(). Leaving the loop early (break, return, an exception) stops it.
+ */
+export declare class Reply implements AsyncIterable<Piece> {
+ private constructor();
+ next(): Promise<IteratorResult<Piece, undefined>>;
+ return(value?: unknown): Promise<IteratorResult<Piece, undefined>>;
+ [Symbol.asyncIterator](): Reply;
+ /** Stops it where it is; the pieces already written can still be read. */
+ stop(): void;
+ /** The answer, its reasoning left out, once the reply is over; the pieces go to it from then on. */
+ text(): Promise<string>;
+ /** Its counters, once it is over. */
+ stats(): Promise<ReplyStats>;
+}
+
+export interface ReplyStats {
+ /** why it ended: the model ended it, max tokens, the context full, an error, tool calls, stop() or an abort */
+ finish: "stop" | "length" | "context" | "error" | "tools" | "stopped" | null;
+ /** the whole prompt, of which cachedTokens already computed; inputTokens read for this reply */
+ promptTokens: number;
+ cachedTokens: number;
+ inputTokens: number;
+ outputTokens: number;
+ reasoningTokens: number;
+ contextUsed: number;
+ contextSize: number;
+ /** draft tokens guessed, and kept */
+ drafted: number;
+ accepted: number;
+ /** seconds reading the prompt, writing the reply, in all, to the first token */
+ inputSeconds: number;
+ outputSeconds: number;
+ totalSeconds: number;
+ firstTokenSeconds: number;
+ /** the threads the engine chose for reading and for writing */
+ inputThreads: number;
+ outputThreads: number;
+ /** the routed experts used, read from the disk, the bytes read, the time waiting for them */
+ expertsUsed: number;
+ expertsRead: number;
+ bytesRead: number;
+ ioWaitSeconds: number;
+ peakRssBytes: number;
+ /** maxReasoning closed the reasoning, not the model */
+ reasoningCut: boolean;
+}
+
+/** The error a promise or a reply rejects with when the engine fails: its code is
+ the suffix of the library's JANAS_LLM_E... (EOPEN for JANAS_LLM_EOPEN), and
+ ECLOSED for a model or a chat closed. */
+export interface JanasError extends Error {
+ code:
+ | "EINVAL"
+ | "ENOMEM"
+ | "EOPEN"
+ | "EMODEL"
+ | "EFULL"
+ | "EBUSY"
+ | "ESMALL"
+ | "EFAIL"
+ | "ELIMIT"
+ | "ECLOSED";
+}
diff --git a/src/node/model.c b/src/node/model.c
new file mode 100644
index 0000000..f5fac81
--- /dev/null
+++ b/src/node/model.c
@@ -0,0 +1,357 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * model.c - open() and the Model class: a model file opened on an engine
+ * thread of its own, its chat, how its preparations are going, close().
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "node/node_impl.h"
+
+#define GIB 1073741824.0
+
+struct open_job {
+ char *path;
+ struct janas_llm_params p;
+ char *mtp, *draft;
+ int find_mtp; /* mtp: true, the block beside the model if there is one */
+ int no_gpu;
+ char found[4096]; /* the block found */
+ /* what the model says of itself, for the Model's properties */
+ char *name, *description, *system;
+ int reasons;
+};
+
+static void open_drop(void *data)
+{
+ struct open_job *oj = data;
+ if (!oj)
+ return;
+ free(oj->path);
+ free(oj->mtp);
+ free(oj->draft);
+ free(oj->name);
+ free(oj->description);
+ free(oj->system);
+ free(oj);
+}
+
+static const char *const open_known[] = {
+ "context", "cacheGiB", "reserveGiB", "mtp", "draft", "mode",
+ "gpu", "preload", "expertBits", "headBits", "attention", NULL};
+
+/* one of the strings, as its index; -1 after throwing */
+static int choice(napi_env env, napi_value o, const char *name,
+ const char *const *names, int *out)
+{
+ char *s = NULL;
+ int r = janas_node_opt_string(env, o, "open", name, &s);
+ if (r <= 0)
+ return r;
+ for (int i = 0; names[i]; i++)
+ if (!strcmp(names[i], s)) {
+ free(s);
+ *out = i;
+ return 1;
+ }
+ janas_node_type_error(env, "janas: open: %s cannot be '%s'", name, s);
+ free(s);
+ return -1;
+}
+
+static int open_options(napi_env env, napi_value o, struct open_job *oj)
+{
+ const char *w = "open";
+ static const char *const modes[] = {"auto", "eco", "max", NULL};
+ static const char *const attn[] = {"auto", "exact", "fast", NULL};
+ int64_t i;
+ double d;
+ int b, r, k;
+ if (janas_node_options(env, o, w, open_known) < 0)
+ return -1;
+ if ((r = janas_node_opt_int(env, o, w, "context", 1, UINT32_MAX, &i)) < 0)
+ return -1;
+ if (r)
+ oj->p.n_ctx = (uint32_t)i;
+ if ((r = janas_node_opt_number(env, o, w, "cacheGiB", 0, 1 << 20, &d)) < 0)
+ return -1;
+ if (r)
+ oj->p.cache_bytes = (uint64_t)(d * GIB);
+ if ((r = janas_node_opt_number(env, o, w, "reserveGiB", 0, 1 << 20, &d)) <
+ 0)
+ return -1;
+ if (r)
+ oj->p.reserve_bytes = (uint64_t)(d * GIB);
+ napi_value v;
+ napi_valuetype t;
+ if (o && napi_typeof(env, o, &t) == napi_ok && t == napi_object &&
+ napi_get_named_property(env, o, "mtp", &v) == napi_ok &&
+ napi_typeof(env, v, &t) == napi_ok && t != napi_undefined) {
+ if (t == napi_boolean) {
+ bool on = false;
+ napi_get_value_bool(env, v, &on);
+ oj->find_mtp = on;
+ } else if (janas_node_opt_string(env, o, w, "mtp", &oj->mtp) < 0)
+ return -1;
+ }
+ if (janas_node_opt_string(env, o, w, "draft", &oj->draft) < 0)
+ return -1;
+ if ((r = choice(env, o, "mode", modes, &k)) < 0)
+ return -1;
+ if (r)
+ oj->p.mode = k == 1 ? JANAS_LLM_MODE_ECO
+ : k == 2 ? JANAS_LLM_MODE_MAX
+ : JANAS_LLM_MODE_AUTO;
+ if ((r = janas_node_opt_bool(env, o, w, "gpu", &b)) < 0)
+ return -1;
+ if (r)
+ oj->no_gpu = !b;
+ if ((r = janas_node_opt_bool(env, o, w, "preload", &b)) < 0)
+ return -1;
+ if (r)
+ oj->p.no_preload = !b;
+ if ((r = janas_node_opt_int(env, o, w, "expertBits", 2, 6, &i)) < 0)
+ return -1;
+ if (r && i != 2 && i != 4 && i != 6) {
+ janas_node_type_error(env, "janas: open: expertBits is 2, 4 or 6");
+ return -1;
+ }
+ if (r)
+ oj->p.expert_bits = (int32_t)i;
+ if ((r = janas_node_opt_int(env, o, w, "headBits", 4, 6, &i)) < 0)
+ return -1;
+ if (r && i == 5) {
+ janas_node_type_error(env, "janas: open: headBits is 4 or 6");
+ return -1;
+ }
+ if (r)
+ oj->p.head_bits = (int32_t)i;
+ if ((r = choice(env, o, "attention", attn, &k)) < 0)
+ return -1;
+ if (r)
+ oj->p.attn_scores = k == 1 ? JANAS_LLM_ATTN_EXACT
+ : k == 2 ? JANAS_LLM_ATTN_FAST
+ : JANAS_LLM_ATTN_AUTO;
+ return 0;
+}
+
+/* a text the library writes (janas_llm_name and the like), malloc'd */
+static char *take(int32_t (*get)(const janas_llm *, char *, int32_t, int32_t *),
+ const janas_llm *llm)
+{
+ char small[256];
+ int32_t len = 0;
+ if (get(llm, small, sizeof(small), &len) != JANAS_LLM_OK || len < 0)
+ return strdup("");
+ if (len < (int32_t)sizeof(small))
+ return strdup(small);
+ char *s = malloc((size_t)len + 1);
+ if (s && get(llm, s, len + 1, &len) != JANAS_LLM_OK)
+ s[0] = 0;
+ return s;
+}
+
+static void open_run(struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ struct open_job *oj = j->data;
+ if (oj->find_mtp && janas_llm_find_mtp(oj->path, oj->found,
+ sizeof(oj->found)) == JANAS_LLM_OK)
+ oj->p.mtp_path = oj->found;
+ else if (oj->mtp)
+ oj->p.mtp_path = oj->mtp;
+ oj->p.draft_path = oj->draft;
+ j->rc = janas_llm_open(oj->path, &oj->p, &m->llm);
+ if (j->rc != JANAS_LLM_OK) {
+ snprintf(j->error, sizeof(j->error), "%s", janas_llm_last_error());
+ m->llm = NULL;
+ j->last = 1; /* no model: the thread ends */
+ return;
+ }
+ /* where there is no GPU there is nothing to keep it off */
+ if (oj->no_gpu)
+ janas_llm_set_gpu(m->llm, 0);
+ oj->name = take(janas_llm_name, m->llm);
+ oj->description = take(janas_llm_describe, m->llm);
+ oj->system = take(janas_llm_default_system, m->llm);
+ oj->reasons = janas_llm_reasons(m->llm);
+}
+
+static void model_finalize(napi_env env, void *data, void *hint)
+{
+ (void)hint;
+ janas_node_release(env, data);
+}
+
+static napi_value text_or_empty(napi_env env, const char *s)
+{
+ return janas_node_string(env, s ? s : "", JANAS_NAPI_AUTO_LENGTH);
+}
+
+static napi_value open_value(napi_env env, struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ struct open_job *oj = j->data;
+ napi_value obj = janas_node_new(env, m->st->model_class,
+ &janas_node_model_tag, m, model_finalize);
+ if (!obj)
+ return NULL;
+ janas_node_hold(m);
+ napi_property_descriptor d[] = {
+ {.utf8name = "path",
+ .value = text_or_empty(env, oj->path),
+ .attributes = napi_enumerable},
+ {.utf8name = "name",
+ .value = text_or_empty(env, oj->name),
+ .attributes = napi_enumerable},
+ {.utf8name = "description",
+ .value = text_or_empty(env, oj->description),
+ .attributes = napi_enumerable},
+ {.utf8name = "defaultSystem",
+ .value = text_or_empty(env, oj->system),
+ .attributes = napi_enumerable},
+ {.utf8name = "reasons",
+ .value = janas_node_bool(env, oj->reasons),
+ .attributes = napi_enumerable},
+ {.utf8name = "mtp",
+ .value = oj->p.mtp_path ? text_or_empty(env, oj->p.mtp_path)
+ : janas_node_bool(env, 0),
+ .attributes = napi_enumerable},
+ };
+ napi_define_properties(env, obj, sizeof(d) / sizeof(d[0]), d);
+ return obj;
+}
+
+static void open_after(napi_env env, struct janas_node_job *j)
+{
+ struct janas_node_model *m = j->m;
+ if (j->rc < 0)
+ m->closing = 1; /* the thread has ended: back as the last job */
+ else if (!m->holders)
+ janas_node_close(env, m, NULL); /* its object could not be made */
+}
+
+napi_value janas_node_open(napi_env env, napi_callback_info info)
+{
+ size_t argc = 2;
+ napi_value argv[2] = {NULL, NULL};
+ napi_get_cb_info(env, info, &argc, argv, NULL, NULL);
+ struct janas_node_env *st = janas_node_env(env);
+ size_t len = 0;
+ char *path = argc ? janas_node_text(env, argv[0], &len) : NULL;
+ if (!st || !path)
+ return len == SIZE_MAX
+ ? janas_node_throw(env, JANAS_LLM_ENOMEM,
+ "janas: out of memory")
+ : janas_node_type_error(
+ env, "janas: open(path, options): the path of a "
+ ".jns file, as a string");
+ struct open_job *oj = calloc(1, sizeof(*oj));
+ if (!oj) {
+ free(path);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ }
+ oj->path = path;
+ janas_llm_params_default(&oj->p);
+ if (open_options(env, argc > 1 ? argv[1] : NULL, oj) < 0) {
+ open_drop(oj);
+ return NULL;
+ }
+ struct janas_node_model *m = janas_node_engine(env, st);
+ struct janas_node_job *j = m ? janas_node_job(m, open_run) : NULL;
+ napi_value p = j ? janas_node_promise(env, &j->deferred) : NULL;
+ if (!p) {
+ open_drop(oj);
+ free(j);
+ if (m) /* the thread ends with the close it is given */
+ janas_node_close(env, m, NULL);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM,
+ "janas: open: no memory or no thread for "
+ "the engine");
+ }
+ j->data = oj;
+ j->drop = open_drop;
+ j->value = open_value;
+ j->after = open_after;
+ janas_node_post(env, j);
+ return p;
+}
+
+static napi_value model_chat(napi_env env, napi_callback_info info)
+{
+ size_t argc = 1;
+ napi_value argv[1] = {NULL};
+ struct janas_node_model *m = janas_node_self(
+ env, info, &janas_node_model_tag, &argc, argv, "Model.chat");
+ if (!m)
+ return NULL;
+ return janas_node_chat(env, m, argc ? argv[0] : NULL);
+}
+
+static napi_value model_close(napi_env env, napi_callback_info info)
+{
+ struct janas_node_model *m = janas_node_self(
+ env, info, &janas_node_model_tag, NULL, NULL, "Model.close");
+ if (!m)
+ return NULL;
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p)
+ janas_node_close(env, m, d);
+ return p;
+}
+
+/* How the model's preparations are going: the expert cache filling from
+ what this machine used most, the NPU made ready. The library allows both
+ questions while the engine's thread works. */
+static napi_value model_status(napi_env env, napi_callback_info info)
+{
+ struct janas_node_model *m = janas_node_self(
+ env, info, &janas_node_model_tag, NULL, NULL, "Model.status");
+ if (!m)
+ return NULL;
+ int open = m->engine && !m->closing && m->llm;
+ int64_t done = 0, total = 0;
+ int32_t ndone = 0, ntotal = 0;
+ double seconds = 0;
+ int preparing = 0;
+ if (open) {
+ janas_llm_preload(m->llm, &done, &total);
+ preparing = janas_llm_npu_preparing(m->llm, &ndone, &ntotal, &seconds);
+ }
+ napi_value o, pre, npu;
+ if (napi_create_object(env, &o) != napi_ok ||
+ napi_create_object(env, &pre) != napi_ok ||
+ napi_create_object(env, &npu) != napi_ok)
+ return NULL;
+ janas_node_put(env, pre, "done", janas_node_number(env, (double)done));
+ janas_node_put(env, pre, "total", janas_node_number(env, (double)total));
+ janas_node_put(env, npu, "preparing", janas_node_bool(env, preparing > 0));
+ janas_node_put(env, npu, "done", janas_node_number(env, ndone));
+ janas_node_put(env, npu, "total", janas_node_number(env, ntotal));
+ janas_node_put(env, npu, "seconds", janas_node_number(env, seconds));
+ janas_node_put(env, o, "open", janas_node_bool(env, open));
+ janas_node_put(env, o, "busy", janas_node_bool(env, m->pending > 0));
+ janas_node_put(env, o, "preload", pre);
+ janas_node_put(env, o, "npu", npu);
+ return o;
+}
+
+napi_value janas_node_model_class(napi_env env)
+{
+ const napi_property_attributes method = napi_writable | napi_configurable;
+ napi_property_descriptor d[] = {
+ {.utf8name = "chat", .method = model_chat, .attributes = method},
+ {.utf8name = "status", .method = model_status, .attributes = method},
+ {.utf8name = "close", .method = model_close, .attributes = method},
+ };
+ napi_value cls = NULL;
+ if (napi_define_class(env, "Model", JANAS_NAPI_AUTO_LENGTH,
+ janas_node_constructor,
+ (void *)"a Model comes from open()",
+ sizeof(d) / sizeof(d[0]), d, &cls) != napi_ok)
+ return NULL;
+ return cls;
+}
diff --git a/src/node/napi.h b/src/node/napi.h
new file mode 100644
index 0000000..de7bf6f
--- /dev/null
+++ b/src/node/napi.h
@@ -0,0 +1,222 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * napi.h - the part of Node-API that the module for Node.js calls, declared
+ * here so that Janas builds without Node's headers. Node-API is Node's C
+ * interface for native modules, the same in every version of Node from 12.22
+ * on (this is its version 8): its functions are the node process's own, found
+ * when the module is loaded.
+ *
+ * Types, values and layouts as Node's js_native_api_types.h and
+ * node_api_types.h have them, only those the module uses. Where Node's
+ * headers are installed, tests/test_node.c declares these functions after
+ * them, and the compiler checks that the two agree. Private to src/node/.
+ */
+#ifndef JANAS_NODE_NAPI_H
+#define JANAS_NODE_NAPI_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+/* a string's length when it ends with a NUL */
+#define JANAS_NAPI_AUTO_LENGTH SIZE_MAX
+
+#ifndef JANAS_NAPI_NODE_TYPES /* the check takes Node's own */
+typedef struct napi_env__ *napi_env;
+typedef struct napi_value__ *napi_value;
+typedef struct napi_ref__ *napi_ref;
+typedef struct napi_callback_info__ *napi_callback_info;
+typedef struct napi_deferred__ *napi_deferred;
+typedef struct napi_threadsafe_function__ *napi_threadsafe_function;
+
+typedef enum {
+ napi_ok,
+ napi_invalid_arg,
+ napi_object_expected,
+ napi_string_expected,
+ napi_name_expected,
+ napi_function_expected,
+ napi_number_expected,
+ napi_boolean_expected,
+ napi_array_expected,
+ napi_generic_failure,
+ napi_pending_exception,
+ napi_cancelled,
+ napi_escape_called_twice,
+ napi_handle_scope_mismatch,
+ napi_callback_scope_mismatch,
+ napi_queue_full,
+ napi_closing,
+ napi_bigint_expected,
+ napi_date_expected,
+ napi_arraybuffer_expected,
+ napi_detachable_arraybuffer_expected,
+ napi_would_deadlock
+} napi_status;
+
+typedef enum {
+ napi_undefined,
+ napi_null,
+ napi_boolean,
+ napi_number,
+ napi_string,
+ napi_symbol,
+ napi_object,
+ napi_function,
+ napi_external,
+ napi_bigint
+} napi_valuetype;
+
+typedef enum {
+ napi_default = 0,
+ napi_writable = 1 << 0,
+ napi_enumerable = 1 << 1,
+ napi_configurable = 1 << 2,
+ napi_static = 1 << 10
+} napi_property_attributes;
+
+typedef enum {
+ napi_tsfn_release,
+ napi_tsfn_abort
+} napi_threadsafe_function_release_mode;
+
+typedef enum {
+ napi_tsfn_nonblocking,
+ napi_tsfn_blocking
+} napi_threadsafe_function_call_mode;
+
+typedef napi_value (*napi_callback)(napi_env env, napi_callback_info info);
+typedef void (*napi_finalize)(napi_env env, void *finalize_data,
+ void *finalize_hint);
+typedef void (*napi_threadsafe_function_call_js)(napi_env env,
+ napi_value js_callback,
+ void *context, void *data);
+typedef void (*napi_cleanup_hook)(void *arg);
+
+typedef struct {
+ const char *utf8name; /* one of utf8name and name is NULL */
+ napi_value name;
+ napi_callback method;
+ napi_callback getter;
+ napi_callback setter;
+ napi_value value;
+ napi_property_attributes attributes;
+ void *data;
+} napi_property_descriptor;
+
+typedef struct {
+ const char *error_message;
+ void *engine_reserved;
+ uint32_t engine_error_code;
+ napi_status error_code;
+} napi_extended_error_info;
+
+typedef struct {
+ uint64_t lower;
+ uint64_t upper;
+} napi_type_tag;
+#endif
+
+/* js_native_api.h */
+napi_status napi_get_last_error_info(napi_env env,
+ const napi_extended_error_info **result);
+napi_status napi_get_undefined(napi_env env, napi_value *result);
+napi_status napi_get_null(napi_env env, napi_value *result);
+napi_status napi_get_global(napi_env env, napi_value *result);
+napi_status napi_get_boolean(napi_env env, bool value, napi_value *result);
+napi_status napi_create_object(napi_env env, napi_value *result);
+napi_status napi_create_double(napi_env env, double value, napi_value *result);
+napi_status napi_create_string_utf8(napi_env env, const char *str,
+ size_t length, napi_value *result);
+napi_status napi_create_function(napi_env env, const char *utf8name,
+ size_t length, napi_callback cb, void *data,
+ napi_value *result);
+napi_status napi_create_error(napi_env env, napi_value code, napi_value msg,
+ napi_value *result);
+napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype *result);
+napi_status napi_get_value_double(napi_env env, napi_value value,
+ double *result);
+napi_status napi_get_value_bool(napi_env env, napi_value value, bool *result);
+napi_status napi_get_value_string_utf8(napi_env env, napi_value value,
+ char *buf, size_t bufsize,
+ size_t *result);
+napi_status napi_get_property_names(napi_env env, napi_value object,
+ napi_value *result);
+napi_status napi_set_named_property(napi_env env, napi_value object,
+ const char *utf8name, napi_value value);
+napi_status napi_get_named_property(napi_env env, napi_value object,
+ const char *utf8name, napi_value *result);
+napi_status napi_get_element(napi_env env, napi_value object, uint32_t index,
+ napi_value *result);
+napi_status napi_is_array(napi_env env, napi_value value, bool *result);
+napi_status napi_get_array_length(napi_env env, napi_value value,
+ uint32_t *result);
+napi_status napi_call_function(napi_env env, napi_value recv, napi_value func,
+ size_t argc, const napi_value *argv,
+ napi_value *result);
+napi_status napi_new_instance(napi_env env, napi_value constructor, size_t argc,
+ const napi_value *argv, napi_value *result);
+napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo,
+ size_t *argc, napi_value *argv,
+ napi_value *this_arg, void **data);
+napi_status napi_define_class(napi_env env, const char *utf8name, size_t length,
+ napi_callback constructor, void *data,
+ size_t property_count,
+ const napi_property_descriptor *properties,
+ napi_value *result);
+napi_status napi_define_properties(napi_env env, napi_value object,
+ size_t property_count,
+ const napi_property_descriptor *properties);
+napi_status napi_wrap(napi_env env, napi_value js_object, void *native_object,
+ napi_finalize finalize_cb, void *finalize_hint,
+ napi_ref *result);
+napi_status napi_unwrap(napi_env env, napi_value js_object, void **result);
+napi_status napi_create_reference(napi_env env, napi_value value,
+ uint32_t initial_refcount, napi_ref *result);
+napi_status napi_delete_reference(napi_env env, napi_ref ref);
+napi_status napi_get_reference_value(napi_env env, napi_ref ref,
+ napi_value *result);
+napi_status napi_throw_error(napi_env env, const char *code, const char *msg);
+napi_status napi_throw_type_error(napi_env env, const char *code,
+ const char *msg);
+napi_status napi_is_exception_pending(napi_env env, bool *result);
+napi_status napi_get_and_clear_last_exception(napi_env env, napi_value *result);
+napi_status napi_create_promise(napi_env env, napi_deferred *deferred,
+ napi_value *promise);
+napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred,
+ napi_value resolution);
+napi_status napi_reject_deferred(napi_env env, napi_deferred deferred,
+ napi_value rejection);
+napi_status napi_set_instance_data(napi_env env, void *data,
+ napi_finalize finalize_cb,
+ void *finalize_hint);
+napi_status napi_get_instance_data(napi_env env, void **data);
+napi_status napi_type_tag_object(napi_env env, napi_value value,
+ const napi_type_tag *type_tag);
+napi_status napi_check_object_type_tag(napi_env env, napi_value value,
+ const napi_type_tag *type_tag,
+ bool *result);
+
+/* node_api.h */
+napi_status napi_add_env_cleanup_hook(napi_env env, napi_cleanup_hook fun,
+ void *arg);
+napi_status napi_create_threadsafe_function(
+ napi_env env, napi_value func, napi_value async_resource,
+ napi_value async_resource_name, size_t max_queue_size,
+ size_t initial_thread_count, void *thread_finalize_data,
+ napi_finalize thread_finalize_cb, void *context,
+ napi_threadsafe_function_call_js call_js_cb,
+ napi_threadsafe_function *result);
+napi_status
+napi_call_threadsafe_function(napi_threadsafe_function func, void *data,
+ napi_threadsafe_function_call_mode is_blocking);
+napi_status
+napi_release_threadsafe_function(napi_threadsafe_function func,
+ napi_threadsafe_function_release_mode mode);
+napi_status napi_ref_threadsafe_function(napi_env env,
+ napi_threadsafe_function func);
+napi_status napi_unref_threadsafe_function(napi_env env,
+ napi_threadsafe_function func);
+
+#endif
diff --git a/src/node/node_impl.h b/src/node/node_impl.h
new file mode 100644
index 0000000..18525be
--- /dev/null
+++ b/src/node/node_impl.h
@@ -0,0 +1,246 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * node_impl.h - what the files of the module for Node.js share: janas.node,
+ * the library's API for JavaScript (janas.d.ts says it in TypeScript).
+ *
+ * Every open model has a thread of its own, the engine's: the library wants
+ * a model and its chat used from one thread at a time, and JavaScript's
+ * thread must never wait for a model. JavaScript's thread posts jobs to it
+ * (open, a chat, a reply, close), and the engine's gives back each job when
+ * done, and the pieces of a reply as they come, through a thread-safe
+ * function: every JavaScript value is made on JavaScript's thread. The
+ * fields belong to JavaScript's thread where a comment does not say
+ * otherwise.
+ */
+#ifndef JANAS_NODE_IMPL_H
+#define JANAS_NODE_IMPL_H
+
+#include <pthread.h>
+#include <stdatomic.h>
+
+#include "janas/llm.h"
+#include "node/napi.h"
+
+/* the module's own failure, beside the library's JANAS_LLM_E... */
+#define JANAS_NODE_ECLOSED (-100) /* the model or the chat is closed */
+
+struct janas_node_model;
+struct janas_node_reply;
+
+/* The classes and the engines of one Node environment (the main thread's,
+ or a worker's): every environment loads the module anew. */
+struct janas_node_env {
+ int refs; /* the environment, and each model opened in it */
+ int teardown; /* it is going away: no JavaScript any more */
+ int constructing; /* the module is making an object: without it the
+ classes refuse new */
+ napi_ref model_class, chat_class, reply_class;
+ struct janas_node_model *models; /* those whose engine runs */
+};
+
+/* What the engine's thread gives back: a job, or a message of a reply.
+ The first member of both. */
+#define JANAS_NODE_BACK_JOB 0 /* a job is done */
+#define JANAS_NODE_BACK_TEXT 1 /* a piece of a reply */
+#define JANAS_NODE_BACK_PROGRESS 2 /* a block of a reply's prompt read */
+struct janas_node_back {
+ int kind;
+ struct janas_node_back *next; /* undelivered, when the environment went */
+};
+
+/* A job for the engine's thread. */
+struct janas_node_job {
+ struct janas_node_back back;
+ struct janas_node_job *next; /* in the queue */
+ struct janas_node_model *m;
+ /* on the engine's thread: the work, which sets rc (and error) */
+ void (*run)(struct janas_node_job *j);
+ /* on JavaScript's: the value its promise resolves with (NULL:
+ undefined); called only when rc is not negative */
+ napi_value (*value)(napi_env env, struct janas_node_job *j);
+ /* on JavaScript's, after its promise is settled (may be NULL) */
+ void (*after)(napi_env env, struct janas_node_job *j);
+ /* frees data, and nothing else (NULL: free) */
+ void (*drop)(void *data);
+ napi_deferred deferred; /* the promise it settles, or NULL */
+ int last; /* the engine's thread ends after it */
+ int32_t rc;
+ char error[512];
+ void *data;
+};
+
+/* A piece of a reply, or how much of its prompt is read. */
+struct janas_node_msg {
+ struct janas_node_back back;
+ struct janas_node_msg *next; /* in the reply's queue */
+ struct janas_node_reply *reply;
+ int reasoning; /* the piece is the model's reasoning */
+ uint32_t read, total; /* prompt tokens read, of total */
+ size_t len;
+ char text[];
+};
+
+struct janas_node_model {
+ struct janas_node_model *next; /* in the environment's list */
+ struct janas_node_env *st;
+ int refs; /* its object, its chat's and its replies', the engine */
+ int holders; /* of them, JavaScript's objects: the last one gone closes
+ the model */
+ int pending; /* jobs posted and not back: while there are some, the
+ thread-safe function keeps the event loop alive */
+ int closing; /* close asked for, or the model did not open */
+ int engine; /* the engine's thread runs */
+ int has_chat;
+ napi_deferred *close_wait; /* close() calls waiting */
+ int n_close_wait;
+ struct janas_node_job *close_job; /* made with the engine, so that a
+ model can always be closed */
+ struct janas_node_reply *replies; /* those not over */
+ napi_threadsafe_function tsfn;
+ pthread_t thread;
+ pthread_mutex_t mu;
+ pthread_cond_t cv;
+ /* under mu */
+ struct janas_node_job *head, *tail; /* the queue */
+ struct janas_node_back *undelivered; /* the environment went first */
+ /* the engine's thread's; JavaScript's reads llm (status()) only after
+ the open is back and before close is asked for */
+ janas_llm *llm;
+ janas_llm_chat *chat;
+};
+
+struct janas_node_reply {
+ struct janas_node_reply *next; /* in the model's list, until it is over */
+ struct janas_node_model *m;
+ int refs; /* its object, and its job until the job is back */
+ int gone; /* its object was collected */
+ atomic_int stop; /* asked to stop: read by the engine's thread */
+ int ended, error_given, returned;
+ int32_t rc;
+ char error[512];
+ int stopped; /* it ended because it was asked to */
+ struct janas_llm_chat_stats st;
+ struct janas_node_msg *q, *q_tail; /* pieces not taken yet */
+ napi_deferred *wait; /* next() calls waiting */
+ int n_wait, cap_wait;
+ napi_deferred *stats_wait; /* stats() calls waiting */
+ int n_stats_wait, cap_stats_wait;
+ napi_ref signal, listener; /* an AbortSignal and the listener on it */
+ napi_ref chat; /* the chat's object, until the reply is over */
+ int collect; /* text() took the pieces: the answer's */
+ char *answer; /* text so far */
+ size_t answer_len, answer_cap;
+ napi_deferred *text_wait; /* text() calls waiting */
+ int n_text_wait, cap_text_wait;
+ /* what is sent, read by the engine's thread */
+ int load; /* janas_llm_chat_load, else janas_llm_chat_send */
+ char *text;
+ size_t len;
+ int32_t n;
+ int32_t *roles;
+ char **texts;
+ int32_t *lens;
+};
+
+struct janas_node_chat {
+ struct janas_node_model *m;
+ int closed;
+ struct janas_llm_chat_params p; /* as last set, for set() to change */
+};
+
+/* addon.c: the environment, values, errors, options */
+struct janas_node_env *janas_node_env(napi_env env);
+void janas_node_env_unref(struct janas_node_env *st);
+napi_value janas_node_undefined(napi_env env);
+napi_value janas_node_string(napi_env env, const char *s, size_t len);
+napi_value janas_node_number(napi_env env, double v);
+napi_value janas_node_bool(napi_env env, int v);
+void janas_node_put(napi_env env, napi_value obj, const char *name,
+ napi_value v);
+const char *janas_node_code(int32_t rc);
+napi_value janas_node_error(napi_env env, int32_t rc, const char *msg);
+/* throw, and return NULL for the callback to return */
+napi_value janas_node_throw(napi_env env, int32_t rc, const char *msg);
+napi_value janas_node_type_error(napi_env env, const char *fmt, ...)
+ __attribute__((format(printf, 2, 3)));
+/* a promise and its deferred; one already settled */
+napi_value janas_node_promise(napi_env env, napi_deferred *d);
+napi_value janas_node_resolved(napi_env env, napi_value v);
+napi_value janas_node_rejected(napi_env env, napi_value err);
+/* the classes' tags: an object of one is never taken for another's */
+extern const napi_type_tag janas_node_model_tag, janas_node_chat_tag,
+ janas_node_reply_tag;
+/* an object of a class, tagged and wrapping native, fin called when it is
+ collected; NULL when it could not be made (fin not called then) */
+napi_value janas_node_new(napi_env env, napi_ref cls, const napi_type_tag *tag,
+ void *native, napi_finalize fin);
+/* the classes' constructor: refuses new from JavaScript (its data says
+ where an object of the class comes from) */
+napi_value janas_node_constructor(napi_env env, napi_callback_info info);
+/* the native object of this, and the arguments (argc in-out, may be NULL);
+ NULL after throwing when this is not an object of the class */
+void *janas_node_self(napi_env env, napi_callback_info info,
+ const napi_type_tag *tag, size_t *argc, napi_value *argv,
+ const char *what);
+/* a string's UTF-8 bytes, NUL-terminated, malloc'd; NULL when v is not a
+ string (nothing thrown) or memory ran out (*len SIZE_MAX) */
+char *janas_node_text(napi_env env, napi_value v, size_t *len);
+/*
+ * Options, held to the names known: janas_node_options throws a TypeError
+ * for anything but an object, undefined or null, and for a name it does not
+ * know, and returns -1 then (0 otherwise). The getters return 1 with the
+ * value, 0 when the option is absent (undefined), -1 after throwing a
+ * TypeError when it has another type.
+ */
+int janas_node_options(napi_env env, napi_value obj, const char *what,
+ const char *const *known);
+int janas_node_opt(napi_env env, napi_value obj, const char *what,
+ const char *name, napi_valuetype type, napi_value *v);
+int janas_node_opt_number(napi_env env, napi_value obj, const char *what,
+ const char *name, double lo, double hi, double *out);
+int janas_node_opt_int(napi_env env, napi_value obj, const char *what,
+ const char *name, int64_t lo, int64_t hi, int64_t *out);
+int janas_node_opt_bool(napi_env env, napi_value obj, const char *what,
+ const char *name, int *out);
+/* *out malloc'd */
+int janas_node_opt_string(napi_env env, napi_value obj, const char *what,
+ const char *name, char **out);
+
+/* engine.c: the engine's thread, its jobs, a model's life */
+struct janas_node_model *janas_node_engine(napi_env env,
+ struct janas_node_env *st);
+struct janas_node_job *janas_node_job(struct janas_node_model *m,
+ void (*run)(struct janas_node_job *j));
+void janas_node_post(napi_env env, struct janas_node_job *j);
+/* on the engine's thread */
+void janas_node_give(struct janas_node_model *m, struct janas_node_back *b);
+void janas_node_ref(struct janas_node_model *m);
+void janas_node_unref(napi_env env, struct janas_node_model *m);
+void janas_node_hold(struct janas_node_model *m);
+void janas_node_release(napi_env env, struct janas_node_model *m);
+/* asks the engine to close the model; d (may be NULL) settles when it has */
+void janas_node_close(napi_env env, struct janas_node_model *m,
+ napi_deferred d);
+void janas_node_teardown(struct janas_node_env *st);
+
+/* model.c */
+napi_value janas_node_model_class(napi_env env);
+napi_value janas_node_open(napi_env env, napi_callback_info info);
+
+/* chat.c */
+napi_value janas_node_chat_class(napi_env env);
+napi_value janas_node_chat(napi_env env, struct janas_node_model *m,
+ napi_value options);
+
+/* reply.c */
+napi_value janas_node_reply_class(napi_env env);
+/* a reply of c (its object chat_obj, kept alive while the reply runs) */
+napi_value janas_node_reply(napi_env env, struct janas_node_chat *c,
+ napi_value chat_obj, int load, napi_value what,
+ napi_value options);
+void janas_node_reply_back(napi_env env, struct janas_node_msg *msg);
+/* asks every reply of the model not over to stop */
+void janas_node_stop_replies(struct janas_node_model *m);
+
+#endif
diff --git a/src/node/reply.c b/src/node/reply.c
new file mode 100644
index 0000000..960e5cf
--- /dev/null
+++ b/src/node/reply.c
@@ -0,0 +1,753 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * reply.c - the Reply class: a reply the model writes, read piece by piece
+ * as an async iterator (for await), or whole (text()), stopped (stop(), an
+ * AbortSignal, or leaving the loop), and counted (stats()).
+ *
+ * The engine's thread sends the message (janas_llm_chat_send) or loads the
+ * conversation (janas_llm_chat_load), then reads the pieces with
+ * janas_llm_chat_next and gives each back as it comes; JavaScript's thread
+ * hands them to the next() waiting, or keeps them for the next() to come.
+ * The job comes back after its last piece, with the reply's counters.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "node/node_impl.h"
+
+struct reply_job {
+ struct janas_node_reply *r;
+ int stopped;
+ int have_stats;
+ struct janas_llm_chat_stats st;
+};
+
+/* --- JavaScript's thread: the reply's state ---------------------------- */
+
+static int push(napi_deferred **a, int *n, int *cap, napi_deferred d)
+{
+ if (*n == *cap) {
+ int c = *cap ? *cap * 2 : 4;
+ napi_deferred *b = realloc(*a, (size_t)c * sizeof(*b));
+ if (!b)
+ return -1;
+ *a = b;
+ *cap = c;
+ }
+ (*a)[(*n)++] = d;
+ return 0;
+}
+
+static napi_deferred shift(napi_deferred *a, int *n)
+{
+ napi_deferred d = a[0];
+ memmove(a, a + 1, (size_t)(--*n) * sizeof(*a));
+ return d;
+}
+
+static napi_value iter_result(napi_env env, napi_value value, int done)
+{
+ napi_value o;
+ if (napi_create_object(env, &o) != napi_ok)
+ return NULL;
+ janas_node_put(env, o, "value", value ? value : janas_node_undefined(env));
+ janas_node_put(env, o, "done", janas_node_bool(env, done));
+ return o;
+}
+
+static napi_value piece_value(napi_env env, struct janas_node_msg *msg)
+{
+ napi_value o;
+ if (napi_create_object(env, &o) != napi_ok)
+ return NULL;
+ if (msg->back.kind == JANAS_NODE_BACK_TEXT) {
+ janas_node_put(env, o, "type",
+ janas_node_string(env, "text", JANAS_NAPI_AUTO_LENGTH));
+ janas_node_put(env, o, "text",
+ janas_node_string(env, msg->text, msg->len));
+ janas_node_put(env, o, "reasoning",
+ janas_node_bool(env, msg->reasoning));
+ } else {
+ janas_node_put(
+ env, o, "type",
+ janas_node_string(env, "progress", JANAS_NAPI_AUTO_LENGTH));
+ janas_node_put(env, o, "read", janas_node_number(env, msg->read));
+ janas_node_put(env, o, "total", janas_node_number(env, msg->total));
+ }
+ return o;
+}
+
+static const char *finish_name(const struct janas_node_reply *r)
+{
+ if (r->stopped)
+ return "stopped";
+ switch (r->st.finish) {
+ case JANAS_LLM_FINISH_STOP:
+ return "stop";
+ case JANAS_LLM_FINISH_LENGTH:
+ return "length";
+ case JANAS_LLM_FINISH_CONTEXT:
+ return "context";
+ case JANAS_LLM_FINISH_TOOLS:
+ return "tools";
+ case JANAS_LLM_FINISH_ERROR:
+ return "error";
+ default:
+ return r->rc < 0 ? "error" : NULL;
+ }
+}
+
+static napi_value stats_value(napi_env env, const struct janas_node_reply *r)
+{
+ const struct janas_llm_chat_stats *s = &r->st;
+ napi_value o;
+ if (napi_create_object(env, &o) != napi_ok)
+ return NULL;
+ const char *f = finish_name(r);
+ napi_value fin = NULL;
+ if (f)
+ fin = janas_node_string(env, f, JANAS_NAPI_AUTO_LENGTH);
+ else
+ napi_get_null(env, &fin);
+ janas_node_put(env, o, "finish", fin);
+ struct {
+ const char *name;
+ double v;
+ } n[] = {
+ {"promptTokens", s->prompt_tokens},
+ {"cachedTokens", s->cached_tokens},
+ {"inputTokens", s->input_tokens},
+ {"outputTokens", s->output_tokens},
+ {"reasoningTokens", s->reasoning_tokens},
+ {"contextUsed", s->context_used},
+ {"contextSize", s->context_size},
+ {"drafted", s->drafted},
+ {"accepted", s->accepted},
+ {"inputSeconds", s->input_seconds},
+ {"outputSeconds", s->output_seconds},
+ {"totalSeconds", s->total_seconds},
+ {"firstTokenSeconds", s->first_token_seconds},
+ {"inputThreads", s->input_threads},
+ {"outputThreads", s->output_threads},
+ {"expertsUsed", (double)s->experts_used},
+ {"expertsRead", (double)s->experts_read},
+ {"bytesRead", (double)s->bytes_read},
+ {"ioWaitSeconds", s->io_wait_seconds},
+ {"peakRssBytes", (double)s->peak_rss_bytes},
+ };
+ for (size_t i = 0; i < sizeof(n) / sizeof(n[0]); i++)
+ janas_node_put(env, o, n[i].name, janas_node_number(env, n[i].v));
+ janas_node_put(env, o, "reasoningCut",
+ janas_node_bool(env, s->reasoning_cut));
+ return o;
+}
+
+static napi_value reply_error(napi_env env, const struct janas_node_reply *r)
+{
+ return janas_node_error(env, r->rc, r->error);
+}
+
+static void free_queue(struct janas_node_reply *r)
+{
+ while (r->q) {
+ struct janas_node_msg *msg = r->q;
+ r->q = msg->next;
+ free(msg);
+ }
+ r->q_tail = NULL;
+}
+
+static void unwatch_signal(napi_env env, struct janas_node_reply *r)
+{
+ if (!r->signal)
+ return;
+ napi_value signal, fn, rm, argv[2];
+ if (napi_get_reference_value(env, r->signal, &signal) == napi_ok &&
+ napi_get_reference_value(env, r->listener, &fn) == napi_ok &&
+ napi_get_named_property(env, signal, "removeEventListener", &rm) ==
+ napi_ok) {
+ argv[0] = janas_node_string(env, "abort", JANAS_NAPI_AUTO_LENGTH);
+ argv[1] = fn;
+ if (napi_call_function(env, signal, rm, 2, argv, NULL) != napi_ok) {
+ napi_value ignored;
+ napi_get_and_clear_last_exception(env, &ignored);
+ }
+ }
+ napi_delete_reference(env, r->signal);
+ napi_delete_reference(env, r->listener);
+ r->signal = r->listener = NULL;
+}
+
+static void unlink_reply(struct janas_node_reply *r)
+{
+ for (struct janas_node_reply **p = &r->m->replies; *p; p = &(*p)->next)
+ if (*p == r) {
+ *p = r->next;
+ break;
+ }
+}
+
+static void reply_unref(napi_env env, struct janas_node_reply *r)
+{
+ if (--r->refs > 0)
+ return;
+ struct janas_node_model *m = r->m;
+ int js = env && !m->st->teardown;
+ free_queue(r);
+ if (js) {
+ unwatch_signal(env, r);
+ if (r->chat)
+ napi_delete_reference(env, r->chat);
+ }
+ free(r->wait);
+ free(r->stats_wait);
+ free(r->text_wait);
+ free(r->answer);
+ free(r->text);
+ if (r->texts)
+ for (int32_t i = 0; i < r->n; i++)
+ free(r->texts[i]);
+ free(r->texts);
+ free(r->roles);
+ free(r->lens);
+ free(r);
+ janas_node_unref(env, m);
+}
+
+static int append_answer(struct janas_node_reply *r, const char *s, size_t len)
+{
+ if (r->answer_len + len + 1 > r->answer_cap) {
+ size_t c = r->answer_cap ? r->answer_cap : 256;
+ while (c < r->answer_len + len + 1)
+ c *= 2;
+ char *b = realloc(r->answer, c);
+ if (!b)
+ return -1;
+ r->answer = b;
+ r->answer_cap = c;
+ }
+ memcpy(r->answer + r->answer_len, s, len);
+ r->answer_len += len;
+ r->answer[r->answer_len] = 0;
+ return 0;
+}
+
+/* a piece for text(): the answer's text, not the reasoning */
+static void collect(struct janas_node_reply *r, struct janas_node_msg *msg)
+{
+ if (msg->back.kind == JANAS_NODE_BACK_TEXT && !msg->reasoning &&
+ append_answer(r, msg->text, msg->len) < 0 && r->rc >= 0) {
+ r->rc = JANAS_LLM_ENOMEM;
+ snprintf(r->error, sizeof(r->error), "janas: out of memory");
+ }
+}
+
+void janas_node_reply_back(napi_env env, struct janas_node_msg *msg)
+{
+ struct janas_node_reply *r = msg->reply;
+ if (r->gone || r->returned) {
+ free(msg);
+ return;
+ }
+ if (r->collect) {
+ collect(r, msg);
+ free(msg);
+ return;
+ }
+ if (r->n_wait) {
+ napi_deferred d = shift(r->wait, &r->n_wait);
+ napi_value v = iter_result(env, piece_value(env, msg), 0);
+ free(msg);
+ if (v)
+ napi_resolve_deferred(env, d, v);
+ else
+ napi_reject_deferred(env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM,
+ "janas: out of memory"));
+ return;
+ }
+ msg->next = NULL;
+ if (r->q_tail)
+ r->q_tail->next = msg;
+ else
+ r->q = msg;
+ r->q_tail = msg;
+}
+
+/* the waiting promises, once the reply is over (or left) */
+static void settle(napi_env env, struct janas_node_reply *r)
+{
+ while (r->n_wait) {
+ napi_deferred d = shift(r->wait, &r->n_wait);
+ if (r->rc < 0 && !r->error_given && !r->returned) {
+ r->error_given = 1;
+ napi_reject_deferred(env, d, reply_error(env, r));
+ } else
+ napi_resolve_deferred(env, d, iter_result(env, NULL, 1));
+ }
+ if (!r->ended)
+ return;
+ while (r->n_text_wait) {
+ napi_deferred d = shift(r->text_wait, &r->n_text_wait);
+ if (r->rc < 0)
+ napi_reject_deferred(env, d, reply_error(env, r));
+ else
+ napi_resolve_deferred(
+ env, d, janas_node_string(env, r->answer, r->answer_len));
+ }
+ while (r->n_stats_wait)
+ napi_resolve_deferred(env, shift(r->stats_wait, &r->n_stats_wait),
+ stats_value(env, r));
+}
+
+static void reply_after(napi_env env, struct janas_node_job *j)
+{
+ struct reply_job *rj = j->data;
+ struct janas_node_reply *r = rj->r;
+ r->ended = 1;
+ if (r->rc >= 0) /* text() may have run out of memory meanwhile */
+ r->rc = j->rc;
+ if (j->rc < 0)
+ memcpy(r->error, j->error, sizeof(r->error));
+ r->stopped = rj->stopped;
+ if (rj->have_stats)
+ r->st = rj->st;
+ unlink_reply(r);
+ unwatch_signal(env, r);
+ if (r->chat) {
+ napi_delete_reference(env, r->chat);
+ r->chat = NULL;
+ }
+ settle(env, r);
+ reply_unref(env, r); /* the job's */
+}
+
+void janas_node_stop_replies(struct janas_node_model *m)
+{
+ for (struct janas_node_reply *r = m->replies; r; r = r->next)
+ atomic_store(&r->stop, 1);
+}
+
+/* --- the engine's thread ------------------------------------------------ */
+
+static int give_piece(struct janas_node_model *m, struct janas_node_reply *r,
+ int kind, const char *text, size_t len, int reasoning,
+ uint32_t read, uint32_t total)
+{
+ struct janas_node_msg *msg = malloc(sizeof(*msg) + len);
+ if (!msg)
+ return -1;
+ memset(msg, 0, sizeof(*msg));
+ msg->back.kind = kind;
+ msg->reply = r;
+ msg->reasoning = reasoning;
+ msg->read = read;
+ msg->total = total;
+ msg->len = len;
+ if (len)
+ memcpy(msg->text, text, len);
+ janas_node_give(m, &msg->back);
+ return 0;
+}
+
+static void reply_run(struct janas_node_job *j)
+{
+ struct reply_job *rj = j->data;
+ struct janas_node_reply *r = rj->r;
+ struct janas_node_model *m = j->m;
+ janas_llm_chat *c = m->chat;
+ if (atomic_load(&r->stop)) { /* stopped before it began */
+ rj->stopped = 1;
+ return;
+ }
+ if (!c) {
+ j->rc = JANAS_NODE_ECLOSED;
+ snprintf(j->error, sizeof(j->error), "janas: the chat is closed");
+ return;
+ }
+ int32_t rc =
+ r->load ? janas_llm_chat_load(c, r->n, r->roles,
+ (const char *const *)r->texts, r->lens)
+ : janas_llm_chat_send(c, r->text, (int32_t)r->len);
+ char buf[4096];
+ while (rc == JANAS_LLM_OK) {
+ if (atomic_load_explicit(&r->stop, memory_order_relaxed)) {
+ rj->stopped = 1;
+ break;
+ }
+ int32_t len = 0;
+ rc = janas_llm_chat_next(c, buf, sizeof(buf), &len);
+ if (rc != JANAS_LLM_OK)
+ break;
+ int lost;
+ if (len > 0) {
+ lost = give_piece(m, r, JANAS_NODE_BACK_TEXT, buf, (size_t)len,
+ janas_llm_chat_thinking(c), 0, 0);
+ } else { /* a block of the prompt read, or nothing to say yet */
+ struct janas_llm_chat_stats s = {.size = sizeof(s)};
+ lost = janas_llm_chat_stats(c, &s) == JANAS_LLM_OK &&
+ s.stage == JANAS_LLM_STAGE_INPUT
+ ? give_piece(m, r, JANAS_NODE_BACK_PROGRESS, NULL, 0, 0,
+ s.input_done, s.input_tokens)
+ : 0;
+ }
+ if (lost) { /* a piece missing would be a wrong text */
+ rc = JANAS_LLM_ENOMEM;
+ snprintf(j->error, sizeof(j->error),
+ "janas: out of memory, the reply cut short");
+ break;
+ }
+ }
+ if (rc == JANAS_LLM_DONE)
+ rc = JANAS_LLM_OK;
+ if (rc < 0 && !j->error[0])
+ snprintf(j->error, sizeof(j->error), "%s", janas_llm_last_error());
+ j->rc = rc;
+ rj->st.size = sizeof(rj->st);
+ rj->have_stats = janas_llm_chat_stats(c, &rj->st) == JANAS_LLM_OK;
+}
+
+/* --- the class ---------------------------------------------------------- */
+
+static struct janas_node_reply *self(napi_env env, napi_callback_info info,
+ size_t *argc, napi_value *argv,
+ const char *what)
+{
+ return janas_node_self(env, info, &janas_node_reply_tag, argc, argv, what);
+}
+
+static napi_value reply_next(napi_env env, napi_callback_info info)
+{
+ struct janas_node_reply *r = self(env, info, NULL, NULL, "Reply.next");
+ if (!r)
+ return NULL;
+ if (r->q) {
+ struct janas_node_msg *msg = r->q;
+ r->q = msg->next;
+ if (!r->q)
+ r->q_tail = NULL;
+ napi_value v = iter_result(env, piece_value(env, msg), 0);
+ free(msg);
+ return janas_node_resolved(env, v);
+ }
+ if (r->ended || r->returned || r->collect) {
+ if (r->rc < 0 && !r->error_given && !r->returned && !r->collect) {
+ r->error_given = 1;
+ return janas_node_rejected(env, reply_error(env, r));
+ }
+ return janas_node_resolved(env, iter_result(env, NULL, 1));
+ }
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p && push(&r->wait, &r->n_wait, &r->cap_wait, d) < 0) {
+ napi_reject_deferred(
+ env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM, "janas: out of memory"));
+ }
+ return p;
+}
+
+/* leaving a for await loop early (break, return, throw) */
+static napi_value reply_return(napi_env env, napi_callback_info info)
+{
+ size_t argc = 1;
+ napi_value argv[1] = {NULL};
+ struct janas_node_reply *r = self(env, info, &argc, argv, "Reply.return");
+ if (!r)
+ return NULL;
+ atomic_store(&r->stop, 1);
+ r->returned = 1;
+ free_queue(r);
+ settle(env, r);
+ return janas_node_resolved(env, iter_result(env, argc ? argv[0] : NULL, 1));
+}
+
+static napi_value reply_iterator(napi_env env, napi_callback_info info)
+{
+ napi_value self_obj = NULL;
+ napi_get_cb_info(env, info, NULL, NULL, &self_obj, NULL);
+ return self_obj;
+}
+
+static napi_value reply_stop(napi_env env, napi_callback_info info)
+{
+ struct janas_node_reply *r = self(env, info, NULL, NULL, "Reply.stop");
+ if (r)
+ atomic_store(&r->stop, 1);
+ return NULL;
+}
+
+static napi_value reply_text(napi_env env, napi_callback_info info)
+{
+ struct janas_node_reply *r = self(env, info, NULL, NULL, "Reply.text");
+ if (!r)
+ return NULL;
+ if (!r->collect) { /* the pieces from now on, and those kept */
+ r->collect = 1;
+ while (r->q) {
+ struct janas_node_msg *msg = r->q;
+ r->q = msg->next;
+ collect(r, msg);
+ free(msg);
+ }
+ r->q_tail = NULL;
+ settle(env, r); /* next() calls waiting: done, the text took them */
+ }
+ if (r->ended) {
+ if (r->rc < 0)
+ return janas_node_rejected(env, reply_error(env, r));
+ return janas_node_resolved(
+ env, janas_node_string(env, r->answer, r->answer_len));
+ }
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p && push(&r->text_wait, &r->n_text_wait, &r->cap_text_wait, d) < 0)
+ napi_reject_deferred(
+ env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM, "janas: out of memory"));
+ return p;
+}
+
+static napi_value reply_stats(napi_env env, napi_callback_info info)
+{
+ struct janas_node_reply *r = self(env, info, NULL, NULL, "Reply.stats");
+ if (!r)
+ return NULL;
+ if (r->ended)
+ return janas_node_resolved(env, stats_value(env, r));
+ napi_deferred d;
+ napi_value p = janas_node_promise(env, &d);
+ if (p && push(&r->stats_wait, &r->n_stats_wait, &r->cap_stats_wait, d) < 0)
+ napi_reject_deferred(
+ env, d,
+ janas_node_error(env, JANAS_LLM_ENOMEM, "janas: out of memory"));
+ return p;
+}
+
+static void reply_finalize(napi_env env, void *data, void *hint)
+{
+ (void)hint;
+ struct janas_node_reply *r = data;
+ struct janas_node_model *m = r->m;
+ atomic_store(&r->stop, 1);
+ r->gone = 1; /* no promise of its can be waited for: none was pending */
+ free_queue(r);
+ janas_node_ref(m); /* m outlives r's last reference */
+ reply_unref(env, r);
+ janas_node_release(env, m); /* the object's hold */
+ janas_node_unref(env, m);
+}
+
+static napi_value on_abort(napi_env env, napi_callback_info info)
+{
+ void *data = NULL;
+ napi_get_cb_info(env, info, NULL, NULL, NULL, &data);
+ if (data)
+ atomic_store(&((struct janas_node_reply *)data)->stop, 1);
+ return NULL;
+}
+
+static int watch_signal(napi_env env, struct janas_node_reply *r,
+ napi_value signal)
+{
+ napi_value aborted, add, fn, argv[2];
+ napi_valuetype t;
+ bool b = false;
+ if (napi_typeof(env, signal, &t) != napi_ok || t != napi_object ||
+ napi_get_named_property(env, signal, "aborted", &aborted) != napi_ok ||
+ napi_get_named_property(env, signal, "addEventListener", &add) !=
+ napi_ok ||
+ napi_typeof(env, add, &t) != napi_ok || t != napi_function) {
+ janas_node_type_error(env, "janas: the signal must be an AbortSignal");
+ return -1;
+ }
+ napi_get_value_bool(env, aborted, &b);
+ if (b) {
+ atomic_store(&r->stop, 1);
+ return 0;
+ }
+ if (napi_create_function(env, "abort", JANAS_NAPI_AUTO_LENGTH, on_abort, r,
+ &fn) != napi_ok)
+ return -1;
+ argv[0] = janas_node_string(env, "abort", JANAS_NAPI_AUTO_LENGTH);
+ argv[1] = fn;
+ if (napi_call_function(env, signal, add, 2, argv, NULL) != napi_ok)
+ return -1;
+ if (napi_create_reference(env, signal, 1, &r->signal) != napi_ok ||
+ napi_create_reference(env, fn, 1, &r->listener) != napi_ok) {
+ janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ return -1;
+ }
+ return 0;
+}
+
+static int message_role(const char *s)
+{
+ static const char *const roles[] = {"system", "user", "assistant", "tool"};
+ static const int32_t ids[] = {JANAS_LLM_ROLE_SYSTEM, JANAS_LLM_ROLE_USER,
+ JANAS_LLM_ROLE_ASSISTANT,
+ JANAS_LLM_ROLE_TOOL};
+ for (int i = 0; i < 4; i++)
+ if (!strcmp(s, roles[i]))
+ return ids[i];
+ return -1;
+}
+
+static int messages(napi_env env, napi_value v, struct janas_node_reply *r)
+{
+ bool array = false;
+ uint32_t n = 0;
+ if (!v || napi_is_array(env, v, &array) != napi_ok || !array ||
+ napi_get_array_length(env, v, &n) != napi_ok || n == 0 ||
+ n > INT32_MAX) {
+ janas_node_type_error(env, "janas: chat.load(messages): an array of "
+ "{role, content}, one at least");
+ return -1;
+ }
+ r->roles = calloc(n, sizeof(*r->roles));
+ r->texts = calloc(n, sizeof(*r->texts));
+ r->lens = calloc(n, sizeof(*r->lens));
+ if (!r->roles || !r->texts || !r->lens) {
+ janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ return -1;
+ }
+ r->n = (int32_t)n;
+ for (uint32_t i = 0; i < n; i++) {
+ napi_value el, role, content;
+ napi_valuetype t;
+ size_t len = 0;
+ char *s = NULL;
+ if (napi_get_element(env, v, i, &el) != napi_ok ||
+ napi_typeof(env, el, &t) != napi_ok || t != napi_object ||
+ napi_get_named_property(env, el, "role", &role) != napi_ok ||
+ napi_get_named_property(env, el, "content", &content) != napi_ok ||
+ !(s = janas_node_text(env, role, &len)) ||
+ (r->roles[i] = message_role(s)) < 0) {
+ free(s);
+ janas_node_type_error(env,
+ "janas: chat.load: message %u: a role "
+ "(system, user, assistant, tool) and a "
+ "content",
+ i);
+ return -1;
+ }
+ free(s);
+ r->texts[i] = janas_node_text(env, content, &len);
+ if (!r->texts[i] || len > INT32_MAX) {
+ janas_node_type_error(env,
+ "janas: chat.load: message %u: the content "
+ "must be a string",
+ i);
+ return -1;
+ }
+ r->lens[i] = (int32_t)len;
+ }
+ return 0;
+}
+
+static void reply_job_drop(void *data)
+{
+ free(data);
+}
+
+napi_value janas_node_reply(napi_env env, struct janas_node_chat *c,
+ napi_value chat_obj, int load, napi_value what,
+ napi_value options)
+{
+ static const char *const known[] = {"signal", NULL};
+ struct janas_node_model *m = c->m;
+ const char *name = load ? "chat.load" : "chat.send";
+ struct janas_node_reply *r = calloc(1, sizeof(*r));
+ struct reply_job *rj = calloc(1, sizeof(*rj));
+ struct janas_node_job *j = janas_node_job(m, reply_run);
+ if (!r || !rj || !j) {
+ free(r);
+ free(rj);
+ free(j);
+ return janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ }
+ r->m = m;
+ janas_node_ref(m); /* the reply's, released with it */
+ r->refs = 1; /* until the object is made: then the object's */
+ r->load = load;
+ int bad = 0;
+ if (load)
+ bad = messages(env, what, r) < 0;
+ else if (!(r->text = janas_node_text(env, what, &r->len)) ||
+ r->len > INT32_MAX) {
+ janas_node_type_error(env, "janas: chat.send(text): the text must be "
+ "a string");
+ bad = 1;
+ }
+ napi_value signal = NULL;
+ int has_signal = 0;
+ if (!bad && janas_node_options(env, options, name, known) < 0)
+ bad = 1;
+ if (!bad && (has_signal = janas_node_opt(env, options, name, "signal",
+ napi_object, &signal)) < 0)
+ bad = 1;
+ napi_value obj = NULL;
+ if (!bad) {
+ obj = janas_node_new(env, m->st->reply_class, &janas_node_reply_tag, r,
+ reply_finalize);
+ if (!obj) {
+ janas_node_throw(env, JANAS_LLM_ENOMEM, "janas: out of memory");
+ bad = 1;
+ }
+ }
+ if (bad) {
+ free(rj);
+ free(j);
+ reply_unref(env, r);
+ return NULL;
+ }
+ janas_node_hold(m); /* the object's, released when it is collected */
+ if (has_signal > 0 && watch_signal(env, r, signal) < 0) {
+ /* the object exists: it ends at once, with nothing written */
+ atomic_store(&r->stop, 1);
+ r->ended = 1;
+ free(rj);
+ free(j);
+ return NULL;
+ }
+ if (chat_obj)
+ napi_create_reference(env, chat_obj, 1, &r->chat);
+ rj->r = r;
+ j->data = rj;
+ j->drop = reply_job_drop;
+ j->after = reply_after;
+ r->refs++; /* the job's, until it is back */
+ r->next = m->replies;
+ m->replies = r;
+ janas_node_post(env, j);
+ return obj;
+}
+
+napi_value janas_node_reply_class(napi_env env)
+{
+ napi_value global, symbol, iterator;
+ if (napi_get_global(env, &global) != napi_ok ||
+ napi_get_named_property(env, global, "Symbol", &symbol) != napi_ok ||
+ napi_get_named_property(env, symbol, "asyncIterator", &iterator) !=
+ napi_ok)
+ return NULL;
+ const napi_property_attributes method = napi_writable | napi_configurable;
+ napi_property_descriptor d[] = {
+ {.utf8name = "next", .method = reply_next, .attributes = method},
+ {.utf8name = "return", .method = reply_return, .attributes = method},
+ {.name = iterator, .method = reply_iterator, .attributes = method},
+ {.utf8name = "stop", .method = reply_stop, .attributes = method},
+ {.utf8name = "text", .method = reply_text, .attributes = method},
+ {.utf8name = "stats", .method = reply_stats, .attributes = method},
+ };
+ napi_value cls = NULL;
+ if (napi_define_class(env, "Reply", JANAS_NAPI_AUTO_LENGTH,
+ janas_node_constructor,
+ (void *)"a Reply comes from chat.send() or "
+ "chat.load()",
+ sizeof(d) / sizeof(d[0]), d, &cls) != napi_ok)
+ return NULL;
+ return cls;
+}
diff --git a/tests/node_check.c b/tests/node_check.c
new file mode 100644
index 0000000..9e4b3a8
--- /dev/null
+++ b/tests/node_check.c
@@ -0,0 +1,284 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * node_check.c - the module for Node.js against the library, on a model:
+ *
+ * node_check model.jns [seconds]
+ *
+ * First the library itself, here: a message and its reply, then the whole
+ * conversation loaded with a second message, greedy, on the CPU alone
+ * (JANAS_GPU=0, JANAS_NPU=0, for the same numbers in both processes). Then
+ * node, through janas.node, says the same and much more: the replies must
+ * be the same text, byte for byte, streamed and read whole, after a reset
+ * and in a new chat; and leaving the loop, an AbortSignal (fired, and
+ * aborted before), two replies asked at once, a prompt of several blocks
+ * (progress pieces), reasoning on and off, the errors, closing twice, and a
+ * model left open when node leaves. Not one of the tests run by build.sh:
+ * it needs a model (Qwen3-0.6B takes about a minute).
+ */
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "janas/llm.h"
+
+#ifdef _WIN32
+int main(void)
+{
+ printf("node_check: the module is built on Linux only\n");
+ return 0;
+}
+#else
+#include "node_run.h"
+
+static const char p1[] = "Write one sentence about the sea.";
+static const char p2[] = "And one about the mountains.";
+
+static const char script[] =
+ "'use strict';\n"
+ "const assert = require('node:assert/strict');\n"
+ "const [addon, path, P1, P2] = process.argv.slice(1);\n"
+ "const janas = require(addon);\n"
+ "const hex = (s) => Buffer.from(s, 'utf8').toString('hex');\n"
+ "const say = (k, v) => process.stdout.write(k + ' ' + v + '\\n');\n"
+ "const pieces = async (r) => { const p = []; for await (const x of r) "
+ "p.push(x); return p; };\n"
+ "const answer = (p) => p.filter((x) => x.type === 'text' && "
+ "!x.reasoning).map((x) => x.text).join('');\n"
+ "const greedy = { temperature: 0, thinking: false, maxReply: 48 };\n"
+ "(async () => {\n"
+ " const m = await janas.open(path, { context: 4096 });\n"
+ " assert.equal(m.status().open, true);\n"
+ " say('model', JSON.stringify(m.name) + ' reasons ' + m.reasons);\n"
+ " const chat = await m.chat(greedy);\n"
+ " await assert.rejects(m.chat(), { code: 'EBUSY' });\n"
+ /* the reply streamed, then the conversation loaded */
+ " const r1 = chat.send(P1);\n"
+ " const t1 = answer(await pieces(r1));\n"
+ " say('t1', hex(t1));\n"
+ " const s1 = await r1.stats();\n"
+ " assert.ok(s1.outputTokens > 0 && ['stop', 'length'].includes("
+ "s1.finish), JSON.stringify(s1));\n"
+ " const r2 = chat.load([{ role: 'user', content: P1 },\n"
+ " { role: 'assistant', content: t1 }, { role: 'user', content: P2 "
+ "}]);\n"
+ " say('t2', hex(await r2.text()));\n"
+ " const s2 = await r2.stats();\n"
+ " say('cached', s2.cachedTokens + ' of ' + s2.promptTokens);\n"
+ " assert.ok(s2.cachedTokens > 0, 'nothing of the prompt reused');\n"
+ /* the same message after a reset, read whole */
+ " await chat.reset();\n"
+ " say('t1again', hex(await chat.send(P1).text()));\n"
+ /* leaving the loop, an AbortSignal fired, one aborted before */
+ " await chat.reset();\n"
+ " const r4 = chat.send('Count from one to two hundred, one number a "
+ "line.');\n"
+ " let k = 0;\n"
+ " for await (const x of r4) if (x.type === 'text' && ++k === 3) break;\n"
+ " assert.equal((await r4.stats()).finish, 'stopped');\n"
+ " const ac = new AbortController();\n"
+ " const r5 = chat.send('Count from one to two hundred.', { signal: "
+ "ac.signal });\n"
+ " for await (const x of r5) if (x.type === 'text') ac.abort();\n"
+ " assert.equal((await r5.stats()).finish, 'stopped');\n"
+ " const ac2 = new AbortController();\n"
+ " ac2.abort();\n"
+ " assert.equal((await pieces(chat.send('Hello', { signal: ac2.signal "
+ "}))).length, 0);\n"
+ /* two at once: the second waits */
+ " await chat.reset();\n"
+ " const [a, b] = await Promise.all([chat.send('Say yes.').text(), "
+ "chat.send('Say no.').text()]);\n"
+ " assert.ok(a.length > 0 && b.length > 0);\n"
+ /* a prompt of several blocks */
+ " await chat.reset();\n"
+ " const long = 'The quick brown fox jumps over the lazy dog. '"
+ ".repeat(80) + 'How many times did the fox jump?';\n"
+ " const p7 = await pieces(chat.send(long));\n"
+ " say('progress', p7.filter((x) => x.type === 'progress').length);\n"
+ " assert.ok(p7.some((x) => x.type === 'progress'), 'no progress "
+ "piece');\n"
+ /* reasoning */
+ " if (m.reasons) {\n"
+ " await chat.reset();\n"
+ " await chat.set({ thinking: true, maxReply: 64 });\n"
+ " const p8 = await pieces(chat.send('What is 17 times 23?'));\n"
+ " assert.ok(p8.some((x) => x.type === 'text' && x.reasoning), 'no "
+ "reasoning');\n"
+ " await chat.set(greedy);\n"
+ " }\n"
+ /* errors */
+ " assert.throws(() => chat.load([]), TypeError);\n"
+ " assert.throws(() => chat.load([{ role: 'robot', content: 'x' }]), "
+ "/message 0/);\n"
+ " assert.throws(() => chat.send(7), TypeError);\n"
+ " assert.throws(() => chat.set({ temperature: -1 }), TypeError);\n"
+ " assert.throws(() => chat.send('x', { signal: {} }), "
+ "/AbortSignal/);\n"
+ /* the chat closed, another */
+ " await chat.close();\n"
+ " assert.throws(() => chat.send('x'), { code: 'ECLOSED' });\n"
+ " const chat2 = await m.chat(greedy);\n"
+ " say('t1chat2', hex(await chat2.send(P1).text()));\n"
+ /* closed twice, then nothing */
+ " await Promise.all([m.close(), m.close()]);\n"
+ " assert.equal(m.status().open, false);\n"
+ " assert.throws(() => chat2.send('x'), { code: 'ECLOSED' });\n"
+ " await assert.rejects(m.chat(), { code: 'ECLOSED' });\n"
+ /* one left open: node leaves all the same, closing it */
+ " const m2 = await janas.open(path, { context: 1024 });\n"
+ " await (await m2.chat({ ...greedy, maxReply: 8 })).send('Hi').text();\n"
+ " say('done', 1);\n"
+ "})().catch((e) => { console.error(e); process.exitCode = 1; });\n";
+
+/* the reply's answer, its reasoning left out */
+static char *reply_text(janas_llm_chat *c, int32_t rc)
+{
+ size_t len = 0, cap = 4096;
+ char *s = malloc(cap), buf[4096];
+ int32_t n;
+ while (s && rc == JANAS_LLM_OK &&
+ (rc = janas_llm_chat_next(c, buf, sizeof(buf), &n)) ==
+ JANAS_LLM_OK) {
+ if (n <= 0 || janas_llm_chat_thinking(c))
+ continue;
+ if (len + (size_t)n + 1 > cap) {
+ char *b = realloc(s, cap *= 2);
+ if (!b) {
+ free(s);
+ return NULL;
+ }
+ s = b;
+ }
+ memcpy(s + len, buf, (size_t)n);
+ len += (size_t)n;
+ }
+ if (!s || rc < 0) {
+ fprintf(stderr, "node_check: %s\n", janas_llm_last_error());
+ free(s);
+ return NULL;
+ }
+ s[len] = 0;
+ return s;
+}
+
+static char *to_hex(const char *s)
+{
+ size_t n = strlen(s);
+ char *h = malloc(2 * n + 1);
+ for (size_t i = 0; h && i < n; i++)
+ sprintf(h + 2 * i, "%02x", (unsigned char)s[i]);
+ if (h)
+ h[2 * n] = 0;
+ return h;
+}
+
+/* the line "key value" of node's output: its value is want */
+static int same(const char *out, const char *key, const char *want)
+{
+ size_t kl = strlen(key);
+ for (const char *line = out; *line;) {
+ size_t n = strcspn(line, "\n");
+ if (n > kl && !strncmp(line, key, kl) && line[kl] == ' ')
+ return n - kl - 1 == strlen(want) &&
+ !strncmp(line + kl + 1, want, n - kl - 1);
+ line += n + (line[n] == '\n');
+ }
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 2) {
+ fprintf(stderr, "usage: node_check model.jns [seconds]\n");
+ return 2;
+ }
+ int timeout_s = argc > 2 ? atoi(argv[2]) : 600;
+ char node[4096], addon[4096];
+ if (!node_find(node, sizeof(node)) || !node_addon(addon, sizeof(addon))) {
+ fprintf(stderr, "node_check: no node in the PATH, or no janas.node "
+ "beside this program\n");
+ return 2;
+ }
+ /* the same numbers in both processes: the CPU's */
+ setenv("JANAS_GPU", "0", 1);
+ setenv("JANAS_NPU", "0", 1);
+
+ struct janas_llm_params p;
+ janas_llm_params_default(&p);
+ p.n_ctx = 4096;
+ janas_llm *llm;
+ if (janas_llm_open(argv[1], &p, &llm) != JANAS_LLM_OK) {
+ fprintf(stderr, "node_check: %s\n", janas_llm_last_error());
+ return 2;
+ }
+ struct janas_llm_chat_params cp;
+ janas_llm_chat_params_default(&cp);
+ cp.temperature = 0;
+ cp.thinking = 0;
+ cp.max_reply = 48;
+ janas_llm_chat *c;
+ char *t1 = NULL, *t2 = NULL;
+ if (janas_llm_chat_create(llm, &cp, &c) == JANAS_LLM_OK) {
+ t1 = reply_text(c, janas_llm_chat_send(c, p1, -1));
+ if (t1) {
+ const int32_t roles[] = {JANAS_LLM_ROLE_USER,
+ JANAS_LLM_ROLE_ASSISTANT,
+ JANAS_LLM_ROLE_USER};
+ const char *texts[] = {p1, t1, p2};
+ t2 = reply_text(c, janas_llm_chat_load(c, 3, roles, texts, NULL));
+ }
+ janas_llm_chat_destroy(c);
+ }
+ janas_llm_close(llm);
+ if (!t1 || !t2) {
+ fprintf(stderr, "node_check: the library's replies failed\n");
+ return 1;
+ }
+ printf("library: \"%s\" / \"%s\"\n", t1, t2);
+
+ char *out = malloc(1 << 20);
+ const char *flags[] = {"--unhandled-rejections=strict", NULL};
+ const char *args[] = {addon, argv[1], p1, p2, NULL};
+ int st =
+ out ? node_run(node, flags, script, args, NULL, timeout_s, out, 1 << 20)
+ : -1;
+ char *h1 = to_hex(t1), *h2 = to_hex(t2);
+ struct {
+ const char *key, *want, *what;
+ } cmp[] = {
+ {"t1", h1, "the reply streamed"},
+ {"t2", h2, "the conversation loaded, read whole"},
+ {"t1again", h1, "the same message after a reset"},
+ {"t1chat2", h1, "the same message in a new chat"},
+ };
+ int failures = st != 0;
+ printf("node: exit %d%s\n", st,
+ out && strstr(out, "\ndone 1") ? "" : ", did not finish");
+ if (!out || !strstr(out, "\ndone 1"))
+ failures++;
+ for (size_t i = 0; out && i < sizeof(cmp) / sizeof(cmp[0]); i++) {
+ int ok = h1 && h2 && same(out, cmp[i].key, cmp[i].want);
+ printf("%-5s %s\n", ok ? "ok" : "FAIL", cmp[i].what);
+ failures += !ok;
+ }
+ if (out) {
+ const char *keys[] = {"model", "cached", "progress"};
+ for (size_t i = 0; i < 3; i++) {
+ char k[32];
+ snprintf(k, sizeof(k), "%s ", keys[i]);
+ const char *q = strstr(out, k);
+ if (q)
+ printf("node: %.*s\n", (int)strcspn(q, "\n"), q);
+ }
+ }
+ printf("node_check: %s\n", failures ? "FAIL" : "ok");
+ free(out);
+ free(h1);
+ free(h2);
+ free(t1);
+ free(t2);
+ return failures ? 1 : 0;
+}
+#endif
diff --git a/tests/node_run.h b/tests/node_run.h
new file mode 100644
index 0000000..98bf84a
--- /dev/null
+++ b/tests/node_run.h
@@ -0,0 +1,170 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * node_run.h - node running a script, for the checks of the module for
+ * Node.js (test_node.c, node_check.c): node from the PATH; the module of
+ * the test's own variant, beside it (janas.node, janas-asan.node...); and
+ * the sanitizer's runtime the test was linked with, preloaded into node, so
+ * that the module's checks run there too (node itself is not instrumented:
+ * its leaks at exit are not looked for). Linux only.
+ */
+#ifndef JANAS_TESTS_NODE_RUN_H
+#define JANAS_TESTS_NODE_RUN_H
+
+#include <errno.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+/* node's path from the PATH; 0 when there is none */
+static int node_find(char *out, size_t cap)
+{
+ const char *path = getenv("PATH");
+ while (path && *path) {
+ const char *end = strchr(path, ':');
+ size_t n = end ? (size_t)(end - path) : strlen(path);
+ if (n && (size_t)snprintf(out, cap, "%.*s/node", (int)n, path) < cap &&
+ access(out, X_OK) == 0)
+ return 1;
+ path = end ? end + 1 : NULL;
+ }
+ return 0;
+}
+
+/* the module beside this program, of its variant: test_node-asan takes
+ janas-asan.node */
+static int node_addon(char *out, size_t cap)
+{
+ char self[4096];
+ ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1);
+ if (n <= 0)
+ return 0;
+ self[n] = 0;
+ char *base = strrchr(self, '/');
+ if (!base)
+ return 0;
+ *base++ = 0;
+ const char *variant = strchr(base, '-');
+ if ((size_t)snprintf(out, cap, "%s/janas%s.node", self,
+ variant ? variant : "") >= cap)
+ return 0;
+ return access(out, R_OK) == 0;
+}
+
+/* the sanitizer's runtime mapped in this process, if any */
+static int node_preload(char *out, size_t cap)
+{
+ FILE *f = fopen("/proc/self/maps", "r");
+ char line[4608];
+ int found = 0;
+ while (f && !found && fgets(line, sizeof(line), f)) {
+ char *p = strchr(line, '/');
+ if (!p || !(strstr(p, "/libasan.so") || strstr(p, "/libtsan.so") ||
+ strstr(p, "/libubsan.so")))
+ continue;
+ p[strcspn(p, "\n")] = 0;
+ found = (size_t)snprintf(out, cap, "%s", p) < cap;
+ }
+ if (f)
+ fclose(f);
+ return found;
+}
+
+/*
+ * Runs node with flags, the script (-e) and args, in an environment with
+ * the sanitizer's runtime preloaded and the variables of env ("NAME=value",
+ * NULL-terminated, may be NULL). Its standard output goes into out (cap
+ * bytes, NUL-terminated, the rest dropped), its standard error to ours. The
+ * exit status, or -1 when it could not run or was killed after timeout_s
+ * seconds.
+ */
+static int node_run(const char *node, const char *const *flags,
+ const char *script, const char *const *args,
+ const char *const *env, int timeout_s, char *out,
+ size_t cap)
+{
+ const char *argv[64];
+ int n = 0;
+ argv[n++] = node;
+ for (int i = 0; flags && flags[i] && n < 50; i++)
+ argv[n++] = flags[i];
+ argv[n++] = "-e";
+ argv[n++] = script;
+ for (int i = 0; args && args[i] && n < 63; i++)
+ argv[n++] = args[i];
+ argv[n] = NULL;
+ char preload[4096];
+ int have_preload = node_preload(preload, sizeof(preload));
+ int fd[2];
+ if (pipe(fd) != 0)
+ return -1;
+ fflush(stdout);
+ fflush(stderr);
+ pid_t pid = fork();
+ if (pid < 0) {
+ close(fd[0]);
+ close(fd[1]);
+ return -1;
+ }
+ if (pid == 0) {
+ dup2(fd[1], 1);
+ close(fd[0]);
+ close(fd[1]);
+ if (have_preload) {
+ setenv("LD_PRELOAD", preload, 1);
+ /* node's own allocations at exit are not the module's */
+ setenv("ASAN_OPTIONS", "detect_leaks=0", 0);
+ }
+ for (int i = 0; env && env[i]; i++)
+ putenv((char *)env[i]);
+ execv(node, (char *const *)argv);
+ _exit(127);
+ }
+ close(fd[1]);
+ size_t len = 0;
+ int status = -1, done = 0;
+ time_t end = time(NULL) + timeout_s;
+ for (;;) {
+ struct pollfd p = {.fd = fd[0], .events = POLLIN};
+ int r = poll(&p, 1, 100);
+ if (r > 0) {
+ char buf[4096];
+ ssize_t k = read(fd[0], buf, sizeof(buf));
+ if (k > 0) {
+ size_t take =
+ (size_t)k < cap - 1 - len ? (size_t)k : cap - 1 - len;
+ memcpy(out + len, buf, take);
+ len += take;
+ continue;
+ }
+ if (k == 0 && done)
+ break;
+ }
+ if (!done) {
+ int st;
+ pid_t w = waitpid(pid, &st, WNOHANG);
+ if (w == pid) {
+ done = 1;
+ status = WIFEXITED(st) ? WEXITSTATUS(st) : -1;
+ } else if (time(NULL) > end) {
+ fprintf(stderr, "node did not end in %d s: killed\n",
+ timeout_s);
+ kill(pid, SIGKILL);
+ waitpid(pid, &st, 0);
+ done = 1;
+ status = -1;
+ }
+ } else if (r == 0)
+ break;
+ }
+ close(fd[0]);
+ out[len] = 0;
+ return status;
+}
+
+#endif
diff --git a/tests/test_node.c b/tests/test_node.c
new file mode 100644
index 0000000..aa9cc77
--- /dev/null
+++ b/tests/test_node.c
@@ -0,0 +1,104 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_node.c - the module for Node.js (janas.node) without a model: node
+ * loads it; its classes refuse new, and their methods any other object;
+ * wrong arguments and options throw TypeErrors that name them; a file that
+ * is not there rejects with JANAS_EOPEN, several at once too, each engine
+ * thread started and ended; and node then exits by itself, the module
+ * keeping nothing alive. Skipped where node is not in the PATH.
+ *
+ * Where Node's headers are installed, src/node/napi.h is checked against
+ * them as well: its declarations follow Node's here, and the compiler stops
+ * on any that differs.
+ */
+#if !defined(_WIN32) && defined(__has_include)
+#if __has_include(<node/node_api.h>)
+#include <node/node_api.h>
+#define JANAS_NAPI_NODE_TYPES
+#include "node/napi.h"
+#endif
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#ifdef _WIN32
+int main(void)
+{
+ printf("test_node: skipped, the module is built on Linux only\n");
+ return 0;
+}
+#else
+#include "node_run.h"
+
+static const char script[] =
+ "'use strict';\n"
+ "const assert = require('node:assert/strict');\n"
+ "const janas = require(process.argv[1]);\n"
+ "let checks = 0;\n"
+ "const check = (f) => { f(); checks++; };\n"
+ "check(() => {\n"
+ " assert.equal(typeof janas.open, 'function');\n"
+ " assert.equal(janas.abiVersion(), 1);\n"
+ " assert.equal(typeof janas.version, 'string');\n"
+ " for (const c of ['Model', 'Chat', 'Reply'])\n"
+ " assert.equal(typeof janas[c], 'function');\n"
+ " assert.equal(typeof janas.Reply.prototype[Symbol.asyncIterator], "
+ "'function');\n"
+ "});\n"
+ "check(() => {\n"
+ " assert.throws(() => new janas.Model(), /comes from open\\(\\)/);\n"
+ " assert.throws(() => new janas.Chat(), TypeError);\n"
+ " assert.throws(() => new janas.Reply(), TypeError);\n"
+ " assert.throws(() => janas.Model.prototype.chat.call({}), TypeError);\n"
+ " assert.throws(() => janas.Reply.prototype.next.call("
+ "janas.Chat.prototype), TypeError);\n"
+ "});\n"
+ "check(() => {\n"
+ " assert.throws(() => janas.open(), TypeError);\n"
+ " assert.throws(() => janas.open(42), TypeError);\n"
+ " assert.throws(() => janas.open('m.jns', 3), /must be an object/);\n"
+ " assert.throws(() => janas.open('m.jns', { cache: 4 }), "
+ "/no option 'cache'/);\n"
+ " assert.throws(() => janas.open('m.jns', { context: 'big' }), "
+ "/context must be a number/);\n"
+ " assert.throws(() => janas.open('m.jns', { context: 1.5 }), "
+ "/whole number/);\n"
+ " assert.throws(() => janas.open('m.jns', { mode: 'fast' }), "
+ "/mode cannot be 'fast'/);\n"
+ " assert.throws(() => janas.open('m.jns', { expertBits: 3 }), "
+ "/expertBits/);\n"
+ " assert.throws(() => janas.open('m.jns', { mtp: 5 }), TypeError);\n"
+ "});\n"
+ "(async () => {\n"
+ " for (let i = 0; i < 3; i++)\n"
+ " await assert.rejects(janas.open('/nonexistent/janas-test.jns'),\n"
+ " (e) => e instanceof Error && e.code === 'EOPEN');\n"
+ " checks++;\n"
+ " await Promise.all([0, 1, 2, 3].map(() => assert.rejects(\n"
+ " janas.open('/nonexistent/janas-test.jns', { context: 1024 }),\n"
+ " { code: 'EOPEN' })));\n"
+ " checks++;\n"
+ " console.log('checks ' + checks);\n"
+ "})().catch((e) => { console.error(e); process.exitCode = 1; });\n";
+
+int main(void)
+{
+ char node[4096], addon[4096], out[4096];
+ if (!node_find(node, sizeof(node))) {
+ printf("test_node: skipped, no node in the PATH\n");
+ return 0;
+ }
+ if (!node_addon(addon, sizeof(addon))) {
+ printf("test_node: FAIL, no janas.node beside the test\n");
+ return 1;
+ }
+ const char *args[] = {addon, NULL};
+ int st = node_run(node, NULL, script, args, NULL, 120, out, sizeof(out));
+ int ok = st == 0 && strstr(out, "checks 5") != NULL;
+ printf("test_node: %s (%s, exit %d: %s)\n", ok ? "ok" : "FAIL", addon, st,
+ out[0] ? strtok(out, "\n") : "no output");
+ return ok ? 0 : 1;
+}
+#endif