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-01: janas-weather, and "here" for the services

camauri929a7a995973
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d773f34..a47d2b3 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,37 +1,20 @@
# Contributing to Janas
-Janas is an experiment in early development: formats, interfaces and the
-command line change without notice. Before writing code, it is worth asking in
-an issue whether the thing you have in mind is already being changed underneath.
+Janas is an experiment in early development: formats, interfaces and the command line change without notice. Before writing code, it is worth asking in an issue whether the thing you have in mind is already being changed underneath.
## What helps most
-**A measurement from a machine nobody here owns.** Everything in the engine is
-decided from what it measures, and it has only ever measured one machine (a
-Core Ultra 9 185H with 32 GB of RAM and an NVMe disk, on Debian 13). Run:
+**A measurement from a machine nobody here owns.** Everything in the engine is decided from what it measures, and it has only ever measured one machine (a Core Ultra 9 185H with 32 GB of RAM and an NVMe disk, on Debian 13). Run:
```sh
bin/x86_64-linux/janas-bench <model.jns>
```
-**with the machine to itself** — close the browser and the editor first. The
-engine takes the memory that is free when it starts and reads the disk while it
-answers, so anything else running lands in the numbers: on the development
-laptop, with 8 GB already taken by other programs, the same model went from
-20-25 tokens per second to nearly 18.
-
-Then open a
-[hardware report](https://github.com/prabanta-dev/janas/issues/new?template=01-hardware-report.yml):
-the form asks for the report it writes, your distribution and kernel
-(`uname -a`), your memory (`free -g`), the disk the model sits on, and anything
-that looked wrong. The README lists which machines are wanted most: CPUs without
-AVX-VNNI, AMD, discrete GPUs, machines with 16 GB or less, slower disks.
-
-**A model that will not convert, or converts and then answers nonsense.** Say
-which file (with its link and its SHA-256) and what `gguf2jns` printed
-— there is
-[a form for that](https://github.com/prabanta-dev/janas/issues/new?template=03-a-model-will-not-work.yml)
-too.
+**with the machine to itself** — close the browser and the editor first. The engine takes the memory that is free when it starts and reads the disk while it answers, so anything else running lands in the numbers: on the development laptop, with 8 GB already taken by other programs, the same model went from 20-25 tokens per second to nearly 18.
+
+Then open a [hardware report](https://github.com/prabanta-dev/janas/issues/new?template=01-hardware-report.yml): the form asks for the report it writes, your distribution and kernel (`uname -a`), your memory (`free -g`), the disk the model sits on, and anything that looked wrong. The README lists which machines are wanted most: CPUs without AVX-VNNI, AMD, discrete GPUs, machines with 16 GB or less, slower disks.
+
+**A model that will not convert, or converts and then answers nonsense.** Say which file (with its link and its SHA-256) and what `gguf2jns` printed — there is [a form for that](https://github.com/prabanta-dev/janas/issues/new?template=03-a-model-will-not-work.yml) too.
## Code
@@ -44,21 +27,14 @@ too.
`./build.sh --help` says what each variant catches and what the actions do.
-- The code is C11 with no dependencies beyond the C library. Vulkan, when used,
- is loaded at run time: the engine must build and run without it.
-- Format with `clang-format -i` (the `.clang-format` in the root). Warnings are
- errors: `-Wall -Wextra -Werror`.
-- A change that touches arithmetic must keep the results it promises: kernels
- agree bit for bit with the scalar reference, and a pass over a block of tokens
- agrees bit for bit with the same tokens one at a time. The tests check this;
- keep them passing.
-- Numbers in a commit message are welcome, and should say on what they were
- measured.
+- The code is C11 with no dependencies beyond the C library. Vulkan, when used, is loaded at run time: the engine must build and run without it.
+- Format with `clang-format -i` (the `.clang-format` in the root). Warnings are errors: `-Wall -Wextra -Werror`.
+- A change that touches arithmetic must keep the results it promises: kernels agree bit for bit with the scalar reference, and a pass over a block of tokens agrees bit for bit with the same tokens one at a time. The tests check this; keep them passing.
+- Numbers in a commit message are welcome, and should say on what they were measured.
## Copyright and sign-off
-Janas is licensed under the **GNU General Public License, version 3 or later**
-(see [LICENSE](LICENSE)). Contributions are taken under the same licence.
+Janas is licensed under the **GNU General Public License, version 3 or later** (see [LICENSE](LICENSE)). Contributions are taken under the same licence.
Every commit must carry a sign-off line:
@@ -66,16 +42,10 @@ Every commit must carry a sign-off line:
Signed-off-by: Your Name <your@email>
```
-which `git commit -s` adds for you. It means what the
-[Developer Certificate of Origin](https://developercertificate.org/) says: that
-you wrote the change, or have the right to submit it under this licence.
+which `git commit -s` adds for you. It means what the [Developer Certificate of Origin](https://developercertificate.org/) says: that you wrote the change, or have the right to submit it under this licence.
-Please keep contributions to code you own. Code copied from elsewhere, however
-small, has to be declared in the pull request, with where it came from and under
-what licence.
+Please keep contributions to code you own. Code copied from elsewhere, however small, has to be declared in the pull request, with where it came from and under what licence.
## Models
-The engine reads models; it does not carry them. Anything about redistributing
-converted weights is in [MODELS.md](MODELS.md) — in short, the weights keep
-their own licence, which is not this one.
+The engine reads models; it does not carry them. Anything about redistributing converted weights is in [MODELS.md](MODELS.md) — in short, the weights keep their own licence, which is not this one.
diff --git a/ChangeLog.md b/ChangeLog.md
index 20ad08b..20c32f6 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,991 +2,318 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-01] - janas-weather, and "here" for the services
+
+- **janas-weather**, the weather as an MCP service, from free sources with no key: the weather now (`weather_now`: Open-Meteo's model, and what the nearest airport's station measured, with when and how far; when the two disagree, the answer says so), the forecast day by day and hour by hour (`weather_forecast`), the sea at points across it or off a place, with the waves' names (`weather_sea`), and the warnings in force from MeteoAlarm, with the Civil Protection's levels in Italy (`weather_alerts`). MET Norway answers when Open-Meteo does not. `janas-chat` starts it by itself; [docs/services/weather.md](docs/services/weather.md).
+- **"Here", when a question names no place**: `JANAS_LOCATION` (a city, `lat,lon`, or `off`), else the internet connection's position (GeoJS, ipwho.is), else the city of the computer's time zone; the answer says which, and the model tells the user it is a guess. For the weather and for `flights_nearby`.
+- **Tool calls in Qwen's XML form take their parameters in any order.** The grammar held them to the schema's order, and a model that began with a later one could no longer write an earlier one: Qwen3.6-35B-A3B asked the forecast with the number of days first and the place lost, sixteen times over.
+- **`janas-chat` does not run again a call that failed** with the same arguments in the same exchange: the model is told to answer or to ask, and at the second time the exchange stops.
+
## [2026-10-01] - Code completion in the editor
-- **`janas-server` fills in code at an editor's cursor**, with a model for
- code such as Qwen3-Coder-30B-A3B-Instruct, through OpenAI's
- `/v1/completions` with a `suffix` and through llama.cpp's **`/infill`**,
- which the extensions made for llama.cpp ask (llama.vscode): the line up
- to the cursor, `n_predict` (0: the prompt only), `n_indent` and
- `t_max_predict_ms` read as llama.cpp reads them, the answer as
- llama.cpp's. Tried in VSCodium with llama.vscode and with Continue;
- how to set them up in [docs/code-completion.md](docs/code-completion.md).
-- **The window sent at every keystroke is kept from moving.** The
- extensions send "the last N lines before the cursor", whose start moves
- at every new line, and the whole window was read again: 17 s for 1,330
- tokens at every request. The start of each window is now remembered and
- kept, put ahead when the editor slides its window, the text before the
- cursor cut at a line within `--fim-prefix` tokens (2048), the lines after
- it within `--fim-suffix` (8), the text written within `--fim-max` (256):
- 1.5-2.2 s a proposal after the first request of a window, on a laptop
- with Qwen3-Coder-30B-A3B in memory.
-- **Sixteen stop strings** a request, where OpenAI takes four: Continue
- sends more, and every one of its requests was refused.
+- **`janas-server` fills in code at an editor's cursor**, with a model for code such as Qwen3-Coder-30B-A3B-Instruct, through OpenAI's `/v1/completions` with a `suffix` and through llama.cpp's **`/infill`**, which the extensions made for llama.cpp ask (llama.vscode): the line up to the cursor, `n_predict` (0: the prompt only), `n_indent` and `t_max_predict_ms` read as llama.cpp reads them, the answer as llama.cpp's. Tried in VSCodium with llama.vscode and with Continue; how to set them up in [docs/code-completion.md](docs/code-completion.md).
+- **The window sent at every keystroke is kept from moving.** The extensions send "the last N lines before the cursor", whose start moves at every new line, and the whole window was read again: 17 s for 1,330 tokens at every request. The start of each window is now remembered and kept, put ahead when the editor slides its window, the text before the cursor cut at a line within `--fim-prefix` tokens (2048), the lines after it within `--fim-suffix` (8), the text written within `--fim-max` (256): 1.5-2.2 s a proposal after the first request of a window, on a laptop with Qwen3-Coder-30B-A3B in memory.
+- **Sixteen stop strings** a request, where OpenAI takes four: Continue sends more, and every one of its requests was refused.
## [2026-10-01] - janas-flights, the first of Janas's services
-- **janas-flights**, flights as an MCP server of its own, for `janas-chat`
- or any MCP client: where a flight is and what it is doing
- (`flight_status`), the flights of a route (`flights_between`), what
- flies now over a sea, by its name in English or Italian
- (`flights_over`), and near an airport, a city or a point
- (`flights_nearby`). Live positions come from the open ADS-B networks
- (adsb.lol, adsb.fi as the fallback) and need no key; schedules, gates
- and delays come from AviationStack with a free key of the user's own
- (100 calls a month), asked only about one flight or one route - lists
- and areas use open data only. Times are given in each airport's local
- time and in UTC, places in words, and a live position is given to a
- scheduled flight only when the aircraft fits its route. On 1 October:
- AZ1709 from Fiumicino to Catania seen over the Tyrrhenian Sea with two
- arrival estimates, the 21 flights from Fiumicino to Catania, 45
- aircraft over the Tyrrhenian Sea.
-- **`janas-chat` starts Janas's services by itself**: those it finds
- beside it, with no configuration. Their tools run without asking (they
- read public data and change nothing), their calls show as dimmed lines,
- and the model is told to use them whenever a question is on their
- subject, without naming them. `--no-services` starts none.
-- **The server side of MCP** moved to `src/common/mcp_server.c`, shared by
- `janas-mcp` and `janas-flights`.
-- **docs/services/**: the services documented apart from the README, with
- how to use them in Claude Code and the clients that read an
- `mcpServers` file.
+- **janas-flights**, flights as an MCP server of its own, for `janas-chat` or any MCP client: where a flight is and what it is doing (`flight_status`), the flights of a route (`flights_between`), what flies now over a sea, by its name in English or Italian (`flights_over`), and near an airport, a city or a point (`flights_nearby`). Live positions come from the open ADS-B networks (adsb.lol, adsb.fi as the fallback) and need no key; schedules, gates and delays come from AviationStack with a free key of the user's own (100 calls a month), asked only about one flight or one route - lists and areas use open data only. Times are given in each airport's local time and in UTC, places in words, and a live position is given to a scheduled flight only when the aircraft fits its route. On 1 October: AZ1709 from Fiumicino to Catania seen over the Tyrrhenian Sea with two arrival estimates, the 21 flights from Fiumicino to Catania, 45 aircraft over the Tyrrhenian Sea.
+- **`janas-chat` starts Janas's services by itself**: those it finds beside it, with no configuration. Their tools run without asking (they read public data and change nothing), their calls show as dimmed lines, and the model is told to use them whenever a question is on their subject, without naming them. `--no-services` starts none.
+- **The server side of MCP** moved to `src/common/mcp_server.c`, shared by `janas-mcp` and `janas-flights`.
+- **docs/services/**: the services documented apart from the README, with how to use them in Claude Code and the clients that read an `mcpServers` file.
## [2026-10-01] - Experts read ahead, steadier drafts, every weight type on the GPU
-- **The drafts no longer switch themselves off for good.** The planner of
- the multi-token prediction drafts judges each number of drafts by the
- cost of a pass of that many tokens, as last timed. One pass of two
- tokens timed while the disk was busy made it refuse every draft, and with
- no drafts that cost was never timed again: in some sessions the drafts
- stopped after the first hundred tokens and never came back, which is why
- the same chat ran at 22 tokens/s one time and 26 the next. It now drafts
- one pass in sixteen even when it chose none, as the drafts copied from
- the conversation already did. Qwen3-Next-80B in `janas-chat`, three
- replies of 600 tokens, two rounds alternated with the release of 28
- September: 26.0 tokens/s (25.5-26.5) against 24.3 (22.5-26.1), +7%.
-- **The same seed gives the same conversation, drafts or not.** A reply
- cut short - by `--max`, or stopped - after a pass that had accepted
- drafts past its end dropped those tokens but not the random numbers drawn
- for them, so every later reply of the conversation came out different
- from the one without drafts. The numbers are given back now: with the
- same seed the replies are identical with and without drafts, cut or not.
-- **A reply's statistics count the experts read ahead**; left out, they
- made the cache look warmer and the disk idler than they were.
-- **Experts read ahead, where the cache misses many.** A mixture whose
- experts do not fit in memory waited for the disk one layer at a time:
- Qwen3-Next-80B with every bit and a 4 GiB cache spent half of each token
- waiting, with the disk busy only 60% of the time. Now the next layer's
- router is applied ahead, and of its first ten experts up to two not in
- the cache are read while the current layer computes (on that model the
- prediction held 91% of the experts chosen). Reading ahead costs on every
- token and pays only when the cache misses many experts, so it turns
- itself on above 60 missed experts a token and off below 40. Qwen3-Next-80B,
- every bit, a fresh cache, three rounds alternated with it off: 4 GiB
- 10.9-11.1 to 11.7-11.8 tokens/s (+6%), 8 GiB 15.6-15.7 to 16.2-16.3
- (+4%); with a warm 20 GiB cache it never turns on and the speed is the
- same; in `janas-chat`, with a 4 GiB cache and every expert, 12.6
- tokens/s against 12.1 of the release of 28 September (+3.6%). The
- results are the same bits, on or off. `JANAS_PREFETCH=0` turns it off.
-- **The expert cache without transparent-huge-page advice.** With the
- kernel's huge pages on "always" and their defrag on "madvise" (the
- common setting), the advice made every first write to the cache try a
- synchronous compaction of memory, which looked like waiting for the
- disk. Without it, a reply of Qwen3-Next-80B from a fresh 20 GiB cache
- went from 17.5-17.7 to 19.7 tokens/s, and a prompt from a warm one from
- 51 to 55; other sizes are even. `JANAS_ARENA_HUGE=1` asks for huge pages
- as before.
-- **Every quantized type on the GPU**: Q8_0, Q4_0, Q4_1, Q5_1, IQ4_NL,
- IQ4_XS, Q3_K and IQ3_S join Q4_K, Q5_K and Q6_K, bit for bit the CPU's
- results (`gpu_check`: 1680 shapes). Gemma-4-26B keeps its attention, its
- dense feed-forward and its output head in Q8_0; Qwen3.5-9B's "UD" mix
- keeps some layers in IQ4_XS and Q8_0.
-- **A whole token on the GPU, as an experiment** (`JANAS_GPU_TOKEN=1`,
- dense Qwen3 models, integrated GPUs): every step of a token - norms,
- RoPE, attention, products, output head - in one submission, recorded
- once. `JANAS_GPU_BLOCK=1` does the same for blocks of up to 64 tokens (a
- prompt, the drafts a speculative pass checks), the same bits as one token
- at a time; `JANAS_GPU_REPACK=1` gives the Q6_K weights an aligned copy
- for it (some 0.8 GB more for Qwen3-4B). On the development laptop's
- integrated GPU it runs level with the CPU: Qwen3-4B writes 24.3-24.7
- tokens/s against the CPU's 24.8, and in blocks reads a 2000-token prompt
- at 107 tokens/s where a token at a time gave 61. It is off unless asked
- for.
-- Tools for measures: `llm_gen cpus=` puts the compute threads on chosen
- CPUs; `bench_long` reports how long the disk was busy beside how long
- the engine waited for it, prints the experts' bits and count in use
- (`BENCH_EXACT=1` keeps every bit and the model's own count), and can
- save the prompt and the reply; the library can hand a caller the
- experts each layer routes a token to, and a prediction of the next
- layer's.
+- **The drafts no longer switch themselves off for good.** The planner of the multi-token prediction drafts judges each number of drafts by the cost of a pass of that many tokens, as last timed. One pass of two tokens timed while the disk was busy made it refuse every draft, and with no drafts that cost was never timed again: in some sessions the drafts stopped after the first hundred tokens and never came back, which is why the same chat ran at 22 tokens/s one time and 26 the next. It now drafts one pass in sixteen even when it chose none, as the drafts copied from the conversation already did. Qwen3-Next-80B in `janas-chat`, three replies of 600 tokens, two rounds alternated with the release of 28 September: 26.0 tokens/s (25.5-26.5) against 24.3 (22.5-26.1), +7%.
+- **The same seed gives the same conversation, drafts or not.** A reply cut short - by `--max`, or stopped - after a pass that had accepted drafts past its end dropped those tokens but not the random numbers drawn for them, so every later reply of the conversation came out different from the one without drafts. The numbers are given back now: with the same seed the replies are identical with and without drafts, cut or not.
+- **A reply's statistics count the experts read ahead**; left out, they made the cache look warmer and the disk idler than they were.
+- **Experts read ahead, where the cache misses many.** A mixture whose experts do not fit in memory waited for the disk one layer at a time: Qwen3-Next-80B with every bit and a 4 GiB cache spent half of each token waiting, with the disk busy only 60% of the time. Now the next layer's router is applied ahead, and of its first ten experts up to two not in the cache are read while the current layer computes (on that model the prediction held 91% of the experts chosen). Reading ahead costs on every token and pays only when the cache misses many experts, so it turns itself on above 60 missed experts a token and off below 40. Qwen3-Next-80B, every bit, a fresh cache, three rounds alternated with it off: 4 GiB 10.9-11.1 to 11.7-11.8 tokens/s (+6%), 8 GiB 15.6-15.7 to 16.2-16.3 (+4%); with a warm 20 GiB cache it never turns on and the speed is the same; in `janas-chat`, with a 4 GiB cache and every expert, 12.6 tokens/s against 12.1 of the release of 28 September (+3.6%). The results are the same bits, on or off. `JANAS_PREFETCH=0` turns it off.
+- **The expert cache without transparent-huge-page advice.** With the kernel's huge pages on "always" and their defrag on "madvise" (the common setting), the advice made every first write to the cache try a synchronous compaction of memory, which looked like waiting for the disk. Without it, a reply of Qwen3-Next-80B from a fresh 20 GiB cache went from 17.5-17.7 to 19.7 tokens/s, and a prompt from a warm one from 51 to 55; other sizes are even. `JANAS_ARENA_HUGE=1` asks for huge pages as before.
+- **Every quantized type on the GPU**: Q8_0, Q4_0, Q4_1, Q5_1, IQ4_NL, IQ4_XS, Q3_K and IQ3_S join Q4_K, Q5_K and Q6_K, bit for bit the CPU's results (`gpu_check`: 1680 shapes). Gemma-4-26B keeps its attention, its dense feed-forward and its output head in Q8_0; Qwen3.5-9B's "UD" mix keeps some layers in IQ4_XS and Q8_0.
+- **A whole token on the GPU, as an experiment** (`JANAS_GPU_TOKEN=1`, dense Qwen3 models, integrated GPUs): every step of a token - norms, RoPE, attention, products, output head - in one submission, recorded once. `JANAS_GPU_BLOCK=1` does the same for blocks of up to 64 tokens (a prompt, the drafts a speculative pass checks), the same bits as one token at a time; `JANAS_GPU_REPACK=1` gives the Q6_K weights an aligned copy for it (some 0.8 GB more for Qwen3-4B). On the development laptop's integrated GPU it runs level with the CPU: Qwen3-4B writes 24.3-24.7 tokens/s against the CPU's 24.8, and in blocks reads a 2000-token prompt at 107 tokens/s where a token at a time gave 61. It is off unless asked for.
+- Tools for measures: `llm_gen cpus=` puts the compute threads on chosen CPUs; `bench_long` reports how long the disk was busy beside how long the engine waited for it, prints the experts' bits and count in use (`BENCH_EXACT=1` keeps every bit and the model's own count), and can save the prompt and the reply; the library can hand a caller the experts each layer routes a token to, and a prediction of the next layer's.
## [2026-09-28] - More of the work on the GPU
-- **The experts' weights go to the GPU too** once every expert of every
- layer is in the cache: the feed-forward weights of a dense model, and a
- mixture small enough to fit. They were always left to the CPU. On the
- development laptop's integrated GPU, Qwen3-4B reads a prompt 29% faster
- (83 to 107 tokens/s) and the chip spends 36% less energy per token
- (0.49 to 0.31 J, RAPL package counter); replies are unchanged.
- `JANAS_GPU_EXPERTS=0` keeps them on the CPU. Regions over 4 GB no longer
- turn the GPU off: they are imported in pieces.
-- **Single tokens on a discrete GPU**, where the tuner finds it faster. The
- tuner never gave a reply's single token to the GPU; on an RTX 5080 (issue
- #15) doing so made replies 11-16% faster, even with only attention and
- output in the card's memory. A discrete GPU now takes them, and the tuner
- tries it and keeps it only if it measures faster; integrated GPUs are
- left as they were.
-- **Two more weight types on the GPU**: Q6_K in bit planes (the down
- matrices of every Qwen mixture and of some layers of the dense models)
- and Q5_K (Qwen3.5 2B and 9B). Like the others they give the CPU's
- results bit for bit, so a product still splits between the two.
-- `JANAS_GPU_VERBOSE=2` lists each product shape once with its weight
- types and whether the GPU takes them.
+- **The experts' weights go to the GPU too** once every expert of every layer is in the cache: the feed-forward weights of a dense model, and a mixture small enough to fit. They were always left to the CPU. On the development laptop's integrated GPU, Qwen3-4B reads a prompt 29% faster (83 to 107 tokens/s) and the chip spends 36% less energy per token (0.49 to 0.31 J, RAPL package counter); replies are unchanged. `JANAS_GPU_EXPERTS=0` keeps them on the CPU. Regions over 4 GB no longer turn the GPU off: they are imported in pieces.
+- **Single tokens on a discrete GPU**, where the tuner finds it faster. The tuner never gave a reply's single token to the GPU; on an RTX 5080 (issue #15) doing so made replies 11-16% faster, even with only attention and output in the card's memory. A discrete GPU now takes them, and the tuner tries it and keeps it only if it measures faster; integrated GPUs are left as they were.
+- **Two more weight types on the GPU**: Q6_K in bit planes (the down matrices of every Qwen mixture and of some layers of the dense models) and Q5_K (Qwen3.5 2B and 9B). Like the others they give the CPU's results bit for bit, so a product still splits between the two.
+- `JANAS_GPU_VERBOSE=2` lists each product shape once with its weight types and whether the GPU takes them.
## [2026-09-27] - No Python left
-- The README names its author, Maurizio "camauri" Cammalleri, under the
- introduction and in a new Credits section, with the copyright line in
- the Licence one; the section also credits the models' authors, llama.cpp
- and ggml (the reference, and the IQ3_S grid), the Unicode Character
- Database, OpenAI's specification, the libraries compiled in, and the
- testers. An `AUTHORS` file says the same in the GNU way.
-- The last two Python scripts are C programs, built with everything else:
- `tools/gen_unicode` writes the tokenizer's Unicode tables from the
- Unicode Character Database (`/usr/share/unicode` on Debian and its kin),
- `tools/openapi_routes` writes `janas-server`'s route table from OpenAI's
- specification. Both give, byte for byte, the files the scripts gave
- (Unicode 15.1.0; OpenAPI 2.3.0, 345 operations), and the coverage count
- is the same. Nothing in Janas needs Python any more, to build or to
- regenerate.
+- The README names its author, Maurizio "camauri" Cammalleri, under the introduction and in a new Credits section, with the copyright line in the Licence one; the section also credits the models' authors, llama.cpp and ggml (the reference, and the IQ3_S grid), the Unicode Character Database, OpenAI's specification, the libraries compiled in, and the testers. An `AUTHORS` file says the same in the GNU way.
+- The last two Python scripts are C programs, built with everything else: `tools/gen_unicode` writes the tokenizer's Unicode tables from the Unicode Character Database (`/usr/share/unicode` on Debian and its kin), `tools/openapi_routes` writes `janas-server`'s route table from OpenAI's specification. Both give, byte for byte, the files the scripts gave (Unicode 15.1.0; OpenAPI 2.3.0, 345 operations), and the coverage count is the same. Nothing in Janas needs Python any more, to build or to regenerate.
## [2026-09-27] - janas-get: a model in one command
-- **`janas-get`** downloads a model of its catalog (the thirteen of
- MODELS.md: Qwen3, Qwen3.5, Qwen3.6, Qwen3-Next, Coder-Next, the
- embedding model, Gemma 4) from Hugging Face, checks the SHA-256 of
- every file against MODELS.md, runs the converters of the same build
- (gguf2jns, jns_planes) and makes the prediction file beside the model -
- hf2jns_mtp over range requests, or Gemma 4's assistant - with its
- fingerprint too. Downloads resume; files already there are checked, not
- fetched again; the GGUF goes as soon as it is converted, so the disk
- holds two copies at the most. `janas-get hf:<owner>/<repo>/<file>` takes
- any GGUF, checked against the SHA-256 Hugging Face lists.
-- Its own HTTPS download in pieces (the client of hf2jns_mtp) and its own
- SHA-256, on the x86 SHA extensions where the CPU has them (1.4 GB/s on
- the development laptop): no curl, no sha256sum.
-- **`janas-try.sh` gets its models through it**: the catalog and the
- fingerprints are in one place. A test checks the catalog against
- MODELS.md, digit by digit.
+- **`janas-get`** downloads a model of its catalog (the thirteen of MODELS.md: Qwen3, Qwen3.5, Qwen3.6, Qwen3-Next, Coder-Next, the embedding model, Gemma 4) from Hugging Face, checks the SHA-256 of every file against MODELS.md, runs the converters of the same build (gguf2jns, jns_planes) and makes the prediction file beside the model - hf2jns_mtp over range requests, or Gemma 4's assistant - with its fingerprint too. Downloads resume; files already there are checked, not fetched again; the GGUF goes as soon as it is converted, so the disk holds two copies at the most. `janas-get hf:<owner>/<repo>/<file>` takes any GGUF, checked against the SHA-256 Hugging Face lists.
+- Its own HTTPS download in pieces (the client of hf2jns_mtp) and its own SHA-256, on the x86 SHA extensions where the CPU has them (1.4 GB/s on the development laptop): no curl, no sha256sum.
+- **`janas-try.sh` gets its models through it**: the catalog and the fingerprints are in one place. A test checks the catalog against MODELS.md, digit by digit.
## [2026-09-27] - janas-try tries Gemma
-- **`janas-try.sh --level gemma`**: Gemma-4-E4B and its assistant,
- downloaded from unsloth and checked by SHA-256, converted in one step,
- with the fingerprints of both files and of the answer at temperature 0
- (`b2c01def5ff6bd5c`: the same with the default kernels and AVX2 alone,
- with and without the assistant, on 4 CPUs and without the GPU). 5.1 GB
- to download; the model runs in about 3 GB of memory.
+- **`janas-try.sh --level gemma`**: Gemma-4-E4B and its assistant, downloaded from unsloth and checked by SHA-256, converted in one step, with the fingerprints of both files and of the answer at temperature 0 (`b2c01def5ff6bd5c`: the same with the default kernels and AVX2 alone, with and without the assistant, on 4 CPUs and without the GPU). 5.1 GB to download; the model runs in about 3 GB of memory.
## [2026-09-27] - The prediction file found beside the model
-- **`janas-chat` and `janas-server` find the model's multi-token
- prediction file by themselves**: of the `.jns` files beside the model,
- the one whose header fits it - an MTP block of the same architecture,
- width and experts, or Gemma 4's assistant as wide as the model's output
- and with its vocabulary - the longest shared start of the name settling
- a tie. Files over 2 GB (models) are not even opened. `--mtp` still names
- one, and `--no-mtp` goes without. For programs,
- `janas_llm_find_mtp()` (and its FreeBASIC declaration); opening a model
- never looks by itself.
+- **`janas-chat` and `janas-server` find the model's multi-token prediction file by themselves**: of the `.jns` files beside the model, the one whose header fits it - an MTP block of the same architecture, width and experts, or Gemma 4's assistant as wide as the model's output and with its vocabulary - the longest shared start of the name settling a tie. Files over 2 GB (models) are not even opened. `--mtp` still names one, and `--no-mtp` goes without. For programs, `janas_llm_find_mtp()` (and its FreeBASIC declaration); opening a model never looks by itself.
## [2026-09-27] - Finer activations for weights in blocks of 32
-- **Weights stored in blocks of 32 (Q8_0, Q4_0, Q4_1, Q5_1, IQ4_NL) now
- meet activations with a scale per 32 values**, as llama.cpp gives them,
- instead of one per 256: a large activation no longer flattens the small
- ones beside it. The activations are quantized once into both forms; the
- K types keep theirs. Checked against an exact float64 forward pass of
- Gemma-4-26B-A4B (all Q8_0 and Q5_1 where it is most sensitive), 200
- tokens: the likeliest token at 156 positions instead of 147, mean logit
- error 0.87 instead of 1.39 (llama.cpp: 160, 0.90). Against llama.cpp,
- mean differences fall by 15-40% on Qwen3.5 in IQ4_NL, Q4_0, Q5_1 and
- UD-Q4_K_XL (Q5_1: 376 -> 389 of 400). Models made only of K types give
- the same bits as before.
+- **Weights stored in blocks of 32 (Q8_0, Q4_0, Q4_1, Q5_1, IQ4_NL) now meet activations with a scale per 32 values**, as llama.cpp gives them, instead of one per 256: a large activation no longer flattens the small ones beside it. The activations are quantized once into both forms; the K types keep theirs. Checked against an exact float64 forward pass of Gemma-4-26B-A4B (all Q8_0 and Q5_1 where it is most sensitive), 200 tokens: the likeliest token at 156 positions instead of 147, mean logit error 0.87 instead of 1.39 (llama.cpp: 160, 0.90). Against llama.cpp, mean differences fall by 15-40% on Qwen3.5 in IQ4_NL, Q4_0, Q5_1 and UD-Q4_K_XL (Q5_1: 376 -> 389 of 400). Models made only of K types give the same bits as before.
## [2026-09-27] - The threads chosen per machine
-- **The time left to read a long prompt no longer jumps at its start.**
- The fitted line of issue #9 rested on two blocks when first used, and
- their noise could tilt it: an estimate many times too long at 1,024
- tokens. It now moves from the latest speed to the fitted line over the
- first sixteen blocks.
-
-- **The engine chooses its threads again, once per machine and model.**
- Since 26 September it always used every usable thread, which was the
- fastest on the development laptop; on an i9-14900HX (issue #13) every
- thread replied at 9.9 tokens/s where the performance cores' 16 gave
- 24.7, and on a 9950X3D one thread per core was 4-15% ahead (#15). The
- first passes of each kind now try every thread, one per performance core
- and the performance cores' threads; the threads of the fastest are kept
- for good, saved with the machine's profile, and only whether the GPU
- takes part keeps being tried. Tried again later, at a longer context,
- the thread counts had lost unfairly to costs measured at a short one,
- which is why they had been fixed. `JANAS_TUNE_THREADS=0` keeps every
- thread.
+- **The time left to read a long prompt no longer jumps at its start.** The fitted line of issue #9 rested on two blocks when first used, and their noise could tilt it: an estimate many times too long at 1,024 tokens. It now moves from the latest speed to the fitted line over the first sixteen blocks.
+
+- **The engine chooses its threads again, once per machine and model.** Since 26 September it always used every usable thread, which was the fastest on the development laptop; on an i9-14900HX (issue #13) every thread replied at 9.9 tokens/s where the performance cores' 16 gave 24.7, and on a 9950X3D one thread per core was 4-15% ahead (#15). The first passes of each kind now try every thread, one per performance core and the performance cores' threads; the threads of the fastest are kept for good, saved with the machine's profile, and only whether the GPU takes part keeps being tried. Tried again later, at a longer context, the thread counts had lost unfairly to costs measured at a short one, which is why they had been fixed. `JANAS_TUNE_THREADS=0` keeps every thread.
## [2026-09-27] - Gemma 4's assistant drafts
-- **Gemma 4's assistant is taken as the MTP file** (`--mtp`, converted by
- `gguf2jns` from `mtp-gemma-4-*.gguf`): a small model of its own - 256
- wide, four layers with queries only - reading the main model's keys and
- values, fed the main model's embedding of the last token and its final
- state, drafting at that token's position and chaining further drafts at
- the same one, as it was trained. A draft costs about a millisecond.
-- An Italian chat reply of 110 tokens, greedy, the same tokens with and
- without it (Core Ultra 9 185H, tokens/s): **E2B 34.7 -> 51.0 (1.47x),
- E4B 18.3 -> 26.3 (1.44x), 12B 8.5 -> 12.9 (1.51x), 26B 16.9 -> 24.5
- (1.44x)**; 64-83% of the drafts the planner chose to verify were
- accepted (on E4B llama.cpp with the same assistant accepts 50% of its
- drafts). The 12B's and 26B's assistants, 1024 wide, give a KV head
- count per layer, which is read as such.
-- Its drafts are picked, as the MTP blocks' are, from a head of 32768
- token ids plus those met in the conversation, instead of all 262144: 8
- MB read a draft instead of 67, for as many accepted.
-- E2B's and E4B's per-layer branch reads its f32 matrices (220 MB a token
- on E4B) once for all the tokens of a pass, with a vector dot product:
- passes over a few tokens 17% faster, single tokens 4%.
- `JANAS_DRAFT_VOCAB` sets the draft head's size, to experiment.
+- **Gemma 4's assistant is taken as the MTP file** (`--mtp`, converted by `gguf2jns` from `mtp-gemma-4-*.gguf`): a small model of its own - 256 wide, four layers with queries only - reading the main model's keys and values, fed the main model's embedding of the last token and its final state, drafting at that token's position and chaining further drafts at the same one, as it was trained. A draft costs about a millisecond.
+- An Italian chat reply of 110 tokens, greedy, the same tokens with and without it (Core Ultra 9 185H, tokens/s): **E2B 34.7 -> 51.0 (1.47x), E4B 18.3 -> 26.3 (1.44x), 12B 8.5 -> 12.9 (1.51x), 26B 16.9 -> 24.5 (1.44x)**; 64-83% of the drafts the planner chose to verify were accepted (on E4B llama.cpp with the same assistant accepts 50% of its drafts). The 12B's and 26B's assistants, 1024 wide, give a KV head count per layer, which is read as such.
+- Its drafts are picked, as the MTP blocks' are, from a head of 32768 token ids plus those met in the conversation, instead of all 262144: 8 MB read a draft instead of 67, for as many accepted.
+- E2B's and E4B's per-layer branch reads its f32 matrices (220 MB a token on E4B) once for all the tokens of a pass, with a vector dot product: passes over a few tokens 17% faster, single tokens 4%. `JANAS_DRAFT_VOCAB` sets the draft head's size, to experiment.
## [2026-09-27] - janas-try reports only this run
-- **A test report carries only the speeds this run measured.** The
- reports of issues #10 and #11 also showed the bench files earlier runs
- had left behind - another level, an older commit - as if they were
- new. They stay in the work directory, out of the report.
+- **A test report carries only the speeds this run measured.** The reports of issues #10 and #11 also showed the bench files earlier runs had left behind - another level, an older commit - as if they were new. They stay in the work directory, out of the report.
## [2026-09-27] - Why a build has no GPU
-- **A build without GPU support says what was missing.** The GPU needs
- both `glslangValidator` and the Vulkan headers when Janas is built; with
- the first and not the second (CachyOS without `vulkan-headers`) the build
- left the GPU out without a word, and `janas-try.sh` reported "built with
- GPU support". Now `build.sh` prints which piece is missing, the engine's
- "GPU: none usable" names it, `janas-try.sh` checks for the headers too,
- and the README gives the Arch packages.
+- **A build without GPU support says what was missing.** The GPU needs both `glslangValidator` and the Vulkan headers when Janas is built; with the first and not the second (CachyOS without `vulkan-headers`) the build left the GPU out without a word, and `janas-try.sh` reported "built with GPU support". Now `build.sh` prints which piece is missing, the engine's "GPU: none usable" names it, `janas-try.sh` checks for the headers too, and the README gives the Arch packages.
## [2026-09-27] - Gemma 4: E2B and E4B
-- **Gemma-4-E2B-it and E4B-it run and chat**, tools included. Each token
- brings a few numbers for every layer (per-layer embeddings): a row of a
- table of their own plus a projection of the embedding (bf16), which open
- a branch of the residual after each feed-forward. The table, half of
- E2B's file, is never loaded: a token's row, a few kilobytes, is read from
- the file when it is needed, so E2B runs in 1.5 GB of memory from a 3.1 GB
- file, E4B in 3.1 GB from 5.0 GB.
-- **The last layers share keys and values**: E2B's last 20 layers and
- E4B's last 18 compute queries only, and read the cache of the last
- earlier layer of their kind. E2B's feed-forward widens from 6,144 to
- 12,288 halfway; the engine takes a width per layer.
-- Against llama.cpp, 200 tokens of text: E2B agrees on the most likely
- token at 191 positions, E4B at 195; prompt blocks give the same bits as
- token by token.
-- **Without reasoning, E2B and E4B are no longer handed an empty thought
- channel**: their template does not write one (the 12B's and 26B's do),
- and given one they reasoned inside the reply. The chat template is now
- read whole: Gemma 4's is 19 KB, and the part after 16 KB was lost.
+- **Gemma-4-E2B-it and E4B-it run and chat**, tools included. Each token brings a few numbers for every layer (per-layer embeddings): a row of a table of their own plus a projection of the embedding (bf16), which open a branch of the residual after each feed-forward. The table, half of E2B's file, is never loaded: a token's row, a few kilobytes, is read from the file when it is needed, so E2B runs in 1.5 GB of memory from a 3.1 GB file, E4B in 3.1 GB from 5.0 GB.
+- **The last layers share keys and values**: E2B's last 20 layers and E4B's last 18 compute queries only, and read the cache of the last earlier layer of their kind. E2B's feed-forward widens from 6,144 to 12,288 halfway; the engine takes a width per layer.
+- Against llama.cpp, 200 tokens of text: E2B agrees on the most likely token at 191 positions, E4B at 195; prompt blocks give the same bits as token by token.
+- **Without reasoning, E2B and E4B are no longer handed an empty thought channel**: their template does not write one (the 12B's and 26B's do), and given one they reasoned inside the reply. The chat template is now read whole: Gemma 4's is 19 KB, and the part after 16 KB was lost.
## [2026-09-27] - Gemma 4: tools
-- **Gemma 4 calls tools**, in its own notation: the functions declared in
- the system turn (`<|tool>declaration:name{...}<tool|>`, parameters written
- as its template writes them, keys sorted), calls `call:name{key:value}`
- read into JSON, held by a grammar to a declared name and a well-formed
- value, and the tools' answers written inside the model's own turn, which
- it then continues. Checked token for token against the template rendered
- with Jinja: the first prompt with its declarations, a conversation loaded
- with a call and its answer (as `janas-server` gives it), and the answer
- appended live. Gemma-4-12B-it called a weather function with the right
- argument and used its answer.
+- **Gemma 4 calls tools**, in its own notation: the functions declared in the system turn (`<|tool>declaration:name{...}<tool|>`, parameters written as its template writes them, keys sorted), calls `call:name{key:value}` read into JSON, held by a grammar to a declared name and a well-formed value, and the tools' answers written inside the model's own turn, which it then continues. Checked token for token against the template rendered with Jinja: the first prompt with its declarations, a conversation loaded with a call and its answer (as `janas-server` gives it), and the answer appended live. Gemma-4-12B-it called a weather function with the right argument and used its answer.
## [2026-09-27] - Gemma 4: the 26B mixture, a sliding context, rings
-- **Gemma-4-26B-A4B-it runs and chats**: 128 experts (eight a token)
- beside a dense feed-forward, the two as branches of their own - each
- normalized on the way in and out, then summed - a router reading its own
- input, and a scale per expert, folded into its weight. `gguf2jns` splits
- gate and up, which the file keeps fused, and widens with zeros the
- feed-forwards that are not a multiple of 256 wide (704 and 2,112 here):
- every weight type reads zero bytes as zero weights, so the products are
- unchanged. Files that need no widening convert to the same bytes as
- before.
+- **Gemma-4-26B-A4B-it runs and chats**: 128 experts (eight a token) beside a dense feed-forward, the two as branches of their own - each normalized on the way in and out, then summed - a router reading its own input, and a scale per expert, folded into its weight. `gguf2jns` splits gate and up, which the file keeps fused, and widens with zeros the feed-forwards that are not a multiple of 256 wide (704 and 2,112 here): every weight type reads zero bytes as zero weights, so the products are unchanged. Files that need no widening convert to the same bytes as before.
- **The sliding-window layers keep a ring** of the positions they can see
- - the window and a prefill block, 1,536 for Gemma 4 - instead of the whole
- context, and attention skips the chunks before the window without reading
- them. The logits are the same to the bit with and without the ring
- (`JANAS_SWA_RING=0`), 1,500 tokens past the window; kept conversations,
- on disk too, come back with the same replies.
-- **A full context slides on Gemma 4 too**: each layer's keys turned back
- with its own RoPE (two kinds, the full layers with their frequency
- factors), sixteen-bit keys, the rings. Qwen models slide as before, to
- the bit.
+ - the window and a prefill block, 1,536 for Gemma 4 - instead of the whole context, and attention skips the chunks before the window without reading them. The logits are the same to the bit with and without the ring (`JANAS_SWA_RING=0`), 1,500 tokens past the window; kept conversations, on disk too, come back with the same replies.
+- **A full context slides on Gemma 4 too**: each layer's keys turned back with its own RoPE (two kinds, the full layers with their frequency factors), sixteen-bit keys, the rings. Qwen models slide as before, to the bit.
## [2026-09-26] - Gemma 4 in the chat
-- **Gemma-4-12B-it chats**: Gemma's format - `<bos>`, turns opened by
- `<|turn>` and closed by `<turn|>`, the assistant called "model" - with
- its reasoning on or off: on, `<|think|>` heads the system turn and the
- model writes its thought channel, shown as reasoning; off, the channel is
- written empty, as the template does. The prompts were checked token for
- token against the model's own template rendered with Jinja and tokenized
- by llama.cpp, with and without reasoning. No tools yet, and a full
- context stops the chat instead of sliding.
+- **Gemma-4-12B-it chats**: Gemma's format - `<bos>`, turns opened by `<|turn>` and closed by `<turn|>`, the assistant called "model" - with its reasoning on or off: on, `<|think|>` heads the system turn and the model writes its thought channel, shown as reasoning; off, the channel is written empty, as the template does. The prompts were checked token for token against the model's own template rendered with Jinja and tokenized by llama.cpp, with and without reasoning. No tools yet, and a full context stops the chat instead of sliding.
## [2026-09-26] - Gemma 4: keys and values at sixteen bits
-- **Gemma 4 keeps its keys and values at sixteen bits** (integers with the
- same scale per position and head, some 250 times finer than eight bits);
- the attention reads them through kernels of their own, the scores over
- the float query. Qwen models stay at eight bits, bit for bit as before;
- `JANAS_KV=8` or `16` overrides the choice. Against llama.cpp on 200
- tokens of prose: 160 most likely tokens in agreement and a mean logit
- difference of 0.84, against 143 and 1.53 at eight bits.
-- **A trap in the reference**: llama.cpp's logits of Gemma 4 depend on its
- batch size - with batches of 64 tokens or more, the early positions see
- later tokens. The comparisons above use batches of 8, which agree with a
- prompt of two tokens run alone. The earlier figures (175 of 200) were
- measured against the larger batches.
+- **Gemma 4 keeps its keys and values at sixteen bits** (integers with the same scale per position and head, some 250 times finer than eight bits); the attention reads them through kernels of their own, the scores over the float query. Qwen models stay at eight bits, bit for bit as before; `JANAS_KV=8` or `16` overrides the choice. Against llama.cpp on 200 tokens of prose: 160 most likely tokens in agreement and a mean logit difference of 0.84, against 143 and 1.53 at eight bits.
+- **A trap in the reference**: llama.cpp's logits of Gemma 4 depend on its batch size - with batches of 64 tokens or more, the early positions see later tokens. The comparisons above use batches of 8, which agree with a prompt of two tokens run alone. The earlier figures (175 of 200) were measured against the larger batches.
## [2026-09-26] - Why there is no GPU
-- **"GPU: none usable" now says why**: built without GPU support
- (`glslangValidator` missing at build time), no Vulkan loader, Vulkan
- seeing no GPU, the GPU turned down with its name and what its driver
- lacks (Vulkan below 1.3, a feature, the subgroup size), or turned off
- (eco mode, `JANAS_GPU=0`). The same reason is in the model's description
- (`janas_llm_describe`). A tester's RTX 5080 was reported as "none
- usable" with nothing more to go on.
-- **`janas-try` reports what Vulkan sees** (each device's name, kind and
- version), whether Janas will be built with GPU support, and whether it
- runs under WSL, before building and in the report.
+- **"GPU: none usable" now says why**: built without GPU support (`glslangValidator` missing at build time), no Vulkan loader, Vulkan seeing no GPU, the GPU turned down with its name and what its driver lacks (Vulkan below 1.3, a feature, the subgroup size), or turned off (eco mode, `JANAS_GPU=0`). The same reason is in the model's description (`janas_llm_describe`). A tester's RTX 5080 was reported as "none usable" with nothing more to go on.
+- **`janas-try` reports what Vulkan sees** (each device's name, kind and version), whether Janas will be built with GPU support, and whether it runs under WSL, before building and in the report.
## [2026-09-26] - Gemma 4, first part (not yet usable)
-- **Gemma 4 (`gemma4`) runs its forward pass**, on Gemma-4-12B-it: layers
- with a sliding window of 1,024 positions and every sixth a full one, each
- kind with its own head size (256 and 512), KV heads and RoPE (the full
- layers with Google's per-pair frequency factors); V taken from K where a
- layer has no V projection, and normalized; norms after attention and
- after the feed-forward, GELU, a scale per layer, soft-capped logits. The
- attention takes a sliding window and a score scale of its own, heads up
- to 512, and the KV cache is laid out per layer.
-- **Gemma's tokenizer**: BPE on UTF-8 characters with SentencePiece's
- spaces and byte tokens, in the same tokenizer as Qwen's. On a mixed text
- (Italian, English, code, CJK, emoji) it gives llama.cpp's 128 tokens.
-- **Not yet usable**: the chat does not know Gemma's format, and with the
- eight-bit KV cache the logits drift from llama.cpp's (the most likely
- token agrees at 175 of 200 positions, mean difference 1.36; llama.cpp
- agrees with itself at 169 when its cache goes from f16 to eight bits).
- Every Qwen model gives the same logits as before, to the bit.
+- **Gemma 4 (`gemma4`) runs its forward pass**, on Gemma-4-12B-it: layers with a sliding window of 1,024 positions and every sixth a full one, each kind with its own head size (256 and 512), KV heads and RoPE (the full layers with Google's per-pair frequency factors); V taken from K where a layer has no V projection, and normalized; norms after attention and after the feed-forward, GELU, a scale per layer, soft-capped logits. The attention takes a sliding window and a score scale of its own, heads up to 512, and the KV cache is laid out per layer.
+- **Gemma's tokenizer**: BPE on UTF-8 characters with SentencePiece's spaces and byte tokens, in the same tokenizer as Qwen's. On a mixed text (Italian, English, code, CJK, emoji) it gives llama.cpp's 128 tokens.
+- **Not yet usable**: the chat does not know Gemma's format, and with the eight-bit KV cache the logits drift from llama.cpp's (the most likely token agrees at 175 of 200 positions, mean difference 1.36; llama.cpp agrees with itself at 169 when its cache goes from f16 to eight bits). Every Qwen model gives the same logits as before, to the bit.
## [2026-09-26] - Long prompts: the expert cache, the tuner, the ETA (issue #9)
-- **The expert cache no longer thrashes on large prefill blocks.** A pass
- asks for experts layer after layer, and when one pass asks for more
- than the cache holds, least-recently-used eviction throws out exactly the
- expert wanted again soonest: on a 262K prompt of Qwen3-Next-80B, blocks
- of 256 read 2.17x the bytes of blocks of 64 (issue #9). In that case the
- victim is now the expert wanted again latest - the current layer's
- others, then the layer before, and back from there. Measured on the 80B
- (4,096 tokens, 12 GB of cache, four bits, blocks of 256): 238 GB read at
- 38.2 token/s before, 172 GB at 45.8 now; blocks of 64 are unchanged.
-- **The tuner tries alternatives ever more rarely while they lose**: at a
- fixed 128 passes it made one slow block every 32,768 tokens of a long
- prompt. The gap now doubles up to 1,024 passes and returns to 128 as soon
- as a try beats the choice.
-- **A prompt's time left follows the cost of a token as the context
- grows** (`input_eta_seconds`, new at the end of `janas_llm_chat_stats`
- and in `llm.bi`): a line in the position, fitted on the blocks read and
- integrated to the end of the prompt, instead of the latest speed, which
- promised 2.5 times too little at 32K of a 262K prompt.
+- **The expert cache no longer thrashes on large prefill blocks.** A pass asks for experts layer after layer, and when one pass asks for more than the cache holds, least-recently-used eviction throws out exactly the expert wanted again soonest: on a 262K prompt of Qwen3-Next-80B, blocks of 256 read 2.17x the bytes of blocks of 64 (issue #9). In that case the victim is now the expert wanted again latest - the current layer's others, then the layer before, and back from there. Measured on the 80B (4,096 tokens, 12 GB of cache, four bits, blocks of 256): 238 GB read at 38.2 token/s before, 172 GB at 45.8 now; blocks of 64 are unchanged.
+- **The tuner tries alternatives ever more rarely while they lose**: at a fixed 128 passes it made one slow block every 32,768 tokens of a long prompt. The gap now doubles up to 1,024 passes and returns to 128 as soon as a try beats the choice.
+- **A prompt's time left follows the cost of a token as the context grows** (`input_eta_seconds`, new at the end of `janas_llm_chat_stats` and in `llm.bi`): a line in the position, fitted on the blocks read and integrated to the end of the prompt, instead of the latest speed, which promised 2.5 times too little at 32K of a 262K prompt.
## [2026-09-26] - IQ3_S weights
-- **IQ3_S weights**, the last type unsloth's "UD" files of the Qwen
- family were missing: 256 weights in eight groups, each weight a level of
- a 512-entry grid, with its sign and a scale per group. A group's eight
- grid entries come in one gather, the signs go to the activations, and
- the integer sum is exact, one fma per 256 weights; AVX2 and AVX-VNNI
- give the reference's bits. The grid is ggml's, copied as data
- (`src/llm/iq3s_grid.h`, MIT, as ggml is) since it defines the format.
- The weights match ggml's to the bit on random blocks; Qwen3.5-0.8B
- requantized to IQ3_S agrees with llama.cpp at a mean logit difference of
- 0.123, the disagreements near-ties.
+- **IQ3_S weights**, the last type unsloth's "UD" files of the Qwen family were missing: 256 weights in eight groups, each weight a level of a 512-entry grid, with its sign and a scale per group. A group's eight grid entries come in one gather, the signs go to the activations, and the integer sum is exact, one fma per 256 weights; AVX2 and AVX-VNNI give the reference's bits. The grid is ggml's, copied as data (`src/llm/iq3s_grid.h`, MIT, as ggml is) since it defines the format. The weights match ggml's to the bit on random blocks; Qwen3.5-0.8B requantized to IQ3_S agrees with llama.cpp at a mean logit difference of 0.123, the disagreements near-ties.
## [2026-09-26] - Q3_K weights, and unsloth's UD files of Qwen3.5-9B
-- **Q3_K weights**: 256 three-bit values in sixteen groups with 6-bit
- scales. The values are summed unsigned (0-7) and the -4 of each is taken
- from the activations' block sums, so the integer sum of a block is exact
- and one fma follows, as for Q4_K; AVX2 and AVX-VNNI give the reference's
- bits. The weights match ggml's to the bit on random blocks; Qwen3.5-0.8B
- in Q3_K_M agrees with llama.cpp at a mean logit difference of 0.115.
-- **A DeltaNet's alpha and beta in F16 or BF16** are taken too: unsloth's
- "UD" files of Qwen3.5-9B keep them so. **Qwen3.5-9B UD-Q4_K_XL** - Q4_K,
- Q5_K, Q6_K, Q8_0, IQ4_XS and F16 in one file - runs and agrees with
- llama.cpp at 0.110, as its Q4_K_M does.
+- **Q3_K weights**: 256 three-bit values in sixteen groups with 6-bit scales. The values are summed unsigned (0-7) and the -4 of each is taken from the activations' block sums, so the integer sum of a block is exact and one fma follows, as for Q4_K; AVX2 and AVX-VNNI give the reference's bits. The weights match ggml's to the bit on random blocks; Qwen3.5-0.8B in Q3_K_M agrees with llama.cpp at a mean logit difference of 0.115.
+- **A DeltaNet's alpha and beta in F16 or BF16** are taken too: unsloth's "UD" files of Qwen3.5-9B keep them so. **Qwen3.5-9B UD-Q4_K_XL** - Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS and F16 in one file - runs and agrees with llama.cpp at 0.110, as its Q4_K_M does.
## [2026-09-26] - Q4_0, Q4_1 and Q5_1 weights
-- **Models quantized in Q4_0, Q4_1 and Q5_1 convert and run** - the types of
- Google's QAT Gemma files and of many older GGUFs. Q4_0 is IQ4_NL's layout
- with evenly spaced levels, so it runs IQ4_NL's kernel with another table;
- Q4_1 and Q5_1 (weights d x q + m, Q5_1 with a fifth bit) share a kernel
- that takes the minimum's share from the activations' block sums, exactly.
- On one to eight vectors, AVX2 and AVX-VNNI give the scalar reference's
- bits. Checked against ggml on 4,096 random blocks of each (the weights
- identical to the bit), and on Qwen3.5-0.8B against llama.cpp: the Q4_0
- file (which holds Q4_1 tensors too) at a mean logit difference of 0.109,
- a Q5_1 one requantized from the Q8_0 at 0.114, the disagreements
- near-ties.
-- A DeltaNet layer's alpha and beta are taken in any type Janas unpacks
- (they came in Q5_1 in the requantized file), not only f32 and Q8_0.
+- **Models quantized in Q4_0, Q4_1 and Q5_1 convert and run** - the types of Google's QAT Gemma files and of many older GGUFs. Q4_0 is IQ4_NL's layout with evenly spaced levels, so it runs IQ4_NL's kernel with another table; Q4_1 and Q5_1 (weights d x q + m, Q5_1 with a fifth bit) share a kernel that takes the minimum's share from the activations' block sums, exactly. On one to eight vectors, AVX2 and AVX-VNNI give the scalar reference's bits. Checked against ggml on 4,096 random blocks of each (the weights identical to the bit), and on Qwen3.5-0.8B against llama.cpp: the Q4_0 file (which holds Q4_1 tensors too) at a mean logit difference of 0.109, a Q5_1 one requantized from the Q8_0 at 0.114, the disagreements near-ties.
+- A DeltaNet layer's alpha and beta are taken in any type Janas unpacks (they came in Q5_1 in the requantized file), not only f32 and Q8_0.
## [2026-09-26] - IQ4_NL and IQ4_XS weights
-- **Models quantized in IQ4_NL and IQ4_XS convert and run**: the two 4-bit
- types whose sixteen levels are spaced unevenly, closer near zero, that
- many of the most downloaded GGUF files use. Their kernels are Q8_0's with
- a table lookup in front (one `pshufb` turns 32 indices into 32 weights),
- on one to eight vectors, AVX2 and AVX-VNNI giving the same bits as the
- scalar reference; IQ4_XS sums its eight scaled groups exactly and takes
- one fma per 256 weights. Checked against ggml on 4,096 random blocks of
- each (the unpacked weights identical to the bit) and on Qwen3.5-0.8B in
- both types against llama.cpp: mean logit difference 0.11, as the Q4_K_M
- file of the same model, and where the most likely token differs the two
- were within 0.46 of each other in llama.cpp's own logits.
-- Not yet: files that mix in IQ3_S or Q3_K (unsloth's "UD"
- quantizations), and the speed of these kernels, which has not been worked
- on - reading a prompt, Qwen3.5-0.8B went at 230 tok/s in IQ4_NL and 155 in
- IQ4_XS against 289 in Q4_K_M.
+- **Models quantized in IQ4_NL and IQ4_XS convert and run**: the two 4-bit types whose sixteen levels are spaced unevenly, closer near zero, that many of the most downloaded GGUF files use. Their kernels are Q8_0's with a table lookup in front (one `pshufb` turns 32 indices into 32 weights), on one to eight vectors, AVX2 and AVX-VNNI giving the same bits as the scalar reference; IQ4_XS sums its eight scaled groups exactly and takes one fma per 256 weights. Checked against ggml on 4,096 random blocks of each (the unpacked weights identical to the bit) and on Qwen3.5-0.8B in both types against llama.cpp: mean logit difference 0.11, as the Q4_K_M file of the same model, and where the most likely token differs the two were within 0.46 of each other in llama.cpp's own logits.
+- Not yet: files that mix in IQ3_S or Q3_K (unsloth's "UD" quantizations), and the speed of these kernels, which has not been worked on - reading a prompt, Qwen3.5-0.8B went at 230 tok/s in IQ4_NL and 155 in IQ4_XS against 289 in Q4_K_M.
## [2026-09-26] - `janas-bench` measures the drafts as a chat meets them
-- **The "with MTP" figures were too high, and this is why.** `janas-bench`
- measured the prediction block by continuing its own prompt, one paragraph
- repeated, greedily - and a model continuing prose copies the paragraphs
- it has seen, which the block guesses almost every time. On Qwen3.5-2B it
- kept 95% of its drafts there and reported 107 tok/s; a real chat with the
- same model kept 34-68% and wrote at 43-62. Every "with drafts" figure in
- the README until today (Qwen3-Next-80B-A3B 30, Qwen3.6-35B-A3B 29,
- Qwen3.5-9B 26, Qwen3.5-2B 107) came from that measurement.
-- **Now the block is measured on a chat reply**: an ordinary question in the
- model's chat format, the first 64 tokens of the answer, once greedy and
- once sampled as the chat samples (temperature 0.7, top-k 20, top-p 0.8,
- fixed seed), each with the share of drafts kept. The prompt for the
- reading speed is prose that does not repeat itself; three rounds by
- default, as the README always said (it was two).
-- What the block is worth depends on the text: on Qwen3.5-2B, 68% of the
- drafts kept on an English explanation, 34% on Italian prose, where the
- engine drafts less and the gain all but goes.
-- **The chat runs on the cores `janas-bench` measures**: every usable core,
- the performance cores with their threads and the efficiency cores, never
- the low-power island. The tuner used to try one thread per performance
- core and their threads alone as well, and after a stretch of long context
- a chat could settle on 12 threads where the bench had reported 20: the
- same machine, two speeds. Measured on six models, from Qwen3.5-2B to
- Qwen3-Next-80B-A3B, all the cores were the fastest or level in every kind
- of pass, and the others lost 5-20% writing; so the threads are fixed now,
- and the tuner only decides whether the GPU helps. `JANAS_TUNE_THREADS=1`
- brings the other counts back, to experiment with.
-- **`janas-bench` reports what the engine will run**: its result line is the
- configuration the engine chose for each kind of pass, as a chat or the
- server will use it, not the fastest figure of each column.
+- **The "with MTP" figures were too high, and this is why.** `janas-bench` measured the prediction block by continuing its own prompt, one paragraph repeated, greedily - and a model continuing prose copies the paragraphs it has seen, which the block guesses almost every time. On Qwen3.5-2B it kept 95% of its drafts there and reported 107 tok/s; a real chat with the same model kept 34-68% and wrote at 43-62. Every "with drafts" figure in the README until today (Qwen3-Next-80B-A3B 30, Qwen3.6-35B-A3B 29, Qwen3.5-9B 26, Qwen3.5-2B 107) came from that measurement.
+- **Now the block is measured on a chat reply**: an ordinary question in the model's chat format, the first 64 tokens of the answer, once greedy and once sampled as the chat samples (temperature 0.7, top-k 20, top-p 0.8, fixed seed), each with the share of drafts kept. The prompt for the reading speed is prose that does not repeat itself; three rounds by default, as the README always said (it was two).
+- What the block is worth depends on the text: on Qwen3.5-2B, 68% of the drafts kept on an English explanation, 34% on Italian prose, where the engine drafts less and the gain all but goes.
+- **The chat runs on the cores `janas-bench` measures**: every usable core, the performance cores with their threads and the efficiency cores, never the low-power island. The tuner used to try one thread per performance core and their threads alone as well, and after a stretch of long context a chat could settle on 12 threads where the bench had reported 20: the same machine, two speeds. Measured on six models, from Qwen3.5-2B to Qwen3-Next-80B-A3B, all the cores were the fastest or level in every kind of pass, and the others lost 5-20% writing; so the threads are fixed now, and the tuner only decides whether the GPU helps. `JANAS_TUNE_THREADS=1` brings the other counts back, to experiment with.
+- **`janas-bench` reports what the engine will run**: its result line is the configuration the engine chose for each kind of pass, as a chat or the server will use it, not the fastest figure of each column.
## [2026-09-26] - Qwen3.5 dense models
-- **Measured** on the development laptop, idle, `janas-bench`: Qwen3.5-9B
- reads a prompt at 46 tok/s and writes at 13, **22 with the block** in a
- chat; Qwen3.5-2B at 215, 49 and **75**. (First published as 26 and 107,
- with the block measured on repeated text: see the entry above.)
- llama.cpp on the same 9B file and machine (`llama-bench`, build of 18
- September) did best at 32 and 9.0.
- README and MODELS.md list the three dense Qwen3.5 models, their
- fingerprints and how to get their block (`hf:` with the checkpoint's
- revision).
-- **The dense Qwen3.5 models run** (`qwen35`: Qwen3.5, 3.6 and 3.8 without
- experts, half of the GGUF downloads on Hugging Face): the layers of
- Qwen3.6-35B-A3B with a dense feed-forward, one row of the architecture
- table. The DeltaNet's alpha and beta come in Q8_0 in these files and are
- made f32 once, exactly, at load. Checked against llama.cpp on the same
- files, 400 tokens of Italian prose and 400 of Pascal: Qwen3.5-0.8B agrees
- on the most likely token at 387 and 386 positions, Qwen3.5-2B at 376 and
- 388, mean logit difference 0.10-0.13, and where they differ the two
- candidates were within 0.53 of each other in llama.cpp's own logits.
- Chat and tool calls (XML) work through `janas-chat` and `janas-server`.
-- **`hf2jns_mtp` converts the MTP block of a dense Qwen3.5** too, its
- feed-forward as the one slot, and takes the block from several shards
- (`hf2jns_mtp <main.jns> <shard>... <out.jns>`): Qwen3.5-9B spreads it
- over three. The number and shape of the experts come from the model and
- the checkpoint instead of Qwen3-Next's written in; its block converts to
- the same file as before, to the byte. On Qwen3.5-9B the drafts are
- accepted at 53% (prose) and 68% (code), the text the same as without.
-- **`hf2jns_mtp <main.jns> hf:<owner>/<repo> <out.jns>` reads the MTP
- block straight from Hugging Face**, with range requests: only the
- `mtp.*` tensors, 487 MB of Qwen3.5-9B's 14 GB of shards, in under a
- minute, with no other program (Janas's own HTTPS client, the one of its
- MCP transport, now following redirects). The file it writes is the same,
- to the byte, as from the shards on disk. A server that ignores a range
- stops it, never a whole file downloaded. Qwen3.5-2B's block too: drafts
- accepted at 78% and 64%. Neighbouring tensors are read in one request (up
- to 256 MB): Qwen3-Next's block, 1,500 tensors, came in 27 minutes one
- connection each and comes in 5 now, to the same bytes.
-- The memory counted for the context asks the architecture table which
- layers have keys and values, instead of two names written in.
+- **Measured** on the development laptop, idle, `janas-bench`: Qwen3.5-9B reads a prompt at 46 tok/s and writes at 13, **22 with the block** in a chat; Qwen3.5-2B at 215, 49 and **75**. (First published as 26 and 107, with the block measured on repeated text: see the entry above.) llama.cpp on the same 9B file and machine (`llama-bench`, build of 18 September) did best at 32 and 9.0. README and MODELS.md list the three dense Qwen3.5 models, their fingerprints and how to get their block (`hf:` with the checkpoint's revision).
+- **The dense Qwen3.5 models run** (`qwen35`: Qwen3.5, 3.6 and 3.8 without experts, half of the GGUF downloads on Hugging Face): the layers of Qwen3.6-35B-A3B with a dense feed-forward, one row of the architecture table. The DeltaNet's alpha and beta come in Q8_0 in these files and are made f32 once, exactly, at load. Checked against llama.cpp on the same files, 400 tokens of Italian prose and 400 of Pascal: Qwen3.5-0.8B agrees on the most likely token at 387 and 386 positions, Qwen3.5-2B at 376 and 388, mean logit difference 0.10-0.13, and where they differ the two candidates were within 0.53 of each other in llama.cpp's own logits. Chat and tool calls (XML) work through `janas-chat` and `janas-server`.
+- **`hf2jns_mtp` converts the MTP block of a dense Qwen3.5** too, its feed-forward as the one slot, and takes the block from several shards (`hf2jns_mtp <main.jns> <shard>... <out.jns>`): Qwen3.5-9B spreads it over three. The number and shape of the experts come from the model and the checkpoint instead of Qwen3-Next's written in; its block converts to the same file as before, to the byte. On Qwen3.5-9B the drafts are accepted at 53% (prose) and 68% (code), the text the same as without.
+- **`hf2jns_mtp <main.jns> hf:<owner>/<repo> <out.jns>` reads the MTP block straight from Hugging Face**, with range requests: only the `mtp.*` tensors, 487 MB of Qwen3.5-9B's 14 GB of shards, in under a minute, with no other program (Janas's own HTTPS client, the one of its MCP transport, now following redirects). The file it writes is the same, to the byte, as from the shards on disk. A server that ignores a range stops it, never a whole file downloaded. Qwen3.5-2B's block too: drafts accepted at 78% and 64%. Neighbouring tensors are read in one request (up to 256 MB): Qwen3-Next's block, 1,500 tensors, came in 27 minutes one connection each and comes in 5 now, to the same bytes.
+- The memory counted for the context asks the architecture table which layers have keys and values, instead of two names written in.
## [2026-09-26] - Architectures as data
-- **What sets one architecture apart from another is a row of a table**
- (`src/llm/arch.c`): recurrent layers and their layout, a gated query,
- a shared expert, which norm comes before the feed-forward, how value
- heads share key heads, MTP layers in the file. The flags `next` and
- `q35` are gone; a new family is a row plus the code of what it has that
- no other had. The logits are the same bits as before on Qwen3-4B,
- Qwen3-30B-A3B, Qwen3.6-35B-A3B and Qwen3-Next-80B-A3B, token by token
- and in blocks, and so are the MTP drafts of the 35B and the 80B.
-- **`model.c` divided by what it does**: it was 2,597 lines; the passes
- stay in it, the attention, DeltaNet and feed-forward layers, opening and
- closing, and the threads with the experts' profile each have a file of
- their own (`model_attn.c`, `model_rec.c`, `model_ffn.c`, `model_load.c`,
- `model_tune.c`). Code moved, not changed: the same bits again on the four
- models.
-- **`build.sh` makes its archives anew** every time: `ar` only adds and
- replaces, so the object of a source since removed or renamed stayed in
- `libjanas.a` and was linked twice (going back to an older commit failed
- to link).
+- **What sets one architecture apart from another is a row of a table** (`src/llm/arch.c`): recurrent layers and their layout, a gated query, a shared expert, which norm comes before the feed-forward, how value heads share key heads, MTP layers in the file. The flags `next` and `q35` are gone; a new family is a row plus the code of what it has that no other had. The logits are the same bits as before on Qwen3-4B, Qwen3-30B-A3B, Qwen3.6-35B-A3B and Qwen3-Next-80B-A3B, token by token and in blocks, and so are the MTP drafts of the 35B and the 80B.
+- **`model.c` divided by what it does**: it was 2,597 lines; the passes stay in it, the attention, DeltaNet and feed-forward layers, opening and closing, and the threads with the experts' profile each have a file of their own (`model_attn.c`, `model_rec.c`, `model_ffn.c`, `model_load.c`, `model_tune.c`). Code moved, not changed: the same bits again on the four models.
+- **`build.sh` makes its archives anew** every time: `ar` only adds and replaces, so the object of a source since removed or renamed stayed in `libjanas.a` and was linked twice (going back to an older commit failed to link).
## [2026-09-26] - Qwen3-Coder's tool calls, run
-- **Qwen3-Coder-Next calls tools through `janas-server`**, in the XML way
- its template describes: asked for the weather and a list of files, it
- made both calls at once with valid arguments, and used their answers in
- the reply; the second turn read 66 new tokens and reused 496. The README
- no longer calls this way untried.
+- **Qwen3-Coder-Next calls tools through `janas-server`**, in the XML way its template describes: asked for the weather and a list of files, it made both calls at once with valid arguments, and used their answers in the reply; the second turn read 66 new tokens and reused 496. The README no longer calls this way untried.
## [2026-09-25] - Builds with clang
-- **`janas-try.sh` no longer skips a 16 GB machine**: it compared the
- memory the kernel reports with 16 GiB exactly, and a machine sold with
- 16 GB shows less (the kernel and an integrated GPU keep some), so every
- one of them lost the medium and full levels, and an 8 GB one the quick
- level. 85% of the memory a level asks for now counts as enough.
-- **`CC=clang ./build.sh` works** (clang 19, every variant under `-Werror`):
- two float conversions of `RAND_MAX` in the benchmarks, a string
- concatenation clang took for a missing comma in `test_grammar`, and the
- `die` of the two converters marked as not returning. The test suite
- passes, and the 4B's answer at temperature 0 is the same text built with
- gcc or clang, with AVX-VNNI or AVX2 kernels.
+- **`janas-try.sh` no longer skips a 16 GB machine**: it compared the memory the kernel reports with 16 GiB exactly, and a machine sold with 16 GB shows less (the kernel and an integrated GPU keep some), so every one of them lost the medium and full levels, and an 8 GB one the quick level. 85% of the memory a level asks for now counts as enough.
+- **`CC=clang ./build.sh` works** (clang 19, every variant under `-Werror`): two float conversions of `RAND_MAX` in the benchmarks, a string concatenation clang took for a missing comma in `test_grammar`, and the `die` of the two converters marked as not returning. The test suite passes, and the 4B's answer at temperature 0 is the same text built with gcc or clang, with AVX-VNNI or AVX2 kernels.
## [2026-09-25] - `tools/janas-try.sh`: try Janas and report, in one command
-- **One command to try Janas on a machine**: it builds and tests, downloads
- a model (quick 4B, medium 35B-A3B, full 80B-A3B with MTP), checks every
- file against its SHA-256 and every conversion against MODELS.md,
- checks the answer at temperature 0 against the text every machine should
- write (the same with any thread count, AVX2 or AVX-VNNI, GPU or not),
- measures with `janas-bench`, tries `janas-server`, and writes a report
- with no names or paths. It asks before each long step and before sending;
- the issue goes through `gh`, or a link fills the new **test report**
- form. Nothing to install, no root.
-- **It measures only a machine left to itself**, or says it did not: before
- the speed test it samples how idle the CPU is for five seconds and, when
- something else is running, explains that the numbers would not be the
- machine's and offers to wait, measure all the same or skip. The report
- says how idle the CPU was and the load average - general figures only,
- never which programs ran.
-- MODELS.md: the fingerprint of the MTP block is the one of the file
- `hf2jns_mtp` writes since issue #6.
+- **One command to try Janas on a machine**: it builds and tests, downloads a model (quick 4B, medium 35B-A3B, full 80B-A3B with MTP), checks every file against its SHA-256 and every conversion against MODELS.md, checks the answer at temperature 0 against the text every machine should write (the same with any thread count, AVX2 or AVX-VNNI, GPU or not), measures with `janas-bench`, tries `janas-server`, and writes a report with no names or paths. It asks before each long step and before sending; the issue goes through `gh`, or a link fills the new **test report** form. Nothing to install, no root.
+- **It measures only a machine left to itself**, or says it did not: before the speed test it samples how idle the CPU is for five seconds and, when something else is running, explains that the numbers would not be the machine's and offers to wait, measure all the same or skip. The report says how idle the CPU was and the load average - general figures only, never which programs ran.
+- MODELS.md: the fingerprint of the MTP block is the one of the file `hf2jns_mtp` writes since issue #6.
## [2026-09-25] - The converter is C: nothing but the build to run Janas
-- **`gguf2jns` is now a C program**, built with everything else, in place
- of the Python script: trying Janas needs a compiler and nothing more. It
- writes the very same bytes - the SHA-256 fingerprints in MODELS.md,
- taken from the Python one, come out identical for Qwen3-4B, Qwen3-30B-A3B
- and Qwen3-Embedding-0.6B.
-- Its GGUF reader (`src/llm/gguf.c`) takes nothing on trust: lengths and
- counts checked against the bytes there are, every tensor's data against
- the size of the file; `test_gguf` fuzzes it.
+- **`gguf2jns` is now a C program**, built with everything else, in place of the Python script: trying Janas needs a compiler and nothing more. It writes the very same bytes - the SHA-256 fingerprints in MODELS.md, taken from the Python one, come out identical for Qwen3-4B, Qwen3-30B-A3B and Qwen3-Embedding-0.6B.
+- Its GGUF reader (`src/llm/gguf.c`) takes nothing on trust: lengths and counts checked against the bytes there are, every tensor's data against the size of the file; `test_gguf` fuzzes it.
## [2026-09-25] - `max_tokens` is the answer's; Open WebUI tried
-- **In janas-server's chat completions, `max_tokens` limits the answer
- alone**, the reasoning not counted; `max_completion_tokens` (and the
- Responses API's `max_output_tokens`) still counts both, as OpenAI defines
- it. Open WebUI asks for a chat's title with `max_tokens` 1000, and with a
- model that reasons at length the reasoning used it all: no title. The
- library has `max_answer` for it, beside `max_reply`.
-- **Open WebUI 0.11.4 tried against janas-server** through its API:
- streamed chat, titles, tags, follow-up suggestions, a document indexed
- with Janas's embeddings and answered from; the conversations kept
- computed across its side requests. The README says how to run them
- together (`--think off`).
+- **In janas-server's chat completions, `max_tokens` limits the answer alone**, the reasoning not counted; `max_completion_tokens` (and the Responses API's `max_output_tokens`) still counts both, as OpenAI defines it. Open WebUI asks for a chat's title with `max_tokens` 1000, and with a model that reasons at length the reasoning used it all: no title. The library has `max_answer` for it, beside `max_reply`.
+- **Open WebUI 0.11.4 tried against janas-server** through its API: streamed chat, titles, tags, follow-up suggestions, a document indexed with Janas's embeddings and answered from; the conversations kept computed across its side requests. The README says how to run them together (`--think off`).
## [2026-09-25] - The MTP block of Qwen3-Next loads again (issue #6)
-- **`hf2jns_mtp` wrote a file the engine refused** since model files gained
- levels (version 3, bit planes): its layer's levels were left at zero, and
- loading it with `--mtp` failed with `layer 0: bad levels`. It writes them
- now, and a file it wrote before is read as what it meant (a slot with no
- planes), so nothing has to be converted again.
+- **`hf2jns_mtp` wrote a file the engine refused** since model files gained levels (version 3, bit planes): its layer's levels were left at zero, and loading it with `--mtp` failed with `layer 0: bad levels`. It writes them now, and a file it wrote before is read as what it meant (a slot with no planes), so nothing has to be converted again.
- The error of an MTP file now names that file, not the model's.
-- `jns_check` says when a file has such levels, and that converting it
- again is optional.
+- `jns_check` says when a file has such levels, and that converting it again is optional.
## [2026-09-25] - MCP: a cancel between rounds, the servers' instructions
-- **janas-server**: a `/responses/{id}/cancel` arriving between two MCP
- rounds of a background response now stops it - the next round is no
- longer started, and the tool call running is stopped too. Checked under
- ThreadSanitizer.
-- **janas-mcp works under Claude Code** (2.1.282, which speaks revision
- 2026-07-28): its discover and tools/list results now carry the caching
- hints that revision requires (`ttlMs`, `cacheScope`), without which Claude
- Code refused the tool list. generate and embed tried from it.
+- **janas-server**: a `/responses/{id}/cancel` arriving between two MCP rounds of a background response now stops it - the next round is no longer started, and the tool call running is stopped too. Checked under ThreadSanitizer.
+- **janas-mcp works under Claude Code** (2.1.282, which speaks revision 2026-07-28): its discover and tools/list results now carry the caching hints that revision requires (`ttlMs`, `cacheScope`), without which Claude Code refused the tool list. generate and embed tried from it.
- `JANAS_METRICS` naming a file that cannot be opened is now said on stderr.
-- **Tried against servers of others**: the reference filesystem and git
- servers over stdio (npx, uvx), DeepWiki over HTTPS from the client and
- from janas-server's Responses API through the `openai` SDK.
-- **janas-chat `--mcp-instructions`**: what the MCP servers say of their
- tools goes after the system message, marked as theirs (off by default).
- `janas_mcp_instructions` in libjanas_mcp gives it to any program.
+- **Tried against servers of others**: the reference filesystem and git servers over stdio (npx, uvx), DeepWiki over HTTPS from the client and from janas-server's Responses API through the `openai` SDK.
+- **janas-chat `--mcp-instructions`**: what the MCP servers say of their tools goes after the system message, marked as theirs (off by default). `janas_mcp_instructions` in libjanas_mcp gives it to any program.
## [2026-09-25] - A long prompt says how it goes, and what it costs
-Asked for in issue #5, after a 262,144-token run that read its prompt for
-fifteen hours without a word.
-
-- **The prompt is read a block at a time**: `janas_llm_chat_next` returns an
- empty piece after each block of 256 tokens, so a program has control
- while a long prompt is read - to show progress, or to stop (janas-server
- now stops a cancelled request in the middle of its prompt). Same speed as
- before, measured.
-- **`janas_llm_chat_stats` says more**, appended to the struct: the stage,
- the tokens read so far, time to the first token, time building the
- prompt, processor time of the reading, the threads chosen, the memory of
- the context and the process's peak, and the prompt by its parts (system
- message and tools, conversation, last message).
-- **`max_input`** in the chat's parameters, and `--max-input` in
- janas-server: a longer prompt is refused with its numbers
- (`JANAS_LLM_ELIMIT`; a 400 `input_limit_exceeded` with `input_tokens`,
- `max_input_tokens`, `excess_tokens`), never cut. `--warn-input` takes it
- and says so.
-- **`JANAS_PROGRESS` and `JANAS_METRICS`** for any program on the library:
- progress lines on stderr, and JSON lines of events (open, prompt,
- progress, first token, reply, refused), counters only, never text.
- janas-chat shows the progress in its status line, has `/context` and
- `--progress`; janas-server has `--metrics` and `--progress`.
-- Documented: the prompt is read in `janas_llm_chat_next`, not when it is
- sent or loaded; `context_used` holds the token that ended the reply,
- hence prompt + output + 1.
+Asked for in issue #5, after a 262,144-token run that read its prompt for fifteen hours without a word.
+
+- **The prompt is read a block at a time**: `janas_llm_chat_next` returns an empty piece after each block of 256 tokens, so a program has control while a long prompt is read - to show progress, or to stop (janas-server now stops a cancelled request in the middle of its prompt). Same speed as before, measured.
+- **`janas_llm_chat_stats` says more**, appended to the struct: the stage, the tokens read so far, time to the first token, time building the prompt, processor time of the reading, the threads chosen, the memory of the context and the process's peak, and the prompt by its parts (system message and tools, conversation, last message).
+- **`max_input`** in the chat's parameters, and `--max-input` in janas-server: a longer prompt is refused with its numbers (`JANAS_LLM_ELIMIT`; a 400 `input_limit_exceeded` with `input_tokens`, `max_input_tokens`, `excess_tokens`), never cut. `--warn-input` takes it and says so.
+- **`JANAS_PROGRESS` and `JANAS_METRICS`** for any program on the library: progress lines on stderr, and JSON lines of events (open, prompt, progress, first token, reply, refused), counters only, never text. janas-chat shows the progress in its status line, has `/context` and `--progress`; janas-server has `--metrics` and `--progress`.
+- Documented: the prompt is read in `janas_llm_chat_next`, not when it is sent or loaded; `context_used` holds the token that ended the reply, hence prompt + output + 1.
## [2026-09-25] - MCP servers in janas-server's Responses API
-- **Tools of type `mcp` in `POST /v1/responses`**, as OpenAI's API has
- them: the server reaches the MCP server a request names (`server_url`,
- `headers`, `authorization`) through libjanas_mcp, starts the output with
- an `mcp_list_tools` item, and gives the tools to the model as
- `server_label__tool`. A call needing approval (`require_approval`,
- `always` by default) ends the response with an `mcp_approval_request`
- and runs when an `mcp_approval_response` answers it; one that needs none
- runs at once as an `mcp_call` item and the model goes on in the same
- response, a round at a time. `allowed_tools`, the approval filters,
- `tool_choice` of type `mcp`, streamed `response.mcp_*` events, and the
- items read back from the history. `--no-mcp` refuses them.
+- **Tools of type `mcp` in `POST /v1/responses`**, as OpenAI's API has them: the server reaches the MCP server a request names (`server_url`, `headers`, `authorization`) through libjanas_mcp, starts the output with an `mcp_list_tools` item, and gives the tools to the model as `server_label__tool`. A call needing approval (`require_approval`, `always` by default) ends the response with an `mcp_approval_request` and runs when an `mcp_approval_response` answers it; one that needs none runs at once as an `mcp_call` item and the model goes on in the same response, a round at a time. `allowed_tools`, the approval filters, `tool_choice` of type `mcp`, streamed `response.mcp_*` events, and the items read back from the history. `--no-mcp` refuses them.
## [2026-09-25] - https:// MCP servers
-- **TLS for the MCP client**, on **Mbed TLS 4.2.0** compiled in
- (`src/third_party/mbedtls`, unmodified, with TF-PSA-Crypto): `https://`
- servers from libjanas_mcp and janas-chat, TLS 1.2 and 1.3, the server's
- certificate checked against the system's certificate authorities
- (`SSL_CERT_FILE` and `SSL_CERT_DIR` override them) and against the host
- name. Mbed TLS's symbols stay hidden inside libjanas_mcp; libjanas_llm
- has none of it.
+- **TLS for the MCP client**, on **Mbed TLS 4.2.0** compiled in (`src/third_party/mbedtls`, unmodified, with TF-PSA-Crypto): `https://` servers from libjanas_mcp and janas-chat, TLS 1.2 and 1.3, the server's certificate checked against the system's certificate authorities (`SSL_CERT_FILE` and `SSL_CERT_DIR` override them) and against the host name. Mbed TLS's symbols stay hidden inside libjanas_mcp; libjanas_llm has none of it.
## [2026-09-25] - MCP servers over HTTP
-- **libjanas_mcp reaches servers over Streamable HTTP** (`janas_mcp_open_url`,
- or `url` and `headers` in the configuration, so janas-chat uses them too):
- every message a POST, the answer a JSON object or an event stream, the
- body's fields mirrored into `MCP-Protocol-Version`, `Mcp-Method`,
- `Mcp-Name` and the `Mcp-Param-*` headers a tool's schema asks for with
- `x-mcp-header` (base64 where a header cannot carry the value; tools whose
- marks break the rules are left out). Both eras: a modern server found by
- its answer to `server/discover`, a legacy one by its refusal, then
- `initialize` and its session, ended with DELETE. `https://` needs TLS,
- which is not built in yet.
+- **libjanas_mcp reaches servers over Streamable HTTP** (`janas_mcp_open_url`, or `url` and `headers` in the configuration, so janas-chat uses them too): every message a POST, the answer a JSON object or an event stream, the body's fields mirrored into `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` and the `Mcp-Param-*` headers a tool's schema asks for with `x-mcp-header` (base64 where a header cannot carry the value; tools whose marks break the rules are left out). Both eras: a modern server found by its answer to `server/discover`, a legacy one by its refusal, then `initialize` and its session, ended with DELETE. `https://` needs TLS, which is not built in yet.
## [2026-09-25] - Janas as an MCP server
-- **`janas-mcp`**: the model offered to MCP clients (Claude Code, editors,
- agents) over stdio, as the tools `generate` (a question to the model, its
- answer back) and `embed` (with `--embedding-model`). Both protocol eras:
- requests of revision 2026-07-28 served statelessly, and the `initialize`
- handshake for revisions 2025-11-25 back to 2024-11-05. Pings are answered
- during a generation, and `notifications/cancelled` stops it.
+- **`janas-mcp`**: the model offered to MCP clients (Claude Code, editors, agents) over stdio, as the tools `generate` (a question to the model, its answer back) and `embed` (with `--embedding-model`). Both protocol eras: requests of revision 2026-07-28 served statelessly, and the `initialize` handshake for revisions 2025-11-25 back to 2024-11-05. Pings are answered during a generation, and `notifications/cancelled` stops it.
## [2026-09-25] - Tools from MCP servers in the chat
-- **janas-chat gives the model the tools of MCP servers**: those listed in
- `~/.config/janas/mcp.json` (or `--mcp-config FILE`), in the `mcpServers`
- format of the other clients, started as child processes and spoken to
- over stdio, in both eras of the protocol - the stateless revision
- 2026-07-28, found by probing with `server/discover`, and the handshake of
- 2025-11-25 for the servers that predate it. Every call is shown and waits
- for yes, no or always-this-tool; `/mcp auto` and `--mcp-auto` run them
- without asking, `/mcp` lists servers and tools, `--no-mcp` starts none.
-- **`libjanas_mcp`**, the client as a library of its own
- (`include/janas/mcp.h`, and `mcp.bi` for FreeBASIC), with nothing of the
- engine in it.
-- **`janas_llm_chat_send_results`** in `libjanas_llm`: what the tools
- answered to the calls of the last reply, sent in the conversation the
- library keeps, the model's reply following as after a message.
-- `tests/mcp_fake_server` and `test_mcp`: the client against a server of
- each era, and the readers of JSON-RPC lines and configuration files fuzzed.
+- **janas-chat gives the model the tools of MCP servers**: those listed in `~/.config/janas/mcp.json` (or `--mcp-config FILE`), in the `mcpServers` format of the other clients, started as child processes and spoken to over stdio, in both eras of the protocol - the stateless revision 2026-07-28, found by probing with `server/discover`, and the handshake of 2025-11-25 for the servers that predate it. Every call is shown and waits for yes, no or always-this-tool; `/mcp auto` and `--mcp-auto` run them without asking, `/mcp` lists servers and tools, `--no-mcp` starts none.
+- **`libjanas_mcp`**, the client as a library of its own (`include/janas/mcp.h`, and `mcp.bi` for FreeBASIC), with nothing of the engine in it.
+- **`janas_llm_chat_send_results`** in `libjanas_llm`: what the tools answered to the calls of the last reply, sent in the conversation the library keeps, the model's reply following as after a message.
+- `tests/mcp_fake_server` and `test_mcp`: the client against a server of each era, and the readers of JSON-RPC lines and configuration files fuzzed.
## [2026-09-24] - The memory left to other programs can be chosen
-- **`--reserve GIB`** in janas-chat, janas-server and janas-bench, and
- `janas_llm_params.reserve_bytes` in the library: when the expert cache
- takes the free memory, how much of it stays free for the rest of the
- machine. The default is unchanged, a fifth of the memory and at least 2
- GiB. More keeps a busy desktop out of swap, at the price of a smaller
- cache on a model larger than the memory: on the 32 GB test machine,
- Qwen3-Next-80B-A3B's cache went from 20.6 to 18.8 GiB with `--reserve 8`.
- The conversations kept computed size their automatic ceiling on it too.
+- **`--reserve GIB`** in janas-chat, janas-server and janas-bench, and `janas_llm_params.reserve_bytes` in the library: when the expert cache takes the free memory, how much of it stays free for the rest of the machine. The default is unchanged, a fifth of the memory and at least 2 GiB. More keeps a busy desktop out of swap, at the price of a smaller cache on a model larger than the memory: on the 32 GB test machine, Qwen3-Next-80B-A3B's cache went from 20.6 to 18.8 GiB with `--reserve 8`. The conversations kept computed size their automatic ceiling on it too.
## [2026-09-24] - Prompts read in blocks of 256 tokens
-- **A prompt is now read 256 tokens at a pass instead of 64**, so that a
- mixture-of-experts model reads each expert once for four times as many
- tokens, and gives it enough of them to run at full speed. Attention and
- the recurrent log still work 64 tokens at a time inside the block, and
- the logits are bit for bit those of reading token by token (checked on
- Qwen3-4B, Qwen3-30B-A3B and Qwen3-Next-80B-A3B). Reading a 1024-token
- prompt: Qwen3-Next-80B-A3B 68.4 → 75.1 tokens/s (+9.9%), Qwen3-30B-A3B
- 92.4 → 97.5 (+5.5%), the dense Qwen3-4B unchanged (87.9 → 87.3). Replies
- are as fast as before. `JANAS_PREFILL_BLOCK` (64 to 4096) sets another
- size; larger blocks gained nothing more here, and 1024 was slower on
- Qwen3-4B and on Qwen3-Next-80B-A3B.
+- **A prompt is now read 256 tokens at a pass instead of 64**, so that a mixture-of-experts model reads each expert once for four times as many tokens, and gives it enough of them to run at full speed. Attention and the recurrent log still work 64 tokens at a time inside the block, and the logits are bit for bit those of reading token by token (checked on Qwen3-4B, Qwen3-30B-A3B and Qwen3-Next-80B-A3B). Reading a 1024-token prompt: Qwen3-Next-80B-A3B 68.4 → 75.1 tokens/s (+9.9%), Qwen3-30B-A3B 92.4 → 97.5 (+5.5%), the dense Qwen3-4B unchanged (87.9 → 87.3). Replies are as fast as before. `JANAS_PREFILL_BLOCK` (64 to 4096) sets another size; larger blocks gained nothing more here, and 1024 was slower on Qwen3-4B and on Qwen3-Next-80B-A3B.
## [2026-09-24] - The chat's cache share moves while it waits; attention's memory counted
-- **The share of the expert cache filled, in janas-chat's footer, was drawn
- only at the start and after each reply**: it showed whatever it was at
- that moment - 60% at one start, 0% at the next - and kept it. The footer
- is now drawn again while the editor waits for a key, when the share
- changes, and the share goes when the filling is over; on
- Qwen3-Next-80B-A3B it climbed from 0% to 98% in nine seconds and went,
- with the cursor never leaving the line being written. A filling
- overtaken by the conversation's own requests (they filled the cache
- first) now ends: `janas_llm_preload` then gives a total equal to what it
- loaded, instead of a share stuck below 100%.
-- **The partial results of attention grow with the context** like the
- keys and values, and were left out when the memory was shared out:
- 1.08 GB at 262,144 tokens of Qwen3-Next-80B-A3B, taken from the margin
- left to other programs. They are counted now (`janas_attn_part_bytes`).
+- **The share of the expert cache filled, in janas-chat's footer, was drawn only at the start and after each reply**: it showed whatever it was at that moment - 60% at one start, 0% at the next - and kept it. The footer is now drawn again while the editor waits for a key, when the share changes, and the share goes when the filling is over; on Qwen3-Next-80B-A3B it climbed from 0% to 98% in nine seconds and went, with the cursor never leaving the line being written. A filling overtaken by the conversation's own requests (they filled the cache first) now ends: `janas_llm_preload` then gives a total equal to what it loaded, instead of a share stuck below 100%.
+- **The partial results of attention grow with the context** like the keys and values, and were left out when the memory was shared out: 1.08 GB at 262,144 tokens of Qwen3-Next-80B-A3B, taken from the margin left to other programs. They are counted now (`janas_attn_part_bytes`).
## [2026-09-23] - Conversations kept computed, and a store that outlives the server
-- **Conversations kept computed.** The model holds one sequence, so a server
- whose clients take turns - or one client that asks on the side for titles,
- tags and suggestions, as Open WebUI does four times a turn - had each
- conversation read again from the start when it came back. Now the last
- few are copied out of the model and back in: `janas_llm_chat_keep` in the
- library, `--keep N` (8) and `--keep-memory GIB` in `janas-server`. The
- copy is of the keys and values of every attention layer (the prediction
- block's included) and of the recurrent state of Qwen3-Next and Qwen3.5/3.6.
- On Qwen3-4B, two conversations taking turns reuse 133 of 160 and 119 of
- 143 tokens at their second turn, against 3; on Qwen3.6-35B-A3B, 133 and
- 119 against 0; the replies are the same text either way.
-- **A second reply to the same prompt** on models with a recurrent state
- (`n` above 1, a reply asked again) read the whole prompt again, since that
- state cannot go back. The prompt is now kept before the reply: 143 of 143
- tokens found computed on Qwen3.6-35B-A3B. The system message is kept on
- its own too, so that a new conversation with the same one starts from it.
-- **On disk, below the memory**: `janas_llm_chat_keep_disk`, `--keep-disk
- GIB` (8, never more than a quarter of the free space), in
- `~/.cache/janas`. A copy of at least 1024 tokens is written when it leaves
- the memory and when the server stops, never at every turn; a long system
- message with its tools is then read once, also across restarts. A new
- chat found 2012 of 2013 tokens computed on Qwen3-4B (a 153 MiB file) and
- 2103 of 2103 on Qwen3.6-35B-A3B.
-- **The store outlives the server.** Stored completions, responses and
- conversations are written one file each to `~/.local/share/janas/server`
- (`--store DIR`; `--no-store` keeps them in memory only), readable by
- their owner alone, one server at a time per directory. A response left
- running in the background by a killed server is found as failed.
-- **Fixed: the memory a long context takes was counted four times** on
- Qwen3-Next and Qwen3.5/3.6, whose files give one count of key-value
- heads for all layers: every layer was counted, not only the attention
- ones. Opened at 262,144 tokens, Qwen3-Next-80B-A3B set 13.1 GB aside for
- 3.3 GB of keys and values, left its expert cache 6.7 GiB, and fell back
- to four bits and eight experts; now 13.5 GiB and all ten experts. Reading
- 15,904 tokens went from 22.1 to 30.4 tokens/s and the reply from 14.2 to
- 16.9, with the three facts hidden in the text found either way.
+- **Conversations kept computed.** The model holds one sequence, so a server whose clients take turns - or one client that asks on the side for titles, tags and suggestions, as Open WebUI does four times a turn - had each conversation read again from the start when it came back. Now the last few are copied out of the model and back in: `janas_llm_chat_keep` in the library, `--keep N` (8) and `--keep-memory GIB` in `janas-server`. The copy is of the keys and values of every attention layer (the prediction block's included) and of the recurrent state of Qwen3-Next and Qwen3.5/3.6. On Qwen3-4B, two conversations taking turns reuse 133 of 160 and 119 of 143 tokens at their second turn, against 3; on Qwen3.6-35B-A3B, 133 and 119 against 0; the replies are the same text either way.
+- **A second reply to the same prompt** on models with a recurrent state (`n` above 1, a reply asked again) read the whole prompt again, since that state cannot go back. The prompt is now kept before the reply: 143 of 143 tokens found computed on Qwen3.6-35B-A3B. The system message is kept on its own too, so that a new conversation with the same one starts from it.
+- **On disk, below the memory**: `janas_llm_chat_keep_disk`, `--keep-disk GIB` (8, never more than a quarter of the free space), in `~/.cache/janas`. A copy of at least 1024 tokens is written when it leaves the memory and when the server stops, never at every turn; a long system message with its tools is then read once, also across restarts. A new chat found 2012 of 2013 tokens computed on Qwen3-4B (a 153 MiB file) and 2103 of 2103 on Qwen3.6-35B-A3B.
+- **The store outlives the server.** Stored completions, responses and conversations are written one file each to `~/.local/share/janas/server` (`--store DIR`; `--no-store` keeps them in memory only), readable by their owner alone, one server at a time per directory. A response left running in the background by a killed server is found as failed.
+- **Fixed: the memory a long context takes was counted four times** on Qwen3-Next and Qwen3.5/3.6, whose files give one count of key-value heads for all layers: every layer was counted, not only the attention ones. Opened at 262,144 tokens, Qwen3-Next-80B-A3B set 13.1 GB aside for 3.3 GB of keys and values, left its expert cache 6.7 GiB, and fell back to four bits and eight experts; now 13.5 GiB and all ten experts. Reading 15,904 tokens went from 22.1 to 30.4 tokens/s and the reply from 14.2 to 16.9, with the three facts hidden in the text found either way.
## [2026-09-23] - It builds with GCC 13 again
-- **Ubuntu 24.04's compiler stopped the build** (issue #4): GCC 13 drops a
- `#pragma GCC unroll` on a loop whose condition holds a `?:` and warns,
- and `-Werror` made the warning an error. The bound of the two loops is now
- a constant of its own; with GCC 14 the machine code is the same, byte for
- byte. Checked with GCC 13.3.0 from Debian's packages, also with the options
- Ubuntu's GCC turns on by default.
+- **Ubuntu 24.04's compiler stopped the build** (issue #4): GCC 13 drops a `#pragma GCC unroll` on a loop whose condition holds a `?:` and warns, and `-Werror` made the warning an error. The bound of the two loops is now a constant of its own; with GCC 14 the machine code is the same, byte for byte. Checked with GCC 13.3.0 from Debian's packages, also with the options Ubuntu's GCC turns on by default.
## [2026-09-23] - The first ring of OpenAI's API, whole
-Every operation of the API that a local text model can serve now answers:
-27 of the specification's 345, against 4.
-
-- **Tools** in chat and in responses: the tools written into the system
- message as the model's template writes them, and every call held to a
- grammar of the functions and their parameters from the moment the model
- opens it, so its arguments are always valid JSON for the schema;
- `tool_choice` none, auto, required or a function, parallel calls, the
- calls of earlier turns and the tools' answers in the history. Tried on
- Qwen3-4B: two calls at once, their answers sent back, the reply using
- them, the second turn reusing 304 of its 351 tokens; the XML way of
- Qwen3.5 and 3.6 on Qwen3.6-35B-A3B the same. Qwen3-Coder's description of
- the tools is written from its template and not yet run.
-- **JSON output** held to a grammar token by token: a JSON object, or JSON
- valid against a JSON Schema (types, properties in order, required ones,
- items and bounds, enum, const, anyOf, $ref with recursion).
-- **Log-probabilities** with up to 20 alternatives; `n`, `best_of`,
- presence and frequency penalties, `logit_bias`; several prompts, token
- ids, `echo` and `suffix` in completions.
-- **Stored chat completions**: kept on request, listed with metadata
- filters and pages, read, changed, deleted, their messages listed.
-- **The Responses API** with its conversations: items in and out,
- `previous_response_id`, streamed events, responses in the background and
- their cancelling, input items, token counts, compaction into a summary;
- the eight operations of `/conversations`.
-- **Embeddings** from a second model (`--embedding-model`, e.g.
- Qwen3-Embedding-0.6B): against llama.cpp on the same file, a cosine of
- 0.977 to 0.996 between the vectors of the same text.
-- **Moderations** asked of the chat model, with the scores taken from its
- log-probabilities: a general model with instructions, not a trained
- classifier.
-- **In the library**, for every program: a sampler of its own with a filter
- of the tokens that may come next, grammars with the model's special tokens
- as symbols, JSON Schema as a grammar, a small JSON reader, conversations
- built message by message with their tool calls, token counts, fill in the
- middle, embeddings. The text of a reply is unchanged byte for byte where
- none of it is asked for.
-- **While a request waits**, its stream says where it stands in the line,
- and the test page shows it.
+Every operation of the API that a local text model can serve now answers: 27 of the specification's 345, against 4.
+
+- **Tools** in chat and in responses: the tools written into the system message as the model's template writes them, and every call held to a grammar of the functions and their parameters from the moment the model opens it, so its arguments are always valid JSON for the schema; `tool_choice` none, auto, required or a function, parallel calls, the calls of earlier turns and the tools' answers in the history. Tried on Qwen3-4B: two calls at once, their answers sent back, the reply using them, the second turn reusing 304 of its 351 tokens; the XML way of Qwen3.5 and 3.6 on Qwen3.6-35B-A3B the same. Qwen3-Coder's description of the tools is written from its template and not yet run.
+- **JSON output** held to a grammar token by token: a JSON object, or JSON valid against a JSON Schema (types, properties in order, required ones, items and bounds, enum, const, anyOf, $ref with recursion).
+- **Log-probabilities** with up to 20 alternatives; `n`, `best_of`, presence and frequency penalties, `logit_bias`; several prompts, token ids, `echo` and `suffix` in completions.
+- **Stored chat completions**: kept on request, listed with metadata filters and pages, read, changed, deleted, their messages listed.
+- **The Responses API** with its conversations: items in and out, `previous_response_id`, streamed events, responses in the background and their cancelling, input items, token counts, compaction into a summary; the eight operations of `/conversations`.
+- **Embeddings** from a second model (`--embedding-model`, e.g. Qwen3-Embedding-0.6B): against llama.cpp on the same file, a cosine of 0.977 to 0.996 between the vectors of the same text.
+- **Moderations** asked of the chat model, with the scores taken from its log-probabilities: a general model with instructions, not a trained classifier.
+- **In the library**, for every program: a sampler of its own with a filter of the tokens that may come next, grammars with the model's special tokens as symbols, JSON Schema as a grammar, a small JSON reader, conversations built message by message with their tool calls, token counts, fill in the middle, embeddings. The text of a reply is unchanged byte for byte where none of it is asked for.
+- **While a request waits**, its stream says where it stands in the line, and the test page shows it.
## [2026-09-23] - janas-server: the model behind OpenAI's API
-Asked for in issue #3: an HTTP API that clients written for OpenAI's can use,
-so that a model running on this machine can sit behind a chat front end, an
-editor or a script without anything written for Janas.
-
-- **`janas-server`** answers `GET /v1/models`, `POST /v1/chat/completions`
- and `POST /v1/completions`, whole or streamed as server-sent events, with
- the reasoning apart in `reasoning_content` and the counts in `usage`. It
- listens on this machine only unless told otherwise, asks for a key when
- given one, and warns when it is opened to the network without one. Requests
- run one at a time, in the order they came; a client that goes away stops
- its reply.
-- **The whole of OpenAI's API is in its route table**, generated from the
- specification (2.3.0, 345 operations) by `tools/openapi_routes.py`: what is
- not written yet answers 501 and says why, and what a request asks that is
- not written yet (tools, JSON output, log probabilities) is refused with a
- 400 rather than ignored.
-- **A conversation is not read twice.** OpenAI's API sends the whole
- conversation with every request; the server reads again only what is new.
- The replies it wrote are remembered with their reasoning, so the answer a
- client sends back without it still matches. Checked: three turns through
- the server and through `janas-chat` give the same words, and the second
- turn reads 18 tokens of 260 or 19 of 200.
-- **`--test` serves Janas-Chat Web**, a chat page inside the program: the
- reasoning in grey, the context and the speed under each reply, and the
- marks a model writes read as `janas-chat` reads them, plus quotes, tables,
- struck text, six levels of heading and links that ask before they open.
- *Markdown sample* shows every mark it knows without asking the model.
-- **Two libraries of others, in `janas-server` only**: GNU libmicrohttpd
- 1.0.10 (signature checked) and yyjson 0.13.0, unchanged in
- `src/third_party/`. `build.sh` compiles them apart and never into
- `libjanas_llm`.
-- **In the library**: `janas_llm_chat_load` takes a conversation whole,
- `janas_llm_chat_prompt` continues raw text, `janas_llm_default_system` is
- the system message both programs now share, and the reply statistics say
- why a reply ended and how much of its prompt was already computed. The
- FreeBASIC binding follows, checked with `fbc`.
-- **In `janas-chat`**: the title is *Janas-Chat*; a mark at the very end of a
- reply (`**bold**`, `` `code` ``) was printed instead of read, and now is
- read; an underscore alone at the edge of a word is italic, so `**_this_**`
- works while `snake_case` and `__init__` stay as they are; and the system
- message asks the model not to introduce itself unless asked, which on
- Qwen3-4B turned the whole presentation it gave to "Ciao!" into "Ciao! 😊".
-- **Checked**: the unit tests in release, asan and tsan, a test that sends
- twenty thousand mangled requests to the parser, the engine's logits
- unchanged byte for byte, and the server under asan and tsan. The only races
- tsan reports are two inside libmicrohttpd, formal and harmless in the mode
- it runs in.
+Asked for in issue #3: an HTTP API that clients written for OpenAI's can use, so that a model running on this machine can sit behind a chat front end, an editor or a script without anything written for Janas.
+
+- **`janas-server`** answers `GET /v1/models`, `POST /v1/chat/completions` and `POST /v1/completions`, whole or streamed as server-sent events, with the reasoning apart in `reasoning_content` and the counts in `usage`. It listens on this machine only unless told otherwise, asks for a key when given one, and warns when it is opened to the network without one. Requests run one at a time, in the order they came; a client that goes away stops its reply.
+- **The whole of OpenAI's API is in its route table**, generated from the specification (2.3.0, 345 operations) by `tools/openapi_routes.py`: what is not written yet answers 501 and says why, and what a request asks that is not written yet (tools, JSON output, log probabilities) is refused with a 400 rather than ignored.
+- **A conversation is not read twice.** OpenAI's API sends the whole conversation with every request; the server reads again only what is new. The replies it wrote are remembered with their reasoning, so the answer a client sends back without it still matches. Checked: three turns through the server and through `janas-chat` give the same words, and the second turn reads 18 tokens of 260 or 19 of 200.
+- **`--test` serves Janas-Chat Web**, a chat page inside the program: the reasoning in grey, the context and the speed under each reply, and the marks a model writes read as `janas-chat` reads them, plus quotes, tables, struck text, six levels of heading and links that ask before they open. *Markdown sample* shows every mark it knows without asking the model.
+- **Two libraries of others, in `janas-server` only**: GNU libmicrohttpd 1.0.10 (signature checked) and yyjson 0.13.0, unchanged in `src/third_party/`. `build.sh` compiles them apart and never into `libjanas_llm`.
+- **In the library**: `janas_llm_chat_load` takes a conversation whole, `janas_llm_chat_prompt` continues raw text, `janas_llm_default_system` is the system message both programs now share, and the reply statistics say why a reply ended and how much of its prompt was already computed. The FreeBASIC binding follows, checked with `fbc`.
+- **In `janas-chat`**: the title is *Janas-Chat*; a mark at the very end of a reply (`**bold**`, `` `code` ``) was printed instead of read, and now is read; an underscore alone at the edge of a word is italic, so `**_this_**` works while `snake_case` and `__init__` stay as they are; and the system message asks the model not to introduce itself unless asked, which on Qwen3-4B turned the whole presentation it gave to "Ciao!" into "Ciao! 😊".
+- **Checked**: the unit tests in release, asan and tsan, a test that sends twenty thousand mangled requests to the parser, the engine's logits unchanged byte for byte, and the server under asan and tsan. The only races tsan reports are two inside libmicrohttpd, formal and harmless in the mode it runs in.
## [2026-09-23] - Tests: two failures on every machine but one
-Reported in issue #2 from a Ryzen AI 9 HX 370: `test_expert_cache` could not
-write its file and `test_tuner` found its saved choices missing. Both had the
-same cause, a habit of the development machine leaking into the tests: they
-wrote under `$HOME/tmp`, a directory that exists there and almost nowhere
-else.
-
-- **`test_expert_cache`** writes its file in `$TMPDIR`, else in `/var/tmp` -
- a disk, where O_DIRECT works, which it does not on the tmpfs `/tmp` often is.
- If it cannot, it says so and says what to set.
-- **`test_tuner`** makes a scratch directory of its own with `mkdtemp` and
- removes it when done.
-- **The engine made only the last two levels of its cache directory.** With
- `XDG_CACHE_HOME` pointing somewhere that did not exist yet, the tuner and
- the expert profile were silently not saved. Every missing level is made
- now.
-
-Checked the way it failed: with a `HOME` that has no `tmp` and no `TMPDIR`,
-the old binaries print exactly the two failures of the report and the new ones
-pass.
+Reported in issue #2 from a Ryzen AI 9 HX 370: `test_expert_cache` could not write its file and `test_tuner` found its saved choices missing. Both had the same cause, a habit of the development machine leaking into the tests: they wrote under `$HOME/tmp`, a directory that exists there and almost nowhere else.
+
+- **`test_expert_cache`** writes its file in `$TMPDIR`, else in `/var/tmp` - a disk, where O_DIRECT works, which it does not on the tmpfs `/tmp` often is. If it cannot, it says so and says what to set.
+- **`test_tuner`** makes a scratch directory of its own with `mkdtemp` and removes it when done.
+- **The engine made only the last two levels of its cache directory.** With `XDG_CACHE_HOME` pointing somewhere that did not exist yet, the tuner and the expert profile were silently not saved. Every missing level is made now.
+
+Checked the way it failed: with a `HOME` that has no `tmp` and no `TMPDIR`, the old binaries print exactly the two failures of the report and the new ones pass.
## [2026-09-22] - Janas-LLM: reading a prompt, 8 to 12 per cent faster
-Measured before touching anything: while a block of 64 prompt tokens went
-through the model, nineteen of twenty threads spent **9% of the time** on
-Qwen3-4B and **13%** on Qwen3-30B-A3B waiting for the calling thread, which
-did per-token work alone - the norms and the quantization of the
-activations, the normalization and rotation of each head of q and k with the
-eight-bit copy into the attention cache, the router's choice of experts, and
-the sum of the experts' outputs.
-
-- **All of that now runs on the pool**, token by token or head by head. Each
- token takes the same operations in the same order as before, including the
- order in which it adds up its experts, so nothing changes in the result:
- the logits of Qwen3-4B, Qwen3-30B-A3B and Qwen3-Next-80B-A3B are identical
- byte for byte to the previous version's, over 256 tokens, both in blocks
- and one token at a time.
-- **Prefill, 1024 tokens, cache warm, 20 threads**, old and new alternated:
- Qwen3-4B 82.4 to 88.5 tok/s (+7.6%), Qwen3-30B-A3B 82.7 to 92.6 (+12.1%),
- Qwen3-Next-80B-A3B 58.3 to 64.1 (+9.9%). The time the calling thread works
- alone falls to 0.3% and 0.9%.
-- **Decoding**: the heads of q and k are spread over the pool there too, which
- saves about a third of a millisecond a token: Qwen3-30B-A3B 28.56 to 28.92
- tok/s over three alternated rounds, Qwen3-4B unchanged within the noise.
+Measured before touching anything: while a block of 64 prompt tokens went through the model, nineteen of twenty threads spent **9% of the time** on Qwen3-4B and **13%** on Qwen3-30B-A3B waiting for the calling thread, which did per-token work alone - the norms and the quantization of the activations, the normalization and rotation of each head of q and k with the eight-bit copy into the attention cache, the router's choice of experts, and the sum of the experts' outputs.
+
+- **All of that now runs on the pool**, token by token or head by head. Each token takes the same operations in the same order as before, including the order in which it adds up its experts, so nothing changes in the result: the logits of Qwen3-4B, Qwen3-30B-A3B and Qwen3-Next-80B-A3B are identical byte for byte to the previous version's, over 256 tokens, both in blocks and one token at a time.
+- **Prefill, 1024 tokens, cache warm, 20 threads**, old and new alternated: Qwen3-4B 82.4 to 88.5 tok/s (+7.6%), Qwen3-30B-A3B 82.7 to 92.6 (+12.1%), Qwen3-Next-80B-A3B 58.3 to 64.1 (+9.9%). The time the calling thread works alone falls to 0.3% and 0.9%.
+- **Decoding**: the heads of q and k are spread over the pool there too, which saves about a third of a millisecond a token: Qwen3-30B-A3B 28.56 to 28.92 tok/s over three alternated rounds, Qwen3-4B unchanged within the noise.
## [2026-09-22] - Janas-LLM: three ways the chat laid text out wrong
-All three found by using it, and all three in the same place: what the chat
-knows about where a line may break.
+All three found by using it, and all three in the same place: what the chat knows about where a line may break.
- **A code block inside a list never closed.** A model asked for examples put a Python block inside a numbered list, so it indented the fence that ends it. The markdown machine closed a block only on a backtick in the very first column, so the fence came out as text and everything after it stayed inside the block - where nothing else is a mark, which is why the rest of the reply arrived with its stars and its bullets as written. Spaces no longer end the start of a line inside a block, which is the rule the rest of the machine already used.
- **And the indent of that fence stayed on the screen.** A fence that opens is swallowed whole, its line with it, but the spaces before it had already been printed and stayed behind on a line whose end had gone: the first line of code then came out with its own indent added to the fence's. The spaces a line begins with are now held until it is known whether a fence follows them.
@@ -995,13 +322,7 @@ knows about where a line may break.
## [2026-09-22] - Janas-LLM: the engine was slower with its own speculation on
-Four things, found by pulling one thread: what a draft is worth depends on
-what a second token in a pass costs, and nobody had ever measured that. It is
-**6% on a dense model**, where the weights are read once for both tokens, and
-**28% on a mixture**, where two tokens route to different experts. Against
-that, drafts copied from the conversation survive 11% of the time on ordinary
-prose and 64% on a page of tables, and at the temperature a chat actually uses
-they survive 25%. The engine asked for four of them regardless.
+Four things, found by pulling one thread: what a draft is worth depends on what a second token in a pass costs, and nobody had ever measured that. It is **6% on a dense model**, where the weights are read once for both tokens, and **28% on a mixture**, where two tokens route to different experts. Against that, drafts copied from the conversation survive 11% of the time on ordinary prose and 64% on a page of tables, and at the temperature a chat actually uses they survive 25%. The engine asked for four of them regardless.
- **The drafts copied from the context now have a planner**, the one the prediction block already used, with the chance of a draft in each position measured per position rather than guessed and halved every 192 drafts so it follows the text. `spec_k` goes back to being a ceiling on what may be asked for. Before this, on ordinary prose at the chat's own temperature, speculation made the engine **slower than not speculating at all**: 0.97x on Qwen3-4B and **0.78x on Qwen3-30B-A3B**, with the safety net parking the drafts for 137 passes out of 256. After: 24.3 and 26.3 token/s against 21.4 and 22.0, so 13 and 20 per cent recovered.
- **The sampler sorted thirty-four thousand tokens to use twenty.** Choosing a token collected every logit within thirty times the temperature of the largest - about 34000 of a vocabulary of 151936 - sorted all of them, then kept the twenty `top_k` asks for. It cost 2.4 to 2.9 ms a token on the calling thread while nineteen others waited, five to six per cent of a token of Qwen3-4B, and more with a larger vocabulary (Qwen3.6 has 248320). The twenty largest are now found in one pass with a heap of twenty. Paired against a binary differing only in this: sampling 0.51 s to 0.09 s, decoding 22.3 to 23.7 token/s over three rounds.
@@ -1011,13 +332,7 @@ they survive 25%. The engine asked for four of them regardless.
## [2026-09-22] - Janas-LLM: the 35B's expert phase was never slow
-This project's notes have carried, for two sessions, a figure described as the
-largest thing left open: the routed-expert phase of Qwen3.6-35B running at 40
-GB/s where the same phase of Qwen3-30B runs at 62.4, with the difference
-unexplained after several candidates had been measured and dropped. There was
-nothing to explain. The three models run that phase at **65.3, 65.9 and 63.4
-GB/s** - within four per cent of each other - and the 40 was an accounting
-mistake in three parts.
+This project's notes have carried, for two sessions, a figure described as the largest thing left open: the routed-expert phase of Qwen3.6-35B running at 40 GB/s where the same phase of Qwen3-30B runs at 62.4, with the difference unexplained after several candidates had been measured and dropped. There was nothing to explain. The three models run that phase at **65.3, 65.9 and 63.4 GB/s** - within four per cent of each other - and the 40 was an accounting mistake in three parts.
- **The phase must not be measured whole.** It holds three things with three different rules for counting bytes: the cache, which is a wait on the disk and is 11.9% of the phase on the 35B in decoding and 25.8% on Qwen3-Next-80B; the `gate` and `up` matrices, plain Q4_K read in full every time; and `down`, which is six-bit planes whose byte count depends on a level the engine picks from how much memory there is. The honest number comes from `gate`+`up` alone, where nothing has to be guessed, and `JANAS_EXPTRACE=1` separates them.
- **The shared expert was not being counted.** `qwen35moe` and `qwen3next` have one, used by every token in every layer on top of the `k` routed ones; `qwen3moe`, which is the 30B, does not. Comparing the two while counting only routed experts takes away from the 35B bytes it really reads.
@@ -1035,12 +350,7 @@ mistake in three parts.
## [2026-09-22] - Janas-LLM: the pool was not the bottleneck, and now there is a yardstick
-This project's own notes opened the session with a plan: 21.2% of decoding
-sits in the thread pool's machinery, the engine makes some 340 dispatches a
-token and each one is a barrier, so fusing the three dispatches of the expert
-phase into one would take away two thirds of them. The premise does not
-survive being measured. What came out of measuring it is worth more than the
-plan was.
+This project's own notes opened the session with a plan: 21.2% of decoding sits in the thread pool's machinery, the engine makes some 340 dispatches a token and each one is a barrier, so fusing the three dispatches of the expert phase into one would take away two thirds of them. The premise does not survive being measured. What came out of measuring it is worth more than the plan was.
- **`JANAS_POOLTRACE=1`** is new and stays: one line per call site - the name comes free from a macro around `janas_pool_run` - with its runs, the threads they used, their wall time, and how much of that thread time was spent at the end of a run waiting for the slowest. What the table deliberately does not hold is the time *between* runs, the caller working alone; that is the difference between the wall of the pass and the sum of the column, and it is printed beside it. Off, it costs one variable read per dispatch.
- **The barriers cost 2.4% of the thread time, not 21%.** On Qwen3-30B-A3B decoding 256 tokens, the matrix products - 89% of the time inside the pool - waste 1.4%. Work is claimed on demand there, and it shows.
@@ -1060,11 +370,7 @@ plan was.
## [2026-09-22] - Janas-LLM: the expert phase taken apart
-The entry below put the headroom at two per cent and said the engine was
-finished as an implementation. That was argued from the engine measured
-against itself, which settles nothing: it says there is no waste between a
-kernel and the phase around it, not that the kernel is good. Taken apart
-properly, the figure is about seven per cent, and it is in one place.
+The entry below put the headroom at two per cent and said the engine was finished as an implementation. That was argued from the engine measured against itself, which settles nothing: it says there is no waste between a kernel and the phase around it, not that the kernel is good. Taken apart properly, the figure is about seven per cent, and it is in one place.
- **`JANAS_EXPTRACE=1`** is new and stays: it splits the routed-expert phase into its parts - the two grouped products, the activation and its quantization, the final accumulate, the setup, and the cache - and prints them whenever the per-phase times are read, resetting as it goes. That last detail is the point of it. Prefill and decoding are different machines: decoding is **95.5% matrix product** and its cache costs 2.7%, prefill is 67.4% and 29.5%, because prefill really does read from disk. Averaged together they say something true of neither, which is exactly the mistake this entry was written to correct.
- **There is nothing to take in the glue.** In decoding the whole of the setup, the activation, the accumulate and the cache come to 4.5% of the phase, and the measured wait on the disk is 1% of a token. The 9% quoted earlier was prefill mixed in.
@@ -1075,11 +381,7 @@ properly, the figure is about seven per cent, and it is in one place.
## [2026-09-22] - Janas-LLM: how much is left, and the answer is very little
-The entry below this one closed by saying the engine reaches the metal on one
-phase and asking what the rest could be worth. Measured, the answer is two
-per cent, and the number published earlier today - a third more speed - does
-not survive. What follows is how that was settled, including the two guesses
-that were wrong.
+The entry below this one closed by saying the engine reaches the metal on one phase and asking what the rest could be worth. Measured, the answer is two per cent, and the number published earlier today - a third more speed - does not survive. What follows is how that was settled, including the two guesses that were wrong.
- **There are two yardsticks, not one.** A bare Q4_K product over one contiguous matrix runs at **78.4 GB/s**, 97% of the machine - measured on 1.2 GB, where the level-3 cache is 1% of it and cannot flatter the figure. The same product over expert-sized blocks drawn at random from eight gigabytes runs at **68.4**. Reading scattered costs 12%, and that is the structural price of being a mixture engine, not a fault in the code.
- **How wrong a yardstick can be:** the same command on a 151 MB matrix reported 84.3 GB/s, above the machine's own read bandwidth, because a sixth of that matrix never leaves the cache between passes. 151 MB reads 84.3, 302 reads 80.8, 604 reads 79.2, 1208 reads 78.4. A benchmark that re-reads its data measures the cache unless it is far larger than one.
@@ -1091,10 +393,7 @@ that were wrong.
## [2026-09-22] - Janas-LLM: the speed of the thing, measured again
-All of it re-measured on an idle machine with the expert cache left to size
-itself, which is what the engine does when nobody tells it otherwise. The
-numbers published before were taken with the cache pinned to 20 GiB by hand -
-a setting the product never chooses on its own.
+All of it re-measured on an idle machine with the expert cache left to size itself, which is what the engine does when nobody tells it otherwise. The numbers published before were taken with the cache pinned to 20 GiB by hand - a setting the product never chooses on its own.
| Model | cache | prefill | decode | with MTP |
|---|---|---|---|---|
@@ -1109,9 +408,7 @@ a setting the product never chooses on its own.
## [2026-09-22] - Janas-LLM: the ceiling we measured against was wrong
-We have been quoting a number that does not hold, in this file and in the
-project's own notes, since the first week. It is corrected here in full,
-with how it was found and what it changes.
+We have been quoting a number that does not hold, in this file and in the project's own notes, since the first week. It is corrected here in full, with how it was found and what it changes.
- **The claim.** This machine's memory reads at 83.9 GB/s, the engine's kernels reach 84% of that, and the missing 16% is the cost of unpacking 4-bit weights.
- **What was wrong.** The probe behind that number gave every thread an equal share of the work and waited for all of them. On a CPU with six performance cores, eight efficiency cores and two low-power ones, equal shares on unequal cores measure the slowest core, not the memory. It reported 81.4 GB/s on twelve threads, then a collapse to 69.4 on sixteen - a collapse that does not exist.
diff --git a/INSTALL.md b/INSTALL.md
index a6f689e..6d0faad 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -36,14 +36,10 @@ Everything goes to `bin/x86_64-linux/`: `janas-chat`, `janas-server`, `janas-mcp
Janas reads its own file format (`.jns`), converted from a GGUF file. Supported now: **Qwen3.5 and Qwen3.6** (`qwen35moe`, e.g. Qwen3.6-35B-A3B), **Qwen3-Next** (`qwen3next`, e.g. Qwen3-Next-80B-A3B-Instruct and Qwen3-Coder-Next) and **Qwen3 MoE** (`qwen3moe`, e.g. Qwen3-30B-A3B), in the Q4_K, Q5_K, Q6_K and Q8_0 formats (so the usual **Q4_K_M** files).
-Keep models in `models/` next to the sources: the tools take a path, so
-anywhere works, but that is where the examples here and in the
-[README](README.md#getting-a-model) put them. The README also lists, for each
-model, which Hugging Face repository to take the GGUF from and how large it is.
+Keep models in `models/` next to the sources: the tools take a path, so anywhere works, but that is where the examples here and in the [README](README.md#getting-a-model) put them. The README also lists, for each model, which Hugging Face repository to take the GGUF from and how large it is.
1. Download a Q4_K_M GGUF of the model from Hugging Face, into `models/gguf/`.
-2. Convert it with the converter the build made (with a model split into
- several files, give the first):
+2. Convert it with the converter the build made (with a model split into several files, give the first):
```sh
bin/x86_64-linux/gguf2jns models/gguf/Qwen3-Next-80B-A3B-Instruct-Q4_K_M.gguf \
@@ -61,8 +57,7 @@ model, which Hugging Face repository to take the GGUF from and how large it is.
Qwen3.5 and Qwen3.6 keep their prediction block inside the model file: it is converted and used with no further step.
-Keep the `.jns` files on the NVMe SSD: the experts are read from there while the
-model answers, and a slower disk is felt at every token.
+Keep the `.jns` files on the NVMe SSD: the experts are read from there while the model answers, and a slower disk is felt at every token.
## Chatting
diff --git a/MODELS.md b/MODELS.md
index 7809901..62d9178 100644
--- a/MODELS.md
+++ b/MODELS.md
@@ -1,54 +1,31 @@
# Models, and what may be done with them
-Janas reads models; it does not carry them. This file says what the licence of a
-converted model is, and what this project will and will not redistribute.
+Janas reads models; it does not carry them. This file says what the licence of a converted model is, and what this project will and will not redistribute.
## The engine's licence does not reach the weights
-`tools/gguf2jns` turns a GGUF file into the `.jns` file the engine reads. The
-tool is under the GPL; **the file it writes is not**. A converted model is a
-derivative of the model, not of Janas, and it keeps the licence its author gave
-it. Running GPL software over someone's data does not make that data GPL, and
-nothing in this project claims otherwise.
+`tools/gguf2jns` turns a GGUF file into the `.jns` file the engine reads. The tool is under the GPL; **the file it writes is not**. A converted model is a derivative of the model, not of Janas, and it keeps the licence its author gave it. Running GPL software over someone's data does not make that data GPL, and nothing in this project claims otherwise.
-The other way round matters too: a model's licence may forbid things the GPL
-would allow. The model decides what may be done with the model.
+The other way round matters too: a model's licence may forbid things the GPL would allow. The model decides what may be done with the model.
## What conversion changes, and what it does not
-Converting a GGUF into `.jns` does not retrain, re-quantize or prune anything.
-It rewrites the same numbers in another order:
+Converting a GGUF into `.jns` does not retrain, re-quantize or prune anything. It rewrites the same numbers in another order:
-- one slot per (layer, expert), so the experts a token needs can be read from
- disk without reading anything else;
+- one slot per (layer, expert), so the experts a token needs can be read from disk without reading anything else;
- the experts laid out by co-activation, so the reads fall near each other;
- the model's metadata carried over byte for byte;
-- optionally (`tools/jns_planes`) the experts' down matrix cut into three
- planes of two bits, which is a reordering of the same bits: with all three
- planes the weights are the ones the file came with, to the last bit.
+- optionally (`tools/jns_planes`) the experts' down matrix cut into three planes of two bits, which is a reordering of the same bits: with all three planes the weights are the ones the file came with, to the last bit.
-Anyone redistributing a converted file has to say this, because the licences
-that allow redistribution (Apache 2.0 among them) require that a modified work
-state that it was modified.
+Anyone redistributing a converted file has to say this, because the licences that allow redistribution (Apache 2.0 among them) require that a modified work state that it was modified.
## Converting twice gives the same file
-`tools/gguf2jns` and `tools/jns_planes` are deterministic. The layout of the
-file follows from the sizes in the source, nothing is timed, drawn at random or
-read from the environment, and the weights are copied, never recomputed. The
-same GGUF, converted on another machine, gives the same bytes. The
-converter was a Python script until 25 September 2026; the C one that took
-its place writes the very same bytes, and the fingerprints below hold for
-both.
+`tools/gguf2jns` and `tools/jns_planes` are deterministic. The layout of the file follows from the sizes in the source, nothing is timed, drawn at random or read from the environment, and the weights are copied, never recomputed. The same GGUF, converted on another machine, gives the same bytes. The converter was a Python script until 25 September 2026; the C one that took its place writes the very same bytes, and the fingerprints below hold for both.
-That is what this project publishes about its models: the recipe, and the
-fingerprint of what the recipe produces — not forty gigabytes. Convert your own
-copy, compare, and you know you are running the file the numbers in this
-repository were measured on.
+That is what this project publishes about its models: the recipe, and the fingerprint of what the recipe produces — not forty gigabytes. Convert your own copy, compare, and you know you are running the file the numbers in this repository were measured on.
-Not a claim, a measurement: four of the Qwen models below were converted
-again from their GGUF and compared, byte for byte, with the files this
-project runs, and so were the eight Gemma 4 files. All of them matched.
+Not a claim, a measurement: four of the Qwen models below were converted again from their GGUF and compared, byte for byte, with the files this project runs, and so were the eight Gemma 4 files. All of them matched.
### The recipe
@@ -62,19 +39,11 @@ bin/x86_64-linux/jns_planes models/qwen3-30b-a3b-q4km-flat.jns \
sha256sum models/qwen3-30b-a3b-q4km.jns
```
-On the development laptop (a mobile Core Ultra, the models on NVMe) the two
-steps cost 47 s and 104 s for the 18.6 GB model, 153 s and 194 s for the
-48.4 GB one, with the Python converter: less than the download either way.
-The C one took 51 s for the 18.6 GB model on a busy machine - the disk sets
-the pace, not the language.
+On the development laptop (a mobile Core Ultra, the models on NVMe) the two steps cost 47 s and 104 s for the 18.6 GB model, 153 s and 194 s for the 48.4 GB one, with the Python converter: less than the download either way. The C one took 51 s for the 18.6 GB model on a busy machine - the disk sets the pace, not the language.
### The fingerprints
-Every GGUF below was checked against the SHA-256 that Hugging Face publishes
-for it, so the chain from the model's own repository to the converted file is
-unbroken. The `-flat.jns` line is what `gguf2jns` writes (JNS version 2),
-the line after it what `jns_planes` writes from that (version 3), which is the
-form these models are kept in here.
+Every GGUF below was checked against the SHA-256 that Hugging Face publishes for it, so the chain from the model's own repository to the converted file is unbroken. The `-flat.jns` line is what `gguf2jns` writes (JNS version 2), the line after it what `jns_planes` writes from that (version 3), which is the form these models are kept in here.
**Qwen3-Next-80B-A3B-Instruct**, from [`Qwen/Qwen3-Next-80B-A3B-Instruct-GGUF`](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct-GGUF):
@@ -103,18 +72,14 @@ b46fedd33e0bfb0cae308aa3c158d0a4b2c4a1d2185a1ed6f093cdaf39064772 Qwen_Qwen3.6-3
0276b0697a05075fec8ab076a757205537804ff41dd7e9dadace7c6993763563 qwen3-coder-next-q4km.jns (jns_planes)
```
-**Qwen3-Coder-30B-A3B-Instruct**, for code completion, from
-[`unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF`](https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF):
+**Qwen3-Coder-30B-A3B-Instruct**, for code completion, from [`unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF`](https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF):
```
fadc3e5f8d42bf7e894a785b05082e47daee4df26680389817e2093056f088ad Qwen3-Coder-30B-A3B-Instruct-Q4_K_M.gguf
bee7d25509e911a195cbf05a157e69bb05a62d2241cca2c4fdcfef269dcb2bdd qwen3-coder-30b-a3b-q4km.jns (gguf2jns)
```
-**Qwen3-4B**, from [`Qwen/Qwen3-4B-GGUF`](https://huggingface.co/Qwen/Qwen3-4B-GGUF).
-This one is dense: it has no experts to route, so its feed-forward becomes the
-single slot of each layer, and half its layers keep a `down` matrix in Q4_K,
-which has no planes to cut.
+**Qwen3-4B**, from [`Qwen/Qwen3-4B-GGUF`](https://huggingface.co/Qwen/Qwen3-4B-GGUF). This one is dense: it has no experts to route, so its feed-forward becomes the single slot of each layer, and half its layers keep a `down` matrix in Q4_K, which has no planes to cut.
```
7485fe6f11af29433bc51cab58009521f205840f5b4ae3a32fa7f92e8534fdf5 Qwen3-4B-Q4_K_M.gguf
@@ -122,13 +87,7 @@ e8ed44bdd3c612ce3ec1204a4b9db671115efab4a2ada384c70cf6492d430291 qwen3-4b-q4km-
1cbd8ebfdf14aee05777f5278e655382f040cdedc21d282e93806fc8cf279fc5 qwen3-4b-q4km.jns (jns_planes)
```
-**Qwen3.5-0.8B, Qwen3.5-2B and Qwen3.5-9B**, dense, from
-[`unsloth/Qwen3.5-0.8B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF),
-[`unsloth/Qwen3.5-2B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-2B-GGUF)
-and [`unsloth/Qwen3.5-9B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF),
-GGUF conversions of the Qwen team's checkpoints. Converted in one
-step, as they are kept here: `jns_planes` could cut planes from their Q6_K
-`down` matrices, but a model this size has no need to read fewer bits.
+**Qwen3.5-0.8B, Qwen3.5-2B and Qwen3.5-9B**, dense, from [`unsloth/Qwen3.5-0.8B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF), [`unsloth/Qwen3.5-2B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-2B-GGUF) and [`unsloth/Qwen3.5-9B-GGUF`](https://huggingface.co/unsloth/Qwen3.5-9B-GGUF), GGUF conversions of the Qwen team's checkpoints. Converted in one step, as they are kept here: `jns_planes` could cut planes from their Q6_K `down` matrices, but a model this size has no need to read fewer bits.
```
bd258782e35f7f458f8aced1adc053e6e92e89bc735ba3be89d38a06121dc517 Qwen3.5-0.8B-Q4_K_M.gguf
@@ -147,26 +106,14 @@ e40ec6c58ef2390c7a4ce8c9b7b6b384ed4e55c9980f646d1c98e83e2c018115 qwen3.5-9b-q4k
3fa0185b7eecd43e222d420f68aae28a86b3b90392fd7e4052b5cd337318e895 qwen3-30b-a3b-q4km.jns (jns_planes)
```
-**Qwen3-Embedding-0.6B**, from [`Qwen/Qwen3-Embedding-0.6B-GGUF`](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF),
-for `janas-server --embedding-model`. It is published in Q8_0 and converted
-as it is, in one step: its matrices are not Q6_K, so there are no planes to
-cut. Two conversions give the same bytes.
+**Qwen3-Embedding-0.6B**, from [`Qwen/Qwen3-Embedding-0.6B-GGUF`](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF), for `janas-server --embedding-model`. It is published in Q8_0 and converted as it is, in one step: its matrices are not Q6_K, so there are no planes to cut. Two conversions give the same bytes.
```
06507c7b42688469c4e7298b0a1e16deff06caf291cf0a5b278c308249c3e439 Qwen3-Embedding-0.6B-Q8_0.gguf
1e8eb8cbeba7a1a657354d259c5730bb79f6087160a9ca8da901bd08bdbe943f qwen3-embedding-0.6b-q8.jns (gguf2jns)
```
-**Gemma 4: E2B, E4B, 12B and 26B-A4B, and their assistants**, from
-[`unsloth/gemma-4-E2B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-E2B-it-GGUF),
-[`unsloth/gemma-4-E4B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF),
-[`unsloth/gemma-4-12b-it-GGUF`](https://huggingface.co/unsloth/gemma-4-12b-it-GGUF)
-and [`unsloth/gemma-4-26B-A4B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF).
-Each converted in one step, as it is kept here, and each converted twice on
-27 September 2026: the same bytes. The assistant, Gemma's drafting model
-(the `mtp-` file, given to the chat with `--mtp`), converts with
-`gguf2jns` like the model. The 26B's feed-forwards are widened with zeros
-to a multiple of 256, which is why its file is larger than its GGUF.
+**Gemma 4: E2B, E4B, 12B and 26B-A4B, and their assistants**, from [`unsloth/gemma-4-E2B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-E2B-it-GGUF), [`unsloth/gemma-4-E4B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF), [`unsloth/gemma-4-12b-it-GGUF`](https://huggingface.co/unsloth/gemma-4-12b-it-GGUF) and [`unsloth/gemma-4-26B-A4B-it-GGUF`](https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF). Each converted in one step, as it is kept here, and each converted twice on 27 September 2026: the same bytes. The assistant, Gemma's drafting model (the `mtp-` file, given to the chat with `--mtp`), converts with `gguf2jns` like the model. The 26B's feed-forwards are widened with zeros to a multiple of 256, which is why its file is larger than its GGUF.
```
740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8 gemma-4-E2B-it-Q4_K_M.gguf
@@ -187,10 +134,7 @@ f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f gemma-4-26B-A4
6ba24ee91fe6fe904b29919acbb654a66d9caa0aba67db1df9f921a76e5bcedf gemma-4-26b-it-mtp.jns (gguf2jns)
```
-The multi-token prediction block is not converted from a GGUF — GGUF files
-leave it out — but from the original checkpoint's last shard, quantized to
-Q4_K by `tools/hf2jns_mtp`, which also copies the metadata of the converted
-model handed to it:
+The multi-token prediction block is not converted from a GGUF — GGUF files leave it out — but from the original checkpoint's last shard, quantized to Q4_K by `tools/hf2jns_mtp`, which also copies the metadata of the converted model handed to it:
```sh
bin/x86_64-linux/hf2jns_mtp models/qwen3-next-80b-a3b-q4km.jns \
@@ -198,25 +142,16 @@ bin/x86_64-linux/hf2jns_mtp models/qwen3-next-80b-a3b-q4km.jns \
models/qwen3-next-80b-a3b-mtp-q4k.jns
```
-Two runs of it give the same bytes, and it takes 75 s. **The shard**, from
-[`Qwen/Qwen3-Next-80B-A3B-Instruct`](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct),
-and what comes out:
+Two runs of it give the same bytes, and it takes 75 s. **The shard**, from [`Qwen/Qwen3-Next-80B-A3B-Instruct`](https://huggingface.co/Qwen/Qwen3-Next-80B-A3B-Instruct), and what comes out:
```
1f3ac4d828f7e08dd14eb4dc6f282139ae1fa0d894e43f247da2539d2ef43826 model-00041-of-00041.safetensors
5c9bc4cb6f739193fac5e4daa30c922f73255acf41443ecfc0123ef084584559 qwen3-next-80b-a3b-mtp-q4k.jns (hf2jns_mtp)
```
-Until 25 September 2026 this line read `0dfd70d4…`: the fingerprint of a
-file whose levels `hf2jns_mtp` left at zero (issue #6). The engine now reads
-such a file as it was meant, and `jns_check` says what it is; the tool
-writes the levels, which is the file above.
+Until 25 September 2026 this line read `0dfd70d4…`: the fingerprint of a file whose levels `hf2jns_mtp` left at zero (issue #6). The engine now reads such a file as it was meant, and `jns_check` says what it is; the tool writes the levels, which is the file above.
-**The dense Qwen3.5 models** keep their block in the checkpoint too, spread
-over several shards (three of the four of Qwen3.5-9B, 14 GB). `hf2jns_mtp`
-reads just the block's tensors from Hugging Face, with range requests - 487
-MB for the 9B, under a minute - and deletes them once converted. Name the
-checkpoint's revision, so that the fingerprint below holds:
+**The dense Qwen3.5 models** keep their block in the checkpoint too, spread over several shards (three of the four of Qwen3.5-9B, 14 GB). `hf2jns_mtp` reads just the block's tensors from Hugging Face, with range requests - 487 MB for the 9B, under a minute - and deletes them once converted. Name the checkpoint's revision, so that the fingerprint below holds:
```sh
bin/x86_64-linux/hf2jns_mtp models/qwen3.5-9b-q4km.jns \
@@ -224,30 +159,20 @@ bin/x86_64-linux/hf2jns_mtp models/qwen3.5-9b-q4km.jns \
models/qwen3.5-9b-mtp-q4k.jns
```
-From [`Qwen/Qwen3.5-9B`](https://huggingface.co/Qwen/Qwen3.5-9B) at
-`c2022362`, and [`Qwen/Qwen3.5-2B`](https://huggingface.co/Qwen/Qwen3.5-2B) at
-`15852e8c` (`hf:Qwen/Qwen3.5-2B@15852e8c16360a2fea060d615a32b45270f8a8fc`),
-each with the converted model above:
+From [`Qwen/Qwen3.5-9B`](https://huggingface.co/Qwen/Qwen3.5-9B) at `c2022362`, and [`Qwen/Qwen3.5-2B`](https://huggingface.co/Qwen/Qwen3.5-2B) at `15852e8c` (`hf:Qwen/Qwen3.5-2B@15852e8c16360a2fea060d615a32b45270f8a8fc`), each with the converted model above:
```
67f31f57dbc78ca8c02ef5e3aa137c5df3836a3decda20b6ea057d004089c361 qwen3.5-9b-mtp-q4k.jns (hf2jns_mtp)
19c2d7eba1800acb10a06d7b38709ec92776e852cb2f25032ddd8977d17f2b05 qwen3.5-2b-mtp-q4k.jns (hf2jns_mtp)
```
-The same tensors from shards on disk give the same bytes. A private or gated
-repository wants `HF_TOKEN` in the environment; it is sent to huggingface.co
-only.
+The same tensors from shards on disk give the same bytes. A private or gated repository wants `HF_TOKEN` in the environment; it is sent to huggingface.co only.
### If a fingerprint does not match
-- **Check the GGUF first.** Another quantization of the same model is another
- file, and so is the same quantization from somebody else's repository. A
- `.jns` fingerprint says nothing on its own: it belongs to the GGUF above it.
-- **The tools move.** A change to the layout changes every fingerprint here,
- and the ChangeLog says when that happened. These are the tools as this
- repository publishes them.
-- **The file checks itself.** A `.jns` carries a checksum for every expert and
- for its metadata, so a damaged copy is caught without any of this:
+- **Check the GGUF first.** Another quantization of the same model is another file, and so is the same quantization from somebody else's repository. A `.jns` fingerprint says nothing on its own: it belongs to the GGUF above it.
+- **The tools move.** A change to the layout changes every fingerprint here, and the ChangeLog says when that happened. These are the tools as this repository publishes them.
+- **The file checks itself.** A `.jns` carries a checksum for every expert and for its metadata, so a damaged copy is caught without any of this:
```sh
bin/x86_64-linux/jns_check model.jns --verify
@@ -255,57 +180,26 @@ only.
## What this project redistributes
-**The converter, always. The weights, only when their licence plainly allows
-it.** In order:
+**The converter, always. The weights, only when their licence plainly allows it.** In order:
-1. **Models under Apache 2.0, MIT or a similar licence.** Every model Janas
- supports today is under **Apache 2.0** and none is gated: Qwen3-Next
- (including Qwen3-Coder-Next), Qwen3.5 and Qwen3.6, and Qwen3 MoE — checked
- on their pages, not in their files. Converted files may be
- published, and when they are, they carry:
+1. **Models under Apache 2.0, MIT or a similar licence.** Every model Janas supports today is under **Apache 2.0** and none is gated: Qwen3-Next (including Qwen3-Coder-Next), Qwen3.5 and Qwen3.6, and Qwen3 MoE — checked on their pages, not in their files. Converted files may be published, and when they are, they carry:
- a link to the original model and to its licence;
- the original `LICENSE` and, where there is one, the `NOTICE`;
- - a statement of what was changed (the list above) and which version of the
- tools did it;
+ - a statement of what was changed (the list above) and which version of the tools did it;
- the SHA-256 of every file;
- - no name, logo or wording that suggests the model's authors endorse this.
- Apache 2.0 grants no trademark rights: "converted from Qwen3-Next-80B-A3B,
- by Alibaba Cloud" is a fact; naming a repository after the model is not.
-
-2. **Models whose file says nothing about a licence.** Nothing is published
- until the original page has been read. This is not a formality: of the four
- models converted here, two had lost the `general.license` field on the way,
- through somebody's re-quantization, although the models themselves are
- Apache 2.0. **The metadata is not the licence**; the model's page is.
-
- A GGUF that went through a third party has two hands on it: the model's
- authors and whoever quantized it. Apache 2.0 lets the second redistribute
- and lets this project redistribute in turn, but the attribution is owed to
- both. Where the chain is long — a checkpoint quantized to four bits,
- brought back to half precision and quantized again — the file is better
- left alone, not for the licence but because nobody can honestly say what is
- in it.
-
-3. **Models under a community or research licence** (Llama, Gemma up to
- Gemma 3, and the like - Gemma 4 is Apache 2.0, on Google's page):
- **nothing is published, ever**. Their terms travel with the weights, and
- some of them forbid redistribution outright or attach conditions this project
- will not carry for its users. Convert them yourself, from the copy you
- downloaded under the terms you accepted.
-
-Today there is nothing to fetch, and that is on purpose: the recipe above
-rebuilds every one of these files exactly, so publishing them would only move
-bytes that anyone can make. Should that change, converted models would live in
-the project's model repositories on Hugging Face, not in this one: a file of
-forty gigabytes has no business in a source tree, and GitHub will not take it —
-100 MB a file, 2 GB with Git LFS, 2 GB an asset in a release.
+ - no name, logo or wording that suggests the model's authors endorse this. Apache 2.0 grants no trademark rights: "converted from Qwen3-Next-80B-A3B, by Alibaba Cloud" is a fact; naming a repository after the model is not.
+
+2. **Models whose file says nothing about a licence.** Nothing is published until the original page has been read. This is not a formality: of the four models converted here, two had lost the `general.license` field on the way, through somebody's re-quantization, although the models themselves are Apache 2.0. **The metadata is not the licence**; the model's page is.
+
+ A GGUF that went through a third party has two hands on it: the model's authors and whoever quantized it. Apache 2.0 lets the second redistribute and lets this project redistribute in turn, but the attribution is owed to both. Where the chain is long — a checkpoint quantized to four bits, brought back to half precision and quantized again — the file is better left alone, not for the licence but because nobody can honestly say what is in it.
+
+3. **Models under a community or research licence** (Llama, Gemma up to Gemma 3, and the like - Gemma 4 is Apache 2.0, on Google's page): **nothing is published, ever**. Their terms travel with the weights, and some of them forbid redistribution outright or attach conditions this project will not carry for its users. Convert them yourself, from the copy you downloaded under the terms you accepted.
+
+Today there is nothing to fetch, and that is on purpose: the recipe above rebuilds every one of these files exactly, so publishing them would only move bytes that anyone can make. Should that change, converted models would live in the project's model repositories on Hugging Face, not in this one: a file of forty gigabytes has no business in a source tree, and GitHub will not take it — 100 MB a file, 2 GB with Git LFS, 2 GB an asset in a release.
## If you convert a model yourself
-You are the one redistributing it, if you pass it on. Check the licence of the
-model **and** of the GGUF you converted (they may be different hands), keep the
-notices, say what you changed. The metadata Janas carries over can tell you
-where to start looking:
+You are the one redistributing it, if you pass it on. Check the licence of the model **and** of the GGUF you converted (they may be different hands), keep the notices, say what you changed. The metadata Janas carries over can tell you where to start looking:
```sh
bin/x86_64-linux/jns_check model.jns
diff --git a/README.md b/README.md
index 32e5118..3ec987a 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,6 @@
# Janas
-[![Status: experimental](https://img.shields.io/badge/status-experimental-orange.svg)]()
-[![Platform: Linux x86-64](https://img.shields.io/badge/platform-Linux%20x86--64-lightgrey.svg)]()
-[![LinkedIn](https://img.shields.io/badge/LinkedIn-Maurizio%20Cammalleri-0077B5?logo=linkedin)](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/)
-[![Substack](https://img.shields.io/badge/Substack-Maurizio%20Cammalleri-FF6719?logo=substack)](https://cammalleri.substack.com/)
+[![Status: experimental](https://img.shields.io/badge/status-experimental-orange.svg)]() [![Platform: Linux x86-64](https://img.shields.io/badge/platform-Linux%20x86--64-lightgrey.svg)]() [![LinkedIn](https://img.shields.io/badge/LinkedIn-Maurizio%20Cammalleri-0077B5?logo=linkedin)](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/) [![Substack](https://img.shields.io/badge/Substack-Maurizio%20Cammalleri-FF6719?logo=substack)](https://cammalleri.substack.com/)
```
▄███████████▄
@@ -16,12 +13,7 @@
▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀
```
-Janas is a family of tools for artificial intelligence, written in C with no
-dependencies beyond the C library. Its first component, **Janas-LLM**, runs
-large mixture-of-experts language models on ordinary computers, with or without
-a GPU: the weights stay on disk, the experts each token needs are streamed from
-an NVMe SSD, and the ones that keep coming back stay in memory. An 80-billion
-parameter model runs, and answers, on a laptop with 32 GB of RAM.
+Janas is a family of tools for artificial intelligence, written in C with no dependencies beyond the C library. Its first component, **Janas-LLM**, runs large mixture-of-experts language models on ordinary computers, with or without a GPU: the weights stay on disk, the experts each token needs are streamed from an NVMe SSD, and the ones that keep coming back stay in memory. An 80-billion parameter model runs, and answers, on a laptop with 32 GB of RAM.
Designed and written by **Maurizio "camauri" Cammalleri**.
@@ -38,9 +30,7 @@ Designed and written by **Maurizio "camauri" Cammalleri**.
| **Data** | It writes only in `~/.cache/janas` (what it learns about your machine) and where you tell it to put a converted model. It does not touch the model files it reads. |
| **Hardware** | Developed and run on **one** machine (below). On anything else it is untested: it may be slower, it may refuse the model, it may misbehave. |
-If something goes wrong, `Ctrl-C` stops a reply and `Ctrl-D` leaves the chat;
-`--cache <GiB>` puts a hard limit on the memory it takes, and `JANAS_GPU=0`
-keeps it off the GPU entirely.
+If something goes wrong, `Ctrl-C` stops a reply and `Ctrl-D` leaves the chat; `--cache <GiB>` puts a hard limit on the memory it takes, and `JANAS_GPU=0` keeps it off the GPU entirely.
## The machine it grew on
@@ -51,101 +41,24 @@ Everything in this repository was written and measured on:
- **32 GB** of DDR5 RAM
- **1 TB NVMe SSD** (about 5.7 GB/s reading)
-Everything the engine does is chosen from what it measures, so another machine
-will make other choices — that part is meant to travel. What has never been
-tried is the rest: other CPUs (especially without AVX-VNNI, or AMD), discrete
-GPUs, slower disks, more or less memory. **If you run it somewhere else, the
-report from `janas-bench` is the single most useful thing you can send back**
-(see [Helping it run on more hardware](#helping-it-run-on-more-hardware)).
+Everything the engine does is chosen from what it measures, so another machine will make other choices — that part is meant to travel. What has never been tried is the rest: other CPUs (especially without AVX-VNNI, or AMD), discrete GPUs, slower disks, more or less memory. **If you run it somewhere else, the report from `janas-bench` is the single most useful thing you can send back** (see [Helping it run on more hardware](#helping-it-run-on-more-hardware)).
## What works now
-- **Models:** Qwen3.5 and Qwen3.6 (`qwen35moe`, e.g. Qwen3.6-35B-A3B), Qwen3-Next
- (`qwen3next`, e.g. Qwen3-Next-80B-A3B-Instruct and Qwen3-Coder-Next), Qwen3
- MoE (`qwen3moe`, e.g. Qwen3-30B-A3B), the **dense** Qwen3.5 models
- (`qwen35`) and the **dense** Qwen3 models (`qwen3`), from the usual
- **Q4_K_M** GGUF files, or **Q3_K**, **IQ3_S**, **IQ4_NL**, **IQ4_XS**,
- **Q4_0**, **Q4_1** and **Q5_1** ones, and unsloth's "UD" mixes of them
- (checked on Qwen3.5-0.8B and 9B against llama.cpp). A dense
- feed-forward is a mixture with one expert and no router, so the same path
- serves both and there is no second engine to keep in step. Of the dense
- ones **Qwen3.5-0.8B, 2B and 9B, Qwen3-4B and Qwen3-0.6B are the ones that
- have been run here**; the Qwen3.5 three were checked against llama.cpp on
- the same files.
- **Nearly everything here was measured on Qwen3-Next-80B-A3B-Instruct**: it is
- the one the engine was shaped around, and the one whose numbers are quoted
- below. The others have been converted, checked against a reference and used,
- but far less.
-- **Gemma 4** (`gemma4`): **Gemma-4-12B-it** (dense) and
- **Gemma-4-26B-A4B-it** (a mixture of 128 experts beside a dense
- feed-forward) convert and chat, with their reasoning on or off
- (`--think`); the prompts are, token for token, the ones the model's own
- chat template writes, and a full context slides as it does for the other
- models. Its sliding-window layers keep only the last positions they can
- see, so a long context costs mostly the full layers: for the 12B about 16
- KB a token and half a gigabyte fixed, instead of 175 KB a token. Keys and
- values are kept at sixteen bits (Gemma is far more sensitive to them than
- Qwen). Tools work in Gemma's own notation - declarations, calls and the
- tools' answers inside the model's turn, token for token as its template
- writes them. The small **Gemma-4-E2B-it** and **E4B-it** run too, with
- chat and tools: their per-layer embeddings - a table as large as half of
- E2B's file - are read from the file a row at a time and never loaded, so
- E2B ran here in 1.5 GB of memory (a 3.1 GB file) and E4B in 3.1 GB (5.0
- GB). Each of the four has an **assistant**, a small drafting model of
- its own that reads the main model's keys and values, taken as its
- `--mtp` file: on an Italian chat reply of 110 tokens, greedy, it took
- E2B from 34.7 tokens/s to 51.0, E4B from 18.3 to 26.3, the 12B from 8.5
- to 12.9 and the 26B from 16.9 to 24.5 on the development laptop, the
- same tokens with and without it. Against llama.cpp on 200 tokens of prose the most likely token
- agrees at 160 positions on the 12B (mean logit difference 0.84) and at
- 160 on the 26B (0.97); on another 200-token text at 191 on E2B (0.45) and
- 195 on E4B (0.28). Against an exact float64 computation over the same
- weights (a NumPy forward pass written to check them), on the prose: the 12B
- agrees at 167 positions (llama.cpp 173), the 26B at 156 (llama.cpp
- 160), with mean errors of 0.75 and 0.87 (llama.cpp 0.67 and 0.90). The larger two turn small numerical differences into
- large ones, and llama.cpp is not a steady reference for them: against
- itself with an eight-bit cache it agrees at 153 positions on the 12B, and
- with a 32-bit cache and no flash attention, at 112. The
- reference has to be computed in batches of at most 32 tokens: with larger
- ones llama.cpp's logits for the early positions change (it looks ahead),
- for a reason not yet found.
+- **Models:** Qwen3.5 and Qwen3.6 (`qwen35moe`, e.g. Qwen3.6-35B-A3B), Qwen3-Next (`qwen3next`, e.g. Qwen3-Next-80B-A3B-Instruct and Qwen3-Coder-Next), Qwen3 MoE (`qwen3moe`, e.g. Qwen3-30B-A3B), the **dense** Qwen3.5 models (`qwen35`) and the **dense** Qwen3 models (`qwen3`), from the usual **Q4_K_M** GGUF files, or **Q3_K**, **IQ3_S**, **IQ4_NL**, **IQ4_XS**, **Q4_0**, **Q4_1** and **Q5_1** ones, and unsloth's "UD" mixes of them (checked on Qwen3.5-0.8B and 9B against llama.cpp). A dense feed-forward is a mixture with one expert and no router, so the same path serves both and there is no second engine to keep in step. Of the dense ones **Qwen3.5-0.8B, 2B and 9B, Qwen3-4B and Qwen3-0.6B are the ones that have been run here**; the Qwen3.5 three were checked against llama.cpp on the same files. **Nearly everything here was measured on Qwen3-Next-80B-A3B-Instruct**: it is the one the engine was shaped around, and the one whose numbers are quoted below. The others have been converted, checked against a reference and used, but far less.
+- **Gemma 4** (`gemma4`): **Gemma-4-12B-it** (dense) and **Gemma-4-26B-A4B-it** (a mixture of 128 experts beside a dense feed-forward) convert and chat, with their reasoning on or off (`--think`); the prompts are, token for token, the ones the model's own chat template writes, and a full context slides as it does for the other models. Its sliding-window layers keep only the last positions they can see, so a long context costs mostly the full layers: for the 12B about 16 KB a token and half a gigabyte fixed, instead of 175 KB a token. Keys and values are kept at sixteen bits (Gemma is far more sensitive to them than Qwen). Tools work in Gemma's own notation - declarations, calls and the tools' answers inside the model's turn, token for token as its template writes them. The small **Gemma-4-E2B-it** and **E4B-it** run too, with chat and tools: their per-layer embeddings - a table as large as half of E2B's file - are read from the file a row at a time and never loaded, so E2B ran here in 1.5 GB of memory (a 3.1 GB file) and E4B in 3.1 GB (5.0 GB). Each of the four has an **assistant**, a small drafting model of its own that reads the main model's keys and values, taken as its `--mtp` file: on an Italian chat reply of 110 tokens, greedy, it took E2B from 34.7 tokens/s to 51.0, E4B from 18.3 to 26.3, the 12B from 8.5 to 12.9 and the 26B from 16.9 to 24.5 on the development laptop, the same tokens with and without it. Against llama.cpp on 200 tokens of prose the most likely token agrees at 160 positions on the 12B (mean logit difference 0.84) and at 160 on the 26B (0.97); on another 200-token text at 191 on E2B (0.45) and 195 on E4B (0.28). Against an exact float64 computation over the same weights (a NumPy forward pass written to check them), on the prose: the 12B agrees at 167 positions (llama.cpp 173), the 26B at 156 (llama.cpp 160), with mean errors of 0.75 and 0.87 (llama.cpp 0.67 and 0.90). The larger two turn small numerical differences into large ones, and llama.cpp is not a steady reference for them: against itself with an eight-bit cache it agrees at 153 positions on the 12B, and with a 32-bit cache and no flash attention, at 112. The reference has to be computed in batches of at most 32 tokens: with larger ones llama.cpp's logits for the early positions change (it looks ahead), for a reason not yet found.
- **Reasoning models:** the reasoning is shown apart, in grey, and can be turned off.
-- **`janas-chat`:** a terminal chat with a line editor of its own, history,
- colours, a status line and a context that slides instead of ending.
-- **`libjanas_llm`:** a C library ([`include/janas/llm.h`](include/janas/llm.h))
- and a FreeBASIC binding ([`include/janas/llm.bi`](include/janas/llm.bi)).
-- **Tools from MCP servers** in `janas-chat`: the servers configured as the
- other clients configure them, each call shown and confirmed before it runs
- ([below](#tools-from-mcp-servers)). The client is a library of its own,
- **`libjanas_mcp`** ([`include/janas/mcp.h`](include/janas/mcp.h),
- [`include/janas/mcp.bi`](include/janas/mcp.bi)).
-- **`janas-mcp`:** the other way round, the model offered as tools to MCP
- clients - a question to it, the embedding of a text
- ([below](#janas-as-an-mcp-server)).
-- **`janas-flights`:** where a flight is and what flies over a sea or a
- place, as MCP tools, from the ADS-B receivers of the community, and
- today's schedules with a free AviationStack key: the first of Janas's
- services ([docs/services](docs/services/README.md)).
-- **`janas-server`:** the model behind an HTTP API that follows OpenAI's, so
- that clients written for it can use a model running on this machine:
- chat and completions with tools, JSON output held to a schema and
- log-probabilities, the Responses API with its conversations, embeddings
- and moderations, a chat page of its own to try it from a browser
- ([below](#using-it-over-http)), and code completion for VSCodium and VS
- Code ([docs/code-completion.md](docs/code-completion.md)).
+- **`janas-chat`:** a terminal chat with a line editor of its own, history, colours, a status line and a context that slides instead of ending.
+- **`libjanas_llm`:** a C library ([`include/janas/llm.h`](include/janas/llm.h)) and a FreeBASIC binding ([`include/janas/llm.bi`](include/janas/llm.bi)).
+- **Tools from MCP servers** in `janas-chat`: the servers configured as the other clients configure them, each call shown and confirmed before it runs ([below](#tools-from-mcp-servers)). The client is a library of its own, **`libjanas_mcp`** ([`include/janas/mcp.h`](include/janas/mcp.h), [`include/janas/mcp.bi`](include/janas/mcp.bi)).
+- **`janas-mcp`:** the other way round, the model offered as tools to MCP clients - a question to it, the embedding of a text ([below](#janas-as-an-mcp-server)).
+- **`janas-flights`:** where a flight is and what flies over a sea or a place, as MCP tools, from the ADS-B receivers of the community, and today's schedules with a free AviationStack key: the first of Janas's services ([docs/services](docs/services/README.md)).
+- **`janas-weather`:** the weather now, with what the nearest station measured, the forecast, the sea and its waves, and the warnings in force (in Italy the Civil Protection's levels), from free sources with no key ([docs/services/weather.md](docs/services/weather.md)).
+- **`janas-server`:** the model behind an HTTP API that follows OpenAI's, so that clients written for it can use a model running on this machine: chat and completions with tools, JSON output held to a schema and log-probabilities, the Responses API with its conversations, embeddings and moderations, a chat page of its own to try it from a browser ([below](#using-it-over-http)), and code completion for VSCodium and VS Code ([docs/code-completion.md](docs/code-completion.md)).
- **`janas-bench`:** measures the machine, fills its profile and writes a report.
-- **Faster replies** from drafts the model verifies, so the text is exactly the
- one it would have written: from the model's own multi-token prediction block
- where it has one, from the conversation where it does not, or from a small
- model of the same family given with `--draft`.
-- **Optional GPU** (Vulkan 1.3, integrated or discrete), used only where the
- engine measures that it helps, for every quantized type the CPU reads.
- Results are identical with and without it.
-- **Experts read ahead** when the expert cache is too small for the model:
- the next layer's router is applied early and the experts it picks that
- are not in memory are read from disk while the current layer computes.
- It turns itself on only when the cache misses many experts a token
- (Qwen3-Next-80B with a 4 GiB cache: +6%) and changes no result.
+- **Faster replies** from drafts the model verifies, so the text is exactly the one it would have written: from the model's own multi-token prediction block where it has one, from the conversation where it does not, or from a small model of the same family given with `--draft`.
+- **Optional GPU** (Vulkan 1.3, integrated or discrete), used only where the engine measures that it helps, for every quantized type the CPU reads. Results are identical with and without it.
+- **Experts read ahead** when the expert cache is too small for the model: the next layer's router is applied early and the experts it picks that are not in memory are read from disk while the current layer computes. It turns itself on only when the cache misses many experts a token (Qwen3-Next-80B with a 4 GiB cache: +6%) and changes no result.
On the machine above, with nothing else running, `janas-bench` reports this:
@@ -158,52 +71,15 @@ On the machine above, with nothing else running, `janas-bench` reports this:
| Qwen3.6-35B-A3B (22.3 GB) | 73 tok/s | 23 tok/s | **36 tok/s** |
| Qwen3-Next-80B-A3B (48.4 GB) | 65 tok/s | 23 tok/s | **36 tok/s** |
-Every figure is the **mean of three rounds**, not a best round, of the
-configuration the engine itself chose for each kind of pass - the one a chat
-runs: here all the usable cores (performance and efficiency cores, not
-the low-power ones), with the integrated GPU only where it helped, which
-was reading prompts on the two largest mixtures. On another machine the
-engine may settle on fewer threads: the first passes of each kind try
-every core, one thread per performance core and the performance cores'
-threads, and keep the fastest (on an i9-14900HX every thread replied at
-less than half the speed of the performance cores' 16). The rounds run in alternating
-order so that the machine warming up and the cache filling weigh on each
-setting alike. Expect a few per cent either way between runs, and rather
-less than these on a first run, while the cache is still filling.
-
-The last column is the model's own prediction block guessing the next tokens
-and the model checking them, which is the same text at a higher rate — the
-whole of it is explained under [`--mtp`](#using-the-chat). It is measured on
-a chat reply: an ordinary question in English ("explain how bread is made at
-home"), 64 tokens of the answer, sampled as the chat samples. **What the
-block is worth depends on the text**: there the drafts survived 78-89% of
-the time; on Italian prose Qwen3.5-2B kept about a third of them, and
-gained next to nothing. Qwen3-30B-A3B has no such block, nor have the dense
-Qwen3; the dense Qwen3.5 have one in their original checkpoint, which
-`hf2jns_mtp` converts ([MODELS.md](MODELS.md#the-fingerprints)).
-
-**This column was wrong until 26 September 2026**, and higher: it measured
-the block continuing a paragraph that repeated itself, which a model copies
-and the block guesses almost every time - 107 tok/s for Qwen3.5-2B, 26 for
-Qwen3.5-9B. The MoE figures of the time (29 and 30) happened to be lower
-than today's; the ChangeLog has the details.
-
-For a point of reference, llama.cpp (build `2b18470` of 18 September 2026)
-on the same Qwen3.5-9B file and the same machine, measured the same night
-with `llama-bench -p 256 -n 32` at 6, 12 and 20 threads, did best at 20:
-**32 tok/s** reading the prompt and **9.0 tok/s** writing. The two tools do
-not measure in exactly the same way (`llama-bench` writes without a prompt
-before it; `janas-bench` after 256 tokens of one), and it is one model on
-one machine.
-
-**Try it on an idle machine first.** The expert cache takes the memory that is
-free when the model is opened, and what is left of the model is read from disk
-while it answers, so everything else running takes its share. It degrades
-gently rather than breaking: measured with a browser and an editor open, the
-same model kept about three quarters of its speed and waited five times longer
-on the disk. But the first thing you see should be the machine's
-real speed, and any measurement you mean to send to others has to be taken with
-the machine to itself.
+Every figure is the **mean of three rounds**, not a best round, of the configuration the engine itself chose for each kind of pass - the one a chat runs: here all the usable cores (performance and efficiency cores, not the low-power ones), with the integrated GPU only where it helped, which was reading prompts on the two largest mixtures. On another machine the engine may settle on fewer threads: the first passes of each kind try every core, one thread per performance core and the performance cores' threads, and keep the fastest (on an i9-14900HX every thread replied at less than half the speed of the performance cores' 16). The rounds run in alternating order so that the machine warming up and the cache filling weigh on each setting alike. Expect a few per cent either way between runs, and rather less than these on a first run, while the cache is still filling.
+
+The last column is the model's own prediction block guessing the next tokens and the model checking them, which is the same text at a higher rate — the whole of it is explained under [`--mtp`](#using-the-chat). It is measured on a chat reply: an ordinary question in English ("explain how bread is made at home"), 64 tokens of the answer, sampled as the chat samples. **What the block is worth depends on the text**: there the drafts survived 78-89% of the time; on Italian prose Qwen3.5-2B kept about a third of them, and gained next to nothing. Qwen3-30B-A3B has no such block, nor have the dense Qwen3; the dense Qwen3.5 have one in their original checkpoint, which `hf2jns_mtp` converts ([MODELS.md](MODELS.md#the-fingerprints)).
+
+**This column was wrong until 26 September 2026**, and higher: it measured the block continuing a paragraph that repeated itself, which a model copies and the block guesses almost every time - 107 tok/s for Qwen3.5-2B, 26 for Qwen3.5-9B. The MoE figures of the time (29 and 30) happened to be lower than today's; the ChangeLog has the details.
+
+For a point of reference, llama.cpp (build `2b18470` of 18 September 2026) on the same Qwen3.5-9B file and the same machine, measured the same night with `llama-bench -p 256 -n 32` at 6, 12 and 20 threads, did best at 20: **32 tok/s** reading the prompt and **9.0 tok/s** writing. The two tools do not measure in exactly the same way (`llama-bench` writes without a prompt before it; `janas-bench` after 256 tokens of one), and it is one model on one machine.
+
+**Try it on an idle machine first.** The expert cache takes the memory that is free when the model is opened, and what is left of the model is read from disk while it answers, so everything else running takes its share. It degrades gently rather than breaking: measured with a browser and an editor open, the same model kept about three quarters of its speed and waited five times longer on the disk. But the first thing you see should be the machine's real speed, and any measurement you mean to send to others has to be taken with the machine to itself.
## Documentation
@@ -211,7 +87,7 @@ the machine to itself.
- [ChangeLog.md](ChangeLog.md) — what changed, newest first
- [MODELS.md](MODELS.md) — what a converted model's licence is, and what may be redistributed
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to help, and the sign-off
-- [docs/services](docs/services/README.md) — Janas's services (flights), in `janas-chat` and in other MCP clients
+- [docs/services](docs/services/README.md) — Janas's services (flights, weather), in `janas-chat` and in other MCP clients
- [docs/code-completion.md](docs/code-completion.md) — code completion in VSCodium and VS Code, through `janas-server`
- [AUTHORS](AUTHORS) — who wrote it, and what it owes to others
- [LICENSE](LICENSE) — GNU GPL, version 3 or later
@@ -229,10 +105,7 @@ sudo pacman -S vulkan-headers glslang vulkan-tools # the same, Arch
## Getting a model
-**The short way: `janas-get`.** One command downloads a model from
-Hugging Face, checks the SHA-256 of every file against [MODELS.md](MODELS.md),
-converts it and makes its prediction file beside it (an MTP block, or Gemma
-4's assistant), which the chat then finds by itself:
+**The short way: `janas-get`.** One command downloads a model from Hugging Face, checks the SHA-256 of every file against [MODELS.md](MODELS.md), converts it and makes its prediction file beside it (an MTP block, or Gemma 4's assistant), which the chat then finds by itself:
```sh
bin/x86_64-linux/janas-get list # the models it knows
@@ -240,19 +113,9 @@ bin/x86_64-linux/janas-get gemma-4-e4b # into models/
bin/x86_64-linux/janas-chat models/gemma-4-e4b-it-q4km.jns
```
-A download stopped halfway resumes where it stopped, a file already there
-is checked rather than fetched again, and the GGUF goes once converted
-(`--keep` keeps it). Any other GGUF: `janas-get
-hf:<owner>/<repo>/<file.gguf>`, checked against the SHA-256 Hugging Face
-lists for it. The memory column of `janas-get list` is the smallest
-machine each model is meant for. The rest of this section is the same by
-hand.
+A download stopped halfway resumes where it stopped, a file already there is checked rather than fetched again, and the GGUF goes once converted (`--keep` keeps it). Any other GGUF: `janas-get hf:<owner>/<repo>/<file.gguf>`, checked against the SHA-256 Hugging Face lists for it. The memory column of `janas-get list` is the smallest machine each model is meant for. The rest of this section is the same by hand.
-Janas reads its own format, `.jns`, converted from a **Q4_K_M** GGUF (Q3_K,
-IQ3_S, IQ4_NL, IQ4_XS, Q4_0, Q4_1 and Q5_1 convert too, and so do unsloth's
-"UD" files made of them; IQ2 and IQ1 types, not yet). Keep both
-in `models/` next to the sources — the tools take a path, so anywhere works, but
-that is where these examples put them, and where the project keeps its own.
+Janas reads its own format, `.jns`, converted from a **Q4_K_M** GGUF (Q3_K, IQ3_S, IQ4_NL, IQ4_XS, Q4_0, Q4_1 and Q5_1 convert too, and so do unsloth's "UD" files made of them; IQ2 and IQ1 types, not yet). Keep both in `models/` next to the sources — the tools take a path, so anywhere works, but that is where these examples put them, and where the project keeps its own.
| Model | GGUF converted here | GGUF | `.jns` | Memory it likes |
|---|---|---|---|---|
@@ -267,24 +130,11 @@ that is where these examples put them, and where the project keeps its own.
| **Qwen3-0.6B** — not to talk to: to draft for a dense one (`--draft`) | [unsloth](https://huggingface.co/unsloth/Qwen3-0.6B-GGUF) | 0.40 GB | 0.40 GB | with the model above |
| **Qwen3-Embedding-0.6B** — not to talk to: for embeddings (`janas-server --embedding-model`); published in Q8_0 and converted as it is | [Qwen](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF) | 0.64 GB | 0.64 GB | beside the chat model |
-Qwen3 has other dense models - 1.7B, 8B, 14B, 32B - which declare the same
-architecture as the 4B and so should convert and run the same way. **None of
-them has been tried here**, and until one is, that is a reading of the file
-and not a claim. (Qwen3-30B-A3B is not one of them: the number is close but it
-is a mixture of experts, with an architecture of its own.)
-
-Any other Q4_K_M of the same models converts and runs just as well, including
-the "dynamic" ones that give different tensors different types: the engine
-reads Q4_K, Q5_K, Q6_K and Q8_0, and refuses a file carrying anything else
-rather than guessing. The four above are the files the numbers in this
-repository were measured on, and the ones [MODELS.md](MODELS.md) gives
-fingerprints for, so that a converted file can be checked against the one
-measured here without downloading anything.
-
-All four models are published under the Apache 2.0 licence by Alibaba Cloud,
-and quantized into GGUF by them or by the people above. Their licence is
-theirs, not this project's: [MODELS.md](MODELS.md) says what that means if you
-pass a converted file on to somebody else.
+Qwen3 has other dense models - 1.7B, 8B, 14B, 32B - which declare the same architecture as the 4B and so should convert and run the same way. **None of them has been tried here**, and until one is, that is a reading of the file and not a claim. (Qwen3-30B-A3B is not one of them: the number is close but it is a mixture of experts, with an architecture of its own.)
+
+Any other Q4_K_M of the same models converts and runs just as well, including the "dynamic" ones that give different tensors different types: the engine reads Q4_K, Q5_K, Q6_K and Q8_0, and refuses a file carrying anything else rather than guessing. The four above are the files the numbers in this repository were measured on, and the ones [MODELS.md](MODELS.md) gives fingerprints for, so that a converted file can be checked against the one measured here without downloading anything.
+
+All four models are published under the Apache 2.0 licence by Alibaba Cloud, and quantized into GGUF by them or by the people above. Their licence is theirs, not this project's: [MODELS.md](MODELS.md) says what that means if you pass a converted file on to somebody else.
**Download.** Nothing needs installing — one file, resumable:
@@ -295,32 +145,23 @@ curl -L -C - -O \
cd ../..
```
-With `pip install huggingface_hub` you can instead fetch a whole quantization,
-which is handier when it is split into several files, as Qwen3-Coder-Next is:
+With `pip install huggingface_hub` you can instead fetch a whole quantization, which is handier when it is split into several files, as Qwen3-Coder-Next is:
```sh
huggingface-cli download Qwen/Qwen3-Coder-Next-GGUF \
--include "Qwen3-Coder-Next-Q4_K_M/*" --local-dir models/gguf
```
-**Convert**, with the converter the build made (nothing else to install).
-With a model split into several files, give the first one and the rest is
-found:
+**Convert**, with the converter the build made (nothing else to install). With a model split into several files, give the first one and the rest is found:
```sh
bin/x86_64-linux/gguf2jns models/gguf/Qwen_Qwen3.6-35B-A3B-Q4_K_M.gguf \
models/qwen3.6-35b-a3b-flat.jns
```
-It says what it is doing, and refuses a model it does not know with a clear
-message rather than half a conversion.
+It says what it is doing, and refuses a model it does not know with a clear message rather than half a conversion.
-**Cut the experts into bit planes.** Worth it on any machine that cannot hold
-all the experts in memory, which is the case this engine is built for: the
-down matrix is stored as three planes of two bits, so the engine can read four
-bits of it, or two, instead of six, and decide which when the model is opened.
-Nothing is lost — all three planes give the weights the file came with, bit for
-bit. This is the form the models here are kept in:
+**Cut the experts into bit planes.** Worth it on any machine that cannot hold all the experts in memory, which is the case this engine is built for: the down matrix is stored as three planes of two bits, so the engine can read four bits of it, or two, instead of six, and decide which when the model is opened. Nothing is lost — all three planes give the weights the file came with, bit for bit. This is the form the models here are kept in:
```sh
bin/x86_64-linux/jns_planes models/qwen3.6-35b-a3b-flat.jns \
@@ -335,34 +176,20 @@ bin/x86_64-linux/jns_check models/qwen3.6-35b-a3b.jns # what is insid
bin/x86_64-linux/jns_check models/qwen3.6-35b-a3b.jns --verify # and the checksums
```
-Both steps are deterministic, so the file can be checked against the
-fingerprints in [MODELS.md](MODELS.md).
+Both steps are deterministic, so the file can be checked against the fingerprints in [MODELS.md](MODELS.md).
-Room needed: three copies of the model at the worst moment — the GGUF, the
-converted file and the one with the planes — so about 145 GB for the largest.
-The flat file goes as soon as the planes are written, and the GGUF can go too,
-though keeping it saves the download the day a new version of the converter is
-worth running.
+Room needed: three copies of the model at the worst moment — the GGUF, the converted file and the one with the planes — so about 145 GB for the largest. The flat file goes as soon as the planes are written, and the GGUF can go too, though keeping it saves the download the day a new version of the converter is worth running.
-**The multi-token prediction block** (Qwen3-Next and the dense Qwen3.5;
-optional, faster replies). Its own model carries it, GGUF files leave it
-out, so it comes from the original checkpoint. `hf2jns_mtp` can read just
-the block's tensors from Hugging Face, with range requests, instead of the
-shards that hold them:
+**The multi-token prediction block** (Qwen3-Next and the dense Qwen3.5; optional, faster replies). Its own model carries it, GGUF files leave it out, so it comes from the original checkpoint. `hf2jns_mtp` can read just the block's tensors from Hugging Face, with range requests, instead of the shards that hold them:
```sh
bin/x86_64-linux/hf2jns_mtp models/qwen3-next.jns \
hf:Qwen/Qwen3-Next-80B-A3B-Instruct models/qwen3-next-mtp.jns
```
-For the dense Qwen3.5-9B that is 487 MB instead of 14 GB of shards, in under
-a minute. It also takes the shards themselves, when you have them on disk
-(`hf2jns_mtp <model.jns> <shard>... <out.jns>`). Qwen3.6-35B-A3B needs none of
-this: its GGUF keeps the block.
+For the dense Qwen3.5-9B that is 487 MB instead of 14 GB of shards, in under a minute. It also takes the shards themselves, when you have them on disk (`hf2jns_mtp <model.jns> <shard>... <out.jns>`). Qwen3.6-35B-A3B needs none of this: its GGUF keeps the block.
-**Gemma 4** comes from unsloth's GGUF files, converted in one step, and
-so does its assistant (the `mtp-gemma-4-*.gguf` file beside the model,
-under 0.5 GB), which serves as the multi-token prediction file:
+**Gemma 4** comes from unsloth's GGUF files, converted in one step, and so does its assistant (the `mtp-gemma-4-*.gguf` file beside the model, under 0.5 GB), which serves as the multi-token prediction file:
```sh
huggingface-cli download unsloth/gemma-4-E4B-it-GGUF \
@@ -374,11 +201,7 @@ bin/x86_64-linux/gguf2jns models/gguf/mtp-gemma-4-E4B-it.gguf \
models/gemma-4-e4b-mtp.jns
```
-The same for E2B, the 12B (`gemma-4-12b-it-Q4_K_M.gguf`) and the 26B
-(`gemma-4-26B-A4B-it-UD-Q4_K_M.gguf`); the fingerprints are in
-[MODELS.md](MODELS.md#the-fingerprints). E2B's per-layer table, half of its
-file, is read from the file a token at a time and never loaded: E2B ran
-here in 1.5 GB of memory, E4B in 3.1 GB.
+The same for E2B, the 12B (`gemma-4-12b-it-Q4_K_M.gguf`) and the 26B (`gemma-4-26B-A4B-it-UD-Q4_K_M.gguf`); the fingerprints are in [MODELS.md](MODELS.md#the-fingerprints). E2B's per-layer table, half of its file, is read from the file a token at a time and never loaded: E2B ran here in 1.5 GB of memory, E4B in 3.1 GB.
**And chat:**
@@ -387,19 +210,11 @@ bin/x86_64-linux/janas-chat models/qwen3-next.jns --stats
bin/x86_64-linux/janas-chat models/gemma-4-e4b.jns --stats
```
-The chat finds the multi-token prediction file by itself: of the `.jns`
-files beside the model, the one whose header fits it (an MTP block of the
-same architecture and width, or Gemma 4's assistant for a model that wide
-and with its vocabulary), and says which it took. `--mtp <file>` names
-one; `--no-mtp` goes without. `janas-server` does the same, and programs
-can ask for it with `janas_llm_find_mtp()`.
+The chat finds the multi-token prediction file by itself: of the `.jns` files beside the model, the one whose header fits it (an MTP block of the same architecture and width, or Gemma 4's assistant for a model that wide and with its vocabulary), and says which it took. `--mtp <file>` names one; `--no-mtp` goes without. `janas-server` does the same, and programs can ask for it with `janas_llm_find_mtp()`.
-The first start reads the model's resident weights (a couple of GB) and then
-fills the expert cache in the background, while you read and type. The second
-reply of a session is the one that shows the machine's real speed.
+The first start reads the model's resident weights (a couple of GB) and then fills the expert cache in the background, while you read and type. The second reply of a session is the one that shows the machine's real speed.
-[INSTALL.md](INSTALL.md) has the details, including the other distributions and
-what to do when the GPU is not found.
+[INSTALL.md](INSTALL.md) has the details, including the other distributions and what to do when the GPU is not found.
## Using the chat
@@ -430,73 +245,15 @@ janas-chat <model.jns> [options]
| `--stats` | a line of counters after every reply: speeds, time to the first token, threads, memory |
| `--progress <s>` | a line on stderr every `s` seconds while a long prompt is read (tokens read, rate, time left as an estimate), and one after each reply; on a terminal the status line shows the same while it reads |
-**On `--mtp`, `--draft` and `--no-spec`.** Speculative decoding is not a trade of
-quality for speed: it changes how many tokens come out of one pass, never
-which ones. The small multi-token prediction block guesses the next few
-tokens, the model then runs one pass over the guesses, and a guess is kept
-only where the token the model itself sampled is the very same one - at the
-first disagreement the guess is thrown away and the model's own token stands.
-So no wrong guess can survive into the text, and with the same seed the reply
-is the one you would have got without any of it - checked on every run of the
-tests, 256 tokens with drafts and 256 without, from one seed, identical, and
-in `janas-chat` itself over a conversation of three replies cut at 600
-tokens, with and without drafts. How many guesses a pass checks is decided
-from what passes have cost on this machine, and a pass with a guess is still
-tried now and then when the engine has stopped guessing, so that a moment of
-a busy disk does not switch the guesses off for the rest of the session
-(until 1 October 2026 it could: the same chat of Qwen3-Next-80B then ran at
-22 tok/s one time and 26 the next). On
-the development laptop `--mtp` takes Qwen3-Next-80B-A3B from 23 tok/s to 36
-and Qwen3.5-9B from 13 to 22 on an English explanation, and Gemma 4's
-assistants take its four models about one and a half times faster on an
-Italian chat reply (E4B from 18 tok/s to 26, the 12B from 8.5 to 12.9);
-how much it gives depends on the text, and on Italian prose a small Qwen
-gains little. It gives nothing either where the expert cache is much smaller
-than the model: two tokens in a pass call more experts than one, and the
-disk is already the limit (Qwen3-Next-80B with a 4 GiB cache: a run whose
-guesses had stopped after the first reply wrote at 12.75 tok/s, the five
-that kept them at 12.05-12.55).
-`--no-spec` and `/spec off` turn it off; they buy nothing but time, and are
-there to measure with.
-
-Where a model has no prediction block the guesses are copied from the
-conversation instead, which costs nothing and is right about a quarter of the
-time - enough to be worth it on a dense model and barely enough on a mixture.
-**`--draft` puts a small model of the same family in their place**: it has to
-share the vocabulary, it borrows the big model's threads, and it predicts
-where copying only repeats, so it is right about three quarters of the time.
-Whether that pays depends on what a second token in a pass costs, which is
-about 6% on a dense model and about 28% on a mixture, where two tokens route
-to different experts. So it is for dense models: Qwen3-0.6B drafting Qwen3-4B
-gives **1.14x** - 23.0 to 26.3 tok/s, measured at the chat's own
-temperature, which is why the pair is lower than the table above - and on
-Qwen3-30B-A3B it would not pay for itself.
-
-**On sampling.** The defaults are the ones Qwen recommends for its own models:
-temperature 0.7, top-k 20, top-p 0.8. They are narrower than they look. With
-top-p 0.8, on Qwen3-4B, **196 of 256 tokens had a single candidate left after
-the cut** - nothing to draw, so the reply is the one the model would have given
-greedily, and two questions that mean the same thing get the same words.
-Starting with `--top-p 0.95` brings that to 142 of 256. It is not a fault and
-not a setting this project chose: it is what those numbers do to a model that
-is sure of itself.
-
-**On `--attention`.** At a long context most of a token goes into attention,
-and most of that into the scores: one dot product per position, per head. The
-`fast` way reads the query as sixteen-bit integers with a scale of its own, so
-the dot product becomes an exact integer sum — the machine does sixteen of
-those products at a time instead of eight, and the scores come out a fifth to
-a quarter quicker. What it costs is the query's quantization, a relative
-3e-5, sixty times less than the eight-bit keys and values already carry; on
-four hundred tokens against llama.cpp the most likely token agreed 394 times
-out of 400 on C source against 393 the exact way, and 377 against 382 on
-Italian prose. The engine asks for it by itself only when you asked for more
-than 16384 tokens of context, where the gain is real and the conversation
-will get there; `--attention exact` and `--attention fast` settle it either
-way, and so does `JANAS_ATTN=float|int16`.
-
-In the chat, a line starting with `/` is a command, and it turns grey-blue as
-soon as it names one the chat really has:
+**On `--mtp`, `--draft` and `--no-spec`.** Speculative decoding is not a trade of quality for speed: it changes how many tokens come out of one pass, never which ones. The small multi-token prediction block guesses the next few tokens, the model then runs one pass over the guesses, and a guess is kept only where the token the model itself sampled is the very same one - at the first disagreement the guess is thrown away and the model's own token stands. So no wrong guess can survive into the text, and with the same seed the reply is the one you would have got without any of it - checked on every run of the tests, 256 tokens with drafts and 256 without, from one seed, identical, and in `janas-chat` itself over a conversation of three replies cut at 600 tokens, with and without drafts. How many guesses a pass checks is decided from what passes have cost on this machine, and a pass with a guess is still tried now and then when the engine has stopped guessing, so that a moment of a busy disk does not switch the guesses off for the rest of the session (until 1 October 2026 it could: the same chat of Qwen3-Next-80B then ran at 22 tok/s one time and 26 the next). On the development laptop `--mtp` takes Qwen3-Next-80B-A3B from 23 tok/s to 36 and Qwen3.5-9B from 13 to 22 on an English explanation, and Gemma 4's assistants take its four models about one and a half times faster on an Italian chat reply (E4B from 18 tok/s to 26, the 12B from 8.5 to 12.9); how much it gives depends on the text, and on Italian prose a small Qwen gains little. It gives nothing either where the expert cache is much smaller than the model: two tokens in a pass call more experts than one, and the disk is already the limit (Qwen3-Next-80B with a 4 GiB cache: a run whose guesses had stopped after the first reply wrote at 12.75 tok/s, the five that kept them at 12.05-12.55). `--no-spec` and `/spec off` turn it off; they buy nothing but time, and are there to measure with.
+
+Where a model has no prediction block the guesses are copied from the conversation instead, which costs nothing and is right about a quarter of the time - enough to be worth it on a dense model and barely enough on a mixture. **`--draft` puts a small model of the same family in their place**: it has to share the vocabulary, it borrows the big model's threads, and it predicts where copying only repeats, so it is right about three quarters of the time. Whether that pays depends on what a second token in a pass costs, which is about 6% on a dense model and about 28% on a mixture, where two tokens route to different experts. So it is for dense models: Qwen3-0.6B drafting Qwen3-4B gives **1.14x** - 23.0 to 26.3 tok/s, measured at the chat's own temperature, which is why the pair is lower than the table above - and on Qwen3-30B-A3B it would not pay for itself.
+
+**On sampling.** The defaults are the ones Qwen recommends for its own models: temperature 0.7, top-k 20, top-p 0.8. They are narrower than they look. With top-p 0.8, on Qwen3-4B, **196 of 256 tokens had a single candidate left after the cut** - nothing to draw, so the reply is the one the model would have given greedily, and two questions that mean the same thing get the same words. Starting with `--top-p 0.95` brings that to 142 of 256. It is not a fault and not a setting this project chose: it is what those numbers do to a model that is sure of itself.
+
+**On `--attention`.** At a long context most of a token goes into attention, and most of that into the scores: one dot product per position, per head. The `fast` way reads the query as sixteen-bit integers with a scale of its own, so the dot product becomes an exact integer sum — the machine does sixteen of those products at a time instead of eight, and the scores come out a fifth to a quarter quicker. What it costs is the query's quantization, a relative 3e-5, sixty times less than the eight-bit keys and values already carry; on four hundred tokens against llama.cpp the most likely token agreed 394 times out of 400 on C source against 393 the exact way, and 377 against 382 on Italian prose. The engine asks for it by itself only when you asked for more than 16384 tokens of context, where the gain is real and the conversation will get there; `--attention exact` and `--attention fast` settle it either way, and so does `JANAS_ATTN=float|int16`.
+
+In the chat, a line starting with `/` is a command, and it turns grey-blue as soon as it names one the chat really has:
| Command | |
|---|---|
@@ -515,57 +272,19 @@ soon as it names one the chat really has:
| `/del-config` | forget the saved settings: the next start uses the chat's own |
| `/quit` | leave (also `Ctrl-D`) |
-`/help` and `/about` open a page over the conversation: the text is laid out
-to the window however narrow it is, the arrows and **Page Up** and **Page
-Down** move in it, and **ESC** closes it - no other key does, so a page cannot
-be shut by the one you pressed looking for a way down. `/about` gives the
-version, the author, the licence and the repository, and then the model, the
-machine and the engine as they are at that moment: the three things a report
-of a problem needs, which were until now to be gathered by hand.
-
-What a command changes lasts for that conversation and no longer: a knob
-turned to try something does not quietly become the way things are.
-`/save-config` writes the settings to `~/.config/janas/chat.conf` and
-`/load-config` reads them back, losing whatever is set at the time, which it
-asks about first, and `/del-config` throws the file away so that the next
-start uses the chat's own settings again. The file
-holds the words of the command line, one option to a line and the rest of the
-line its value, so the same reader takes both and you can open it and edit it;
-it is read before the command line, which therefore wins. The system message
-is not kept in it, and the context, the cache, the bits and the attention are
-read at the next start, since they are settled when the model is opened.
-
-A model marks its replies up - `**bold**`, `*italic*`, backticks, fenced
-blocks, headings, bullets - and the chat reads those marks rather than
-printing them: bold is bold, a block of code is told from the prose by its
-colour, a dash becomes a bullet. An underscore counts as italic only alone and
-at the edge of a word, so `_this_` and `**_this_**` are marks while
-`snake_case` and `__init__`, which a conversation about code is full of, stay
-as they are; a star inside a word is not a mark either, so `2*3` is a product.
-`--no-markdown` and `/markdown off` print the marks as they come, and a pipe
-always gets them: a script may want them.
-
-The box the message is written in takes the rows the message needs, up to a
-third of the window, and goes back to one when it has been sent: a long
-question is read while it is written instead of scrolling away sideways.
-
-The conversation is kept as it is written, so **Page Up** and **Page Down**
-look back over it and **Ctrl-Home** and **Ctrl-End** go to its beginning and
-its end. The line being written stays where it is while you read, and sending
-brings the end back. A terminal cannot do this by itself here: the chat pins
-its footer with a scrolling region, and the lines that leave the top of one
-never reach the terminal's own history.
-
-The arrows move in the message - up and down between its lines while it has
-more than one - and bring back earlier prompts from its first and last line,
-kept between sessions; `Home`, `End`, `Delete`, `Ctrl-A/E/K/U/W` and `Ctrl-L` do what they do
-everywhere; `Tab` completes a command; a backslash and `Enter` add a line to
-the message rather than sending it, the backslash itself is not part of what
-the model reads, and the box grows to hold what is written; `Ctrl-C` stops a
-reply.
-
-Piped in or out, the chat writes plain text with no drawing at all, so it can be
-scripted:
+`/help` and `/about` open a page over the conversation: the text is laid out to the window however narrow it is, the arrows and **Page Up** and **Page Down** move in it, and **ESC** closes it - no other key does, so a page cannot be shut by the one you pressed looking for a way down. `/about` gives the version, the author, the licence and the repository, and then the model, the machine and the engine as they are at that moment: the three things a report of a problem needs, which were until now to be gathered by hand.
+
+What a command changes lasts for that conversation and no longer: a knob turned to try something does not quietly become the way things are. `/save-config` writes the settings to `~/.config/janas/chat.conf` and `/load-config` reads them back, losing whatever is set at the time, which it asks about first, and `/del-config` throws the file away so that the next start uses the chat's own settings again. The file holds the words of the command line, one option to a line and the rest of the line its value, so the same reader takes both and you can open it and edit it; it is read before the command line, which therefore wins. The system message is not kept in it, and the context, the cache, the bits and the attention are read at the next start, since they are settled when the model is opened.
+
+A model marks its replies up - `**bold**`, `*italic*`, backticks, fenced blocks, headings, bullets - and the chat reads those marks rather than printing them: bold is bold, a block of code is told from the prose by its colour, a dash becomes a bullet. An underscore counts as italic only alone and at the edge of a word, so `_this_` and `**_this_**` are marks while `snake_case` and `__init__`, which a conversation about code is full of, stay as they are; a star inside a word is not a mark either, so `2*3` is a product. `--no-markdown` and `/markdown off` print the marks as they come, and a pipe always gets them: a script may want them.
+
+The box the message is written in takes the rows the message needs, up to a third of the window, and goes back to one when it has been sent: a long question is read while it is written instead of scrolling away sideways.
+
+The conversation is kept as it is written, so **Page Up** and **Page Down** look back over it and **Ctrl-Home** and **Ctrl-End** go to its beginning and its end. The line being written stays where it is while you read, and sending brings the end back. A terminal cannot do this by itself here: the chat pins its footer with a scrolling region, and the lines that leave the top of one never reach the terminal's own history.
+
+The arrows move in the message - up and down between its lines while it has more than one - and bring back earlier prompts from its first and last line, kept between sessions; `Home`, `End`, `Delete`, `Ctrl-A/E/K/U/W` and `Ctrl-L` do what they do everywhere; `Tab` completes a command; a backslash and `Enter` add a line to the message rather than sending it, the backslash itself is not part of what the model reads, and the box grows to hold what is written; `Ctrl-C` stops a reply.
+
+Piped in or out, the chat writes plain text with no drawing at all, so it can be scripted:
```sh
printf 'Explain mixture of experts in one paragraph.\n/quit\n' \
@@ -574,19 +293,11 @@ printf 'Explain mixture of experts in one paragraph.\n/quit\n' \
### Janas's services
-The chat starts by itself the services of Janas it finds beside it - for
-now `janas-flights` - and the model uses their tools when a question needs
-them, without being told: ask "which flights are over the Tyrrhenian Sea
-now?". `--no-services` starts none. How they work, their keys, and how to
-use them in Claude Code and other clients:
-[docs/services](docs/services/README.md).
+The chat starts by itself the services of Janas it finds beside it - `janas-flights` and `janas-weather` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?" or "what's the weather like?" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
### Tools from MCP servers
-The chat also starts the [Model Context Protocol](https://modelcontextprotocol.io)
-servers listed in `~/.config/janas/mcp.json` (or in the file `--mcp-config`
-names), in the format the other clients use, so a configuration can be
-copied from one of them:
+The chat also starts the [Model Context Protocol](https://modelcontextprotocol.io) servers listed in `~/.config/janas/mcp.json` (or in the file `--mcp-config` names), in the format the other clients use, so a configuration can be copied from one of them:
```json
{"mcpServers": {
@@ -595,101 +306,29 @@ copied from one of them:
"/home/me/notes"]}}}
```
-Their tools are given to the model as `server__tool`. When the model calls
-one, the chat shows the call with its arguments and waits for a key: `y` runs
-it, `n` tells the model it was not allowed, `a` runs it and every later call
-of the same tool. `/mcp` lists the servers and their tools; `/mcp auto`, or
-`--mcp-auto` at the start, runs the calls without asking - which a pipe
-needs, since nobody is there to answer, and without which a piped chat runs
-none. `--no-mcp` starts no server. A tool runs with your rights, and what it
-answers is text somebody else wrote that the model then reads: configure
-only servers you trust, and read the calls before saying yes. For the same
-reason the instructions a server gives for its tools stay out of the
-model's system message unless `--mcp-instructions` asks for them; then
-they follow it, marked as the servers' and not the user's.
-
-Servers are spoken to over their standard input and output (the stdio
-transport), in either era of the protocol: the stateless revision 2026-07-28,
-and the handshake of 2025-11-25 and before, which most servers still speak;
-which one a server speaks is found out when it starts. What a server writes
-to its standard error goes to `~/.cache/janas/mcp/<name>.log`. A server
-that listens at an address is named with `url` (and `headers`, for an
-`Authorization` say) instead of `command`, and spoken to over Streamable
-HTTP, again in either era; `https://` too, the server's certificate checked
-against the system's certificate authorities (or `SSL_CERT_FILE`) and its
-name.
-It has been run against the test server in
-[`tests/mcp_fake_server.c`](tests/mcp_fake_server.c), in both eras, over
-stdio and over HTTP, and against two reference servers over stdio, both of
-the 2025-11-25 era: `@modelcontextprotocol/server-filesystem` 0.2.0 (npx,
-14 tools) and `mcp-server-git` 1.30.0 (uvx, 12 tools), together, with
-Qwen3-4B choosing among their 26 tools - `git_log` for the last commit of a
-repository, `list_directory` then `read_text_file` to find a date in a
-folder. Their descriptions take about 3,700 tokens of the system message,
-read once and kept computed. Over HTTPS it has reached DeepWiki
-(`https://mcp.deepwiki.com/mcp`, 2025-11-25 era, a session per client). A small model does not always find its way:
-asked without a hint, Qwen3-4B tried to read the folder itself as a file,
-got the server's error, and stopped there.
+Their tools are given to the model as `server__tool`. When the model calls one, the chat shows the call with its arguments and waits for a key: `y` runs it, `n` tells the model it was not allowed, `a` runs it and every later call of the same tool. `/mcp` lists the servers and their tools; `/mcp auto`, or `--mcp-auto` at the start, runs the calls without asking - which a pipe needs, since nobody is there to answer, and without which a piped chat runs none. `--no-mcp` starts no server. A tool runs with your rights, and what it answers is text somebody else wrote that the model then reads: configure only servers you trust, and read the calls before saying yes. For the same reason the instructions a server gives for its tools stay out of the model's system message unless `--mcp-instructions` asks for them; then they follow it, marked as the servers' and not the user's.
+
+Servers are spoken to over their standard input and output (the stdio transport), in either era of the protocol: the stateless revision 2026-07-28, and the handshake of 2025-11-25 and before, which most servers still speak; which one a server speaks is found out when it starts. What a server writes to its standard error goes to `~/.cache/janas/mcp/<name>.log`. A server that listens at an address is named with `url` (and `headers`, for an `Authorization` say) instead of `command`, and spoken to over Streamable HTTP, again in either era; `https://` too, the server's certificate checked against the system's certificate authorities (or `SSL_CERT_FILE`) and its name. It has been run against the test server in [`tests/mcp_fake_server.c`](tests/mcp_fake_server.c), in both eras, over stdio and over HTTP, and against two reference servers over stdio, both of the 2025-11-25 era: `@modelcontextprotocol/server-filesystem` 0.2.0 (npx, 14 tools) and `mcp-server-git` 1.30.0 (uvx, 12 tools), together, with Qwen3-4B choosing among their 26 tools - `git_log` for the last commit of a repository, `list_directory` then `read_text_file` to find a date in a folder. Their descriptions take about 3,700 tokens of the system message, read once and kept computed. Over HTTPS it has reached DeepWiki (`https://mcp.deepwiki.com/mcp`, 2025-11-25 era, a session per client). A small model does not always find its way: asked without a hint, Qwen3-4B tried to read the folder itself as a file, got the server's error, and stopped there.
### Watching a long prompt
-A long prompt is most of what a reply costs: on a laptop CPU, 260,000 tokens
-of Qwen3-Next-80B-A3B take hours to read and seconds to answer. So the
-reading tells how it goes. The library reads a prompt a block of 256 tokens
-at a time, and `janas_llm_chat_next` returns an empty piece after each
-block, so a program has control between them; `janas_llm_chat_stats` says
-the stage (reading, writing, done), the tokens read of those to read, the
-time to the first token, the time spent building the prompt, the processor
-time of the reading, the threads the engine chose, the memory of the
-context and the process's peak, how the prompt is made up (system
-message and tools, the conversation before, the last message), and an
-estimate of the time left. `max_input`
-in the chat's parameters refuses a longer prompt with its numbers, and never
-cuts it.
-
-Any program on the library, its own code unchanged, can have the same from
-the environment: `JANAS_PROGRESS=30` writes a line on stderr every thirty
-seconds while a prompt is read and one at the end of each reply, and
-`JANAS_METRICS=file` appends JSON lines - events `open`, `prompt`,
-`progress` (every `JANAS_METRICS_EVERY` seconds, 10 by default), `first_token`,
-`reply` and `refused` - with counters and times only, never the text of a
-prompt or a reply:
+A long prompt is most of what a reply costs: on a laptop CPU, 260,000 tokens of Qwen3-Next-80B-A3B take hours to read and seconds to answer. So the reading tells how it goes. The library reads a prompt a block of 256 tokens at a time, and `janas_llm_chat_next` returns an empty piece after each block, so a program has control between them; `janas_llm_chat_stats` says the stage (reading, writing, done), the tokens read of those to read, the time to the first token, the time spent building the prompt, the processor time of the reading, the threads the engine chose, the memory of the context and the process's peak, how the prompt is made up (system message and tools, the conversation before, the last message), and an estimate of the time left. `max_input` in the chat's parameters refuses a longer prompt with its numbers, and never cuts it.
+
+Any program on the library, its own code unchanged, can have the same from the environment: `JANAS_PROGRESS=30` writes a line on stderr every thirty seconds while a prompt is read and one at the end of each reply, and `JANAS_METRICS=file` appends JSON lines - events `open`, `prompt`, `progress` (every `JANAS_METRICS_EVERY` seconds, 10 by default), `first_token`, `reply` and `refused` - with counters and times only, never the text of a prompt or a reply:
```json
{"event":"progress","time":"2026-09-25T08:44:52.027Z","pid":3948047,"reply":1,"stage":"input","input_done":1536,"input_tokens":3044,"elapsed_seconds":3.8,"tokens_per_second":362.75,"tokens_per_second_avg":405.32,"eta_seconds_estimate":4}
```
-The time left is an estimate that follows how the reading slows: a token
-costs more the more context it follows, attention having more to look at,
-so the engine fits that cost as a line in the token's position over the
-blocks read so far and adds it up to the end of the prompt, never below
-what the latest speed says. On a 260,954-token prompt of
-Qwen3-Next-80B-A3B the elapsed time followed that shape to R² 0.99999,
-where an estimate from the current rate promised 2.5 times too little at
-32K ([issue #9](https://github.com/prabanta-dev/janas/issues/9)); the new
-estimate has not yet been checked on a run that long.
-`janas-chat` shows the progress in its status line and takes `--progress`;
-`janas-server` takes `--metrics`, `--progress`, `--max-input` and
-`--warn-input`.
+The time left is an estimate that follows how the reading slows: a token costs more the more context it follows, attention having more to look at, so the engine fits that cost as a line in the token's position over the blocks read so far and adds it up to the end of the prompt, never below what the latest speed says. On a 260,954-token prompt of Qwen3-Next-80B-A3B the elapsed time followed that shape to R² 0.99999, where an estimate from the current rate promised 2.5 times too little at 32K ([issue #9](https://github.com/prabanta-dev/janas/issues/9)); the new estimate has not yet been checked on a run that long. `janas-chat` shows the progress in its status line and takes `--progress`; `janas-server` takes `--metrics`, `--progress`, `--max-input` and `--warn-input`.
## Filling in code
-`janas-server` fills in code at an editor's cursor, with a model for code
-such as Qwen3-Coder-30B-A3B: OpenAI's `/v1/completions` with a `suffix`,
-and llama.cpp's `/infill`, which llama.vscode asks. The window sent at
-every keystroke is kept from moving, so that a keystroke reads only what
-it changed: 1.5-2.2 s a proposal on a laptop, where a window slid a line
-was read again in 17 s. How to set it up in VSCodium and VS Code, with
-llama.vscode or Continue, and what was measured:
-[docs/code-completion.md](docs/code-completion.md).
+`janas-server` fills in code at an editor's cursor, with a model for code such as Qwen3-Coder-30B-A3B: OpenAI's `/v1/completions` with a `suffix`, and llama.cpp's `/infill`, which llama.vscode asks. The window sent at every keystroke is kept from moving, so that a keystroke reads only what it changed: 1.5-2.2 s a proposal on a laptop, where a window slid a line was read again in 17 s. How to set it up in VSCodium and VS Code, with llama.vscode or Continue, and what was measured: [docs/code-completion.md](docs/code-completion.md).
## 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**.
### From C
@@ -714,23 +353,11 @@ while (janas_llm_chat_next(chat, piece, sizeof(piece), &len) == JANAS_LLM_OK)
cc yours.c -Iinclude -Lbin/x86_64-linux -ljanas_llm -o yours
```
-A program that keeps the conversation itself - an HTTP client does, and sends
-it whole every time - hands it over with `janas_llm_chat_load`: the messages
-with their roles, the last one the user's. Whatever the new conversation
-shares with the one already computed is not read again, so the same messages
-plus a new one cost only the new one. `janas_llm_chat_prompt` continues raw
-text, with no chat format around it, and `janas_llm_default_system` gives the
-system message Janas's own programs use. `janas_llm_chat_stats` says why a
-reply ended and how much of its prompt was already computed.
-`janas_llm_chat_keep` keeps a few conversations computed besides the current
-one, for a program that switches between them: the one that shares most of
-the next request is copied back instead of being read again.
+A program that keeps the conversation itself - an HTTP client does, and sends it whole every time - hands it over with `janas_llm_chat_load`: the messages with their roles, the last one the user's. Whatever the new conversation shares with the one already computed is not read again, so the same messages plus a new one cost only the new one. `janas_llm_chat_prompt` continues raw text, with no chat format around it, and `janas_llm_default_system` gives the system message Janas's own programs use. `janas_llm_chat_stats` says why a reply ended and how much of its prompt was already computed. `janas_llm_chat_keep` keeps a few conversations computed besides the current one, for a program that switches between them: the one that shares most of the next request is copied back instead of being read again.
### From FreeBASIC and BASIC MODERN
-[`include/janas/llm.bi`](include/janas/llm.bi) declares the same library for
-FreeBASIC, and so for **BASIC MODERN**, the dialect implemented by Prabanta —
-the platform Janas is meant to sit inside. The same conversation as above:
+[`include/janas/llm.bi`](include/janas/llm.bi) declares the same library for FreeBASIC, and so for **BASIC MODERN**, the dialect implemented by Prabanta — the platform Janas is meant to sit inside. The same conversation as above:
```basic
#include once "janas/llm.bi"
@@ -754,8 +381,7 @@ do
loop
```
-[`tools/chat.bas`](tools/chat.bas) is a whole chat in a hundred lines, sampling
-and counters included:
+[`tools/chat.bas`](tools/chat.bas) is a whole chat in a hundred lines, sampling and counters included:
```sh
fbc tools/chat.bas -i include -p bin/x86_64-linux -x janas-chat-fb
@@ -763,21 +389,11 @@ LD_LIBRARY_PATH=bin/x86_64-linux ./janas-chat-fb qwen3-next.jns
echo "Hello! Introduce yourself." | LD_LIBRARY_PATH=bin/x86_64-linux ./janas-chat-fb qwen3-next.jns
```
-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.
+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.
### 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`.
+[`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`.
```c
janas_mcp *files;
@@ -798,34 +414,16 @@ cc yours.c -Iinclude -Lbin/x86_64-linux -ljanas_llm -ljanas_mcp -o yours
## Janas as an MCP server
-`janas-mcp` offers the model running here to the clients of the Model
-Context Protocol - Claude Code, editors, other agents - as tools: `generate`
-asks it a question (a prompt, and optionally a system message, a longest
-answer and a temperature) and returns its answer, and `embed` returns the
-vector of a text when an embedding model is given with `--embedding-model`.
-The client starts it and speaks to it over its standard input and output;
-it is configured like any other stdio server:
+`janas-mcp` offers the model running here to the clients of the Model Context Protocol - Claude Code, editors, other agents - as tools: `generate` asks it a question (a prompt, and optionally a system message, a longest answer and a temperature) and returns its answer, and `embed` returns the vector of a text when an embedding model is given with `--embedding-model`. The client starts it and speaks to it over its standard input and output; it is configured like any other stdio server:
```json
{"mcpServers": {"janas": {"command": "/path/to/janas-mcp",
"args": ["/path/to/qwen3-4b.jns"]}}}
```
-It answers both eras of the protocol: a request that names revision
-2026-07-28 in its `_meta` is served statelessly, and a client that opens with
-`initialize` gets the handshake of the revision it asks for (2025-11-25,
-2025-06-18, 2025-03-26 or 2024-11-05). A ping is answered while a generation
-runs, and `notifications/cancelled` stops it. Every call starts a
-conversation of its own; the reasoning of a model that reasons is never
-returned, only the answer. `janas-mcp --help` lists the options (`--ctx`,
-`--temp`, `--max`, `--think`, `--timeout` and the memory ones).
-
-What has been run: a probe script speaking each era to it with Qwen3-0.6B
-and Qwen3-Embedding-0.6B, `janas-chat` with Qwen3-4B calling its two tools
-through `libjanas_mcp`, and Claude Code (2.1.282, revision 2026-07-28),
-which listed both tools and called them - a translation, a summary, an
-embedding - with Qwen3-4B and Qwen3-Embedding-0.6B behind them. To add it
-there: `claude mcp add janas -- /path/to/janas-mcp /path/to/model.jns`.
+It answers both eras of the protocol: a request that names revision 2026-07-28 in its `_meta` is served statelessly, and a client that opens with `initialize` gets the handshake of the revision it asks for (2025-11-25, 2025-06-18, 2025-03-26 or 2024-11-05). A ping is answered while a generation runs, and `notifications/cancelled` stops it. Every call starts a conversation of its own; the reasoning of a model that reasons is never returned, only the answer. `janas-mcp --help` lists the options (`--ctx`, `--temp`, `--max`, `--think`, `--timeout` and the memory ones).
+
+What has been run: a probe script speaking each era to it with Qwen3-0.6B and Qwen3-Embedding-0.6B, `janas-chat` with Qwen3-4B calling its two tools through `libjanas_mcp`, and Claude Code (2.1.282, revision 2026-07-28), which listed both tools and called them - a translation, a summary, an embedding - with Qwen3-4B and Qwen3-Embedding-0.6B behind them. To add it there: `claude mcp add janas -- /path/to/janas-mcp /path/to/model.jns`.
## Using it over HTTP
@@ -833,11 +431,7 @@ there: `claude mcp add janas -- /path/to/janas-mcp /path/to/model.jns`.
bin/x86_64-linux/janas-server qwen3-next.jns
```
-`janas-server` puts the model behind an HTTP API that follows
-[OpenAI's](https://github.com/openai/openai-openapi), on
-`http://127.0.0.1:8080/v1`, so that a client written for that API can use a
-model running on this machine. It takes the model options `janas-chat` takes
-(`--ctx`, `--cache`, `--reserve`, `--mtp`, `--draft`, `--mode`, `--no-gpu`) and these:
+`janas-server` puts the model behind an HTTP API that follows [OpenAI's](https://github.com/openai/openai-openapi), on `http://127.0.0.1:8080/v1`, so that a client written for that API can use a model running on this machine. It takes the model options `janas-chat` takes (`--ctx`, `--cache`, `--reserve`, `--mtp`, `--draft`, `--mode`, `--no-gpu`) and these:
| Option | |
|---|---|
@@ -883,157 +477,41 @@ curl http://127.0.0.1:8080/v1/chat/completions \
-d '{"messages": [{"role": "user", "content": "What is the capital of Sardinia?"}]}'
```
-A client that lets you set the address of an OpenAI-compatible API should
-need nothing else: the base URL is `http://127.0.0.1:8080/v1`, and the key
-whatever you gave `--api-key` (anything, if you gave none). It has been tried
-here with `curl`, its own test page, the `openai` Python SDK and Open WebUI
-0.11.4 (driven through its own API: streamed chat, titles, tags, follow-up
-suggestions, and a document indexed with Janas's embeddings and asked
-about), and by a user with AnythingLLM.
-
-**Models that reason, and the limits a client sets.** Qwen3 and its
-successors reason before they answer, unless told not to. OpenAI's
-`max_completion_tokens` (and `max_output_tokens` in the Responses API)
-counts the reasoning too, and Janas takes it so. The older `max_tokens` of
-a chat, which OpenAI does not take at all for the models that reason, is
-taken for the answer alone: a client that sends it means the answer, and
-counted with the reasoning a small limit was spent before a word of it was
-written (Open WebUI asks for a chat's title with 1000, and got none).
-
-**With Open WebUI**, start the server with `--think off`: the titles, tags
-and suggestions it asks for after every reply are then quick, and a model
-that reasons can still be asked to (`reasoning_effort`). Its built-in tools,
-when they are on, add about 5,000 tokens to every prompt; the server reads
-them once and keeps them computed, but the first reply of a conversation
-waits for them.
-
-**The conversation is the client's.** OpenAI's API keeps no state: every
-request carries the whole conversation. `janas-server` keeps the one it
-computed last, and reads again only what a request adds to it: a client that
-sends the same messages plus a new one pays for the new one alone, and
-`usage.prompt_tokens_details.cached_tokens` says how much was already
-computed. The replies it wrote are remembered with their reasoning, so the
-answer a client sends back - without the reasoning, as clients do - still
-counts as the same turn. A conversation that differs earlier is read again
-from where it differs, and from the start on models with a recurrent state
-(Qwen3-Next, Qwen3.5 and 3.6).
-
-**Reasoning** comes apart from the answer, in `reasoning_content`, whole or
-streamed. `"reasoning_effort": "none"` turns it off for a request, any other
-effort turns it on, and `"chat_template_kwargs": {"enable_thinking": false}`
-works too; `--think` decides for requests that say nothing.
-
-**Beyond OpenAI's fields**, which clients ignore: `top_k` and `min_p` in a
-request, and in every reply's `usage` a `janas` object with the context used
-and its size and the seconds spent reading the prompt and writing the reply.
-
-**Tools.** `tools`, `tool_choice` (`none`, `auto`, `required`, a function)
-and `parallel_tool_calls`, and the older `functions`. The tools are written
-into the system message the way the model's chat template writes them, and a
-call the model opens is held to a grammar of the functions and their
-parameters until it closes it, so its arguments are always a JSON object
-valid against the function's schema. The calls come back in `tool_calls`,
-whole in one delta of the stream, and the reply ends with
-`"finish_reason": "tool_calls"`; sent back with the tools' answers, they are
-found again among the replies the server remembers, so the next turn reads
-only the answers. Qwen models write calls in one of two ways, and the
-template says which: as JSON (Qwen3, Qwen3-Next) or as XML (Qwen3.5 and 3.6,
-Qwen3-Coder). **Both have been run here**: the JSON way on Qwen3-4B and
-Qwen3-0.6B, the XML way on Qwen3.6-35B-A3B (two calls at once, their answers
-sent back, 422 of 471 prompt tokens reused on the next turn) and on
-Qwen3-Coder-Next, which describes the tools in a way of its own (two calls
-at once with valid arguments, their answers used in the reply, 496 of 562
-prompt tokens reused).
-
-**MCP servers in the Responses API.** A tool of type `mcp` (`server_label`,
-`server_url`, `headers`, `authorization`, `allowed_tools`,
-`require_approval`) has the server reach that MCP server over HTTP or
-HTTPS, as OpenAI's does. The response begins with an `mcp_list_tools` item
-(once per conversation), the model sees the tools as
-`server_label__tool`, and a call it writes either becomes an
-`mcp_approval_request` that ends the response - `require_approval` is
-`always` by default, as at OpenAI - and runs when the next request answers
-it with an `mcp_approval_response`, or, where no approval is needed, runs at
-once as an `mcp_call` item with its output, and the model goes on in the
-same response (up to eight rounds). Streamed, the calls come as
-`response.mcp_call.*` events. `allowed_tools` and the approval filters take
-names or `{tool_names, read_only}`; `tool_choice` may name an MCP tool.
-Connectors and tunnels are not served. A request makes the server open
-connections to the address it names: `--no-mcp` turns that off for a
-server others can reach. Tried with Qwen3-4B against the test server of
-`tests/mcp_fake_server.c`: a call run at once, one approved on the next
-request, and the same streamed; and through the `openai` SDK against
-DeepWiki over HTTPS, as OpenAI's own examples do: its tool listed, called,
-and the model answering from what it returned.
-
-**JSON output.** `response_format` `json_object` or `json_schema` (and
-`text.format` in the Responses API): the answer is held to a grammar token by
-token, so it is valid JSON when the model ends it (not when `max_tokens` cuts
-it). A schema is held to its types, the properties of an object in the
-schema's order with the required ones always there and no others, array
-items and bounds up to 32, string lengths up to 64, `enum`, `const`,
-`anyOf`, `oneOf`, `$ref` within the schema and `nullable`; `pattern`,
-`format` and numeric bounds are not enforced. The reasoning, where there is
-one, stays free.
-
-**Log-probabilities.** `logprobs` and `top_logprobs` (up to 20) in chat,
-`logprobs` in completions, `top_logprobs` in responses. They are the
-model's own: where a grammar forced a token the model found unlikely, its
-log-probability says so.
-
-**More than one reply** with `n` (and `best_of` in completions, which keeps
-the best by mean log-probability); `presence_penalty`, `frequency_penalty`
-and `logit_bias` as OpenAI defines them. The replies of `n` are written one
-after the other on the same prompt.
-
-**Embeddings** come from a second, small model opened with
-`--embedding-model`, such as Qwen3-Embedding-0.6B: texts or token ids, one or
-many, `dimensions` to cut the vector shorter, floats or `base64`. Against
-llama.cpp on the same file the vectors of the same text agree to a cosine of
-0.98 to 0.996, and the similarities between texts come out alike.
-
-**Moderations** are asked of the chat model: at temperature 0 it answers
-OpenAI's thirteen categories with a JSON object held to a schema, and each
-score is the chance it gave `true` against `false` in that place. It is a
-general model following instructions, not a classifier trained for the task.
-
-**Kept on disk.** Stored completions, responses and conversations are
-written, one file each, to `~/.local/share/janas/server` (or `--store DIR`),
-and read back when the server starts again; the oldest go past a thousand of
-each. The directory and its files are readable by their owner alone, since
-they hold what the clients said, and one server at a time uses a directory.
-`--no-store` keeps them in memory only, until the server stops. A response
-running in the background when the server is killed is found as failed at
-the next start. Images and sound in messages are refused with a 400 that
-says so.
-
-**Every other operation of OpenAI's API** - there are 345 in the version it
-follows (2.3.0) - has a route that answers 501 and says why: not written
-yet, needs a model of another kind (sound, images, video), trains models, or
-belongs to the administration of OpenAI's service. The table is generated
-from the specification by `tools/openapi_routes`, which also counts what is
-done.
-
-**One request at a time.** The model holds one sequence, so requests wait in
-line and run in the order they came; when the line is full the answer is 429.
-While a streamed request waits, the stream says where it stands in the line
-(`: queue N`, a comment clients skip) and the test page shows it.
-A client that closes the connection while a reply streams stops the reply.
-
-**On the network.** It listens on this machine alone unless `--host` says
-otherwise, and then it warns if there is no key. There is no HTTPS yet: across
-a network you do not trust, put it behind something that adds it.
-
-**The test page.** With `--test`, `http://127.0.0.1:8080/test` is
-*Janas-Chat Web*: a chat in the browser that talks to the API like any client,
-with the reasoning in grey, a line under each reply with the context used and
-the speed (last, lowest, highest and mean of the conversation), and the
-settings - system message, temperature, reasoning, key - behind *Settings*.
-It reads the marks a model writes as `janas-chat` does, and also quotes,
-tables, struck text and links; a link asks before it opens, because links an
-AI writes can be wrong or unsafe. *Markdown sample* shows a text of ours with
-every mark it knows, without asking the model. The page is inside the
-program, loads nothing from anywhere else and may talk only to this server.
+A client that lets you set the address of an OpenAI-compatible API should need nothing else: the base URL is `http://127.0.0.1:8080/v1`, and the key whatever you gave `--api-key` (anything, if you gave none). It has been tried here with `curl`, its own test page, the `openai` Python SDK and Open WebUI 0.11.4 (driven through its own API: streamed chat, titles, tags, follow-up suggestions, and a document indexed with Janas's embeddings and asked about), and by a user with AnythingLLM.
+
+**Models that reason, and the limits a client sets.** Qwen3 and its successors reason before they answer, unless told not to. OpenAI's `max_completion_tokens` (and `max_output_tokens` in the Responses API) counts the reasoning too, and Janas takes it so. The older `max_tokens` of a chat, which OpenAI does not take at all for the models that reason, is taken for the answer alone: a client that sends it means the answer, and counted with the reasoning a small limit was spent before a word of it was written (Open WebUI asks for a chat's title with 1000, and got none).
+
+**With Open WebUI**, start the server with `--think off`: the titles, tags and suggestions it asks for after every reply are then quick, and a model that reasons can still be asked to (`reasoning_effort`). Its built-in tools, when they are on, add about 5,000 tokens to every prompt; the server reads them once and keeps them computed, but the first reply of a conversation waits for them.
+
+**The conversation is the client's.** OpenAI's API keeps no state: every request carries the whole conversation. `janas-server` keeps the one it computed last, and reads again only what a request adds to it: a client that sends the same messages plus a new one pays for the new one alone, and `usage.prompt_tokens_details.cached_tokens` says how much was already computed. The replies it wrote are remembered with their reasoning, so the answer a client sends back - without the reasoning, as clients do - still counts as the same turn. A conversation that differs earlier is read again from where it differs, and from the start on models with a recurrent state (Qwen3-Next, Qwen3.5 and 3.6).
+
+**Reasoning** comes apart from the answer, in `reasoning_content`, whole or streamed. `"reasoning_effort": "none"` turns it off for a request, any other effort turns it on, and `"chat_template_kwargs": {"enable_thinking": false}` works too; `--think` decides for requests that say nothing.
+
+**Beyond OpenAI's fields**, which clients ignore: `top_k` and `min_p` in a request, and in every reply's `usage` a `janas` object with the context used and its size and the seconds spent reading the prompt and writing the reply.
+
+**Tools.** `tools`, `tool_choice` (`none`, `auto`, `required`, a function) and `parallel_tool_calls`, and the older `functions`. The tools are written into the system message the way the model's chat template writes them, and a call the model opens is held to a grammar of the functions and their parameters until it closes it, so its arguments are always a JSON object valid against the function's schema. The calls come back in `tool_calls`, whole in one delta of the stream, and the reply ends with `"finish_reason": "tool_calls"`; sent back with the tools' answers, they are found again among the replies the server remembers, so the next turn reads only the answers. Qwen models write calls in one of two ways, and the template says which: as JSON (Qwen3, Qwen3-Next) or as XML (Qwen3.5 and 3.6, Qwen3-Coder). **Both have been run here**: the JSON way on Qwen3-4B and Qwen3-0.6B, the XML way on Qwen3.6-35B-A3B (two calls at once, their answers sent back, 422 of 471 prompt tokens reused on the next turn) and on Qwen3-Coder-Next, which describes the tools in a way of its own (two calls at once with valid arguments, their answers used in the reply, 496 of 562 prompt tokens reused).
+
+**MCP servers in the Responses API.** A tool of type `mcp` (`server_label`, `server_url`, `headers`, `authorization`, `allowed_tools`, `require_approval`) has the server reach that MCP server over HTTP or HTTPS, as OpenAI's does. The response begins with an `mcp_list_tools` item (once per conversation), the model sees the tools as `server_label__tool`, and a call it writes either becomes an `mcp_approval_request` that ends the response - `require_approval` is `always` by default, as at OpenAI - and runs when the next request answers it with an `mcp_approval_response`, or, where no approval is needed, runs at once as an `mcp_call` item with its output, and the model goes on in the same response (up to eight rounds). Streamed, the calls come as `response.mcp_call.*` events. `allowed_tools` and the approval filters take names or `{tool_names, read_only}`; `tool_choice` may name an MCP tool. Connectors and tunnels are not served. A request makes the server open connections to the address it names: `--no-mcp` turns that off for a server others can reach. Tried with Qwen3-4B against the test server of `tests/mcp_fake_server.c`: a call run at once, one approved on the next request, and the same streamed; and through the `openai` SDK against DeepWiki over HTTPS, as OpenAI's own examples do: its tool listed, called, and the model answering from what it returned.
+
+**JSON output.** `response_format` `json_object` or `json_schema` (and `text.format` in the Responses API): the answer is held to a grammar token by token, so it is valid JSON when the model ends it (not when `max_tokens` cuts it). A schema is held to its types, the properties of an object in the schema's order with the required ones always there and no others, array items and bounds up to 32, string lengths up to 64, `enum`, `const`, `anyOf`, `oneOf`, `$ref` within the schema and `nullable`; `pattern`, `format` and numeric bounds are not enforced. The reasoning, where there is one, stays free.
+
+**Log-probabilities.** `logprobs` and `top_logprobs` (up to 20) in chat, `logprobs` in completions, `top_logprobs` in responses. They are the model's own: where a grammar forced a token the model found unlikely, its log-probability says so.
+
+**More than one reply** with `n` (and `best_of` in completions, which keeps the best by mean log-probability); `presence_penalty`, `frequency_penalty` and `logit_bias` as OpenAI defines them. The replies of `n` are written one after the other on the same prompt.
+
+**Embeddings** come from a second, small model opened with `--embedding-model`, such as Qwen3-Embedding-0.6B: texts or token ids, one or many, `dimensions` to cut the vector shorter, floats or `base64`. Against llama.cpp on the same file the vectors of the same text agree to a cosine of 0.98 to 0.996, and the similarities between texts come out alike.
+
+**Moderations** are asked of the chat model: at temperature 0 it answers OpenAI's thirteen categories with a JSON object held to a schema, and each score is the chance it gave `true` against `false` in that place. It is a general model following instructions, not a classifier trained for the task.
+
+**Kept on disk.** Stored completions, responses and conversations are written, one file each, to `~/.local/share/janas/server` (or `--store DIR`), and read back when the server starts again; the oldest go past a thousand of each. The directory and its files are readable by their owner alone, since they hold what the clients said, and one server at a time uses a directory. `--no-store` keeps them in memory only, until the server stops. A response running in the background when the server is killed is found as failed at the next start. Images and sound in messages are refused with a 400 that says so.
+
+**Every other operation of OpenAI's API** - there are 345 in the version it follows (2.3.0) - has a route that answers 501 and says why: not written yet, needs a model of another kind (sound, images, video), trains models, or belongs to the administration of OpenAI's service. The table is generated from the specification by `tools/openapi_routes`, which also counts what is done.
+
+**One request at a time.** The model holds one sequence, so requests wait in line and run in the order they came; when the line is full the answer is 429. While a streamed request waits, the stream says where it stands in the line (`: queue N`, a comment clients skip) and the test page shows it. A client that closes the connection while a reply streams stops the reply.
+
+**On the network.** It listens on this machine alone unless `--host` says otherwise, and then it warns if there is no key. There is no HTTPS yet: across a network you do not trust, put it behind something that adds it.
+
+**The test page.** With `--test`, `http://127.0.0.1:8080/test` is *Janas-Chat Web*: a chat in the browser that talks to the API like any client, with the reasoning in grey, a line under each reply with the context used and the speed (last, lowest, highest and mean of the conversation), and the settings - system message, temperature, reasoning, key - behind *Settings*. It reads the marks a model writes as `janas-chat` does, and also quotes, tables, struck text and links; a link asks before it opens, because links an AI writes can be wrong or unsafe. *Markdown sample* shows a text of ours with every mark it knows, without asking the model. The page is inside the program, loads nothing from anywhere else and may talk only to this server.
## Measuring your machine
@@ -1041,16 +519,7 @@ program, loads nothing from anywhere else and may talk only to this server.
bin/x86_64-linux/janas-bench qwen3-next.jns
```
-Close what you can before running it: it measures the machine you give it, and
-a browser with thirty tabs is part of the machine. It tries the configurations
-the machine offers — how many threads, which cores,
-with and without the GPU — on real passes of the model, keeps the fastest,
-writes them into `~/.cache/janas` so the next start begins from them, and leaves
-a report in the current directory. On the development laptop that report says,
-among other things, that bringing the efficiency cores in makes decoding about
-a tenth faster than the performance cores alone - and that for blocks of
-several tokens, which is what a prompt and a draft check are, the engine often
-wants fewer threads than for one.
+Close what you can before running it: it measures the machine you give it, and a browser with thirty tabs is part of the machine. It tries the configurations the machine offers — how many threads, which cores, with and without the GPU — on real passes of the model, keeps the fastest, writes them into `~/.cache/janas` so the next start begins from them, and leaves a report in the current directory. On the development laptop that report says, among other things, that bringing the efficiency cores in makes decoding about a tenth faster than the performance cores alone - and that for blocks of several tokens, which is what a prompt and a draft check are, the engine often wants fewer threads than for one.
## Tools
@@ -1062,7 +531,7 @@ wants fewer threads than for one.
| `jns_check` | checks a model file, with `--verify` every expert's checksum |
| `tools/openapi_routes` | `janas-server`'s route table, from OpenAI's specification |
| `tools/gen_unicode` | the tokenizer's Unicode tables, from the Unicode Character Database |
-| `tools/gen_geo` | `janas-flights`' tables of airports, cities and seas, from OurAirports, GeoNames and Natural Earth |
+| `tools/gen_geo` | the services' tables of airports, cities and seas, from OurAirports, GeoNames and Natural Earth |
| `mcp_fake_server` | an MCP server over stdio in either era of the protocol, for trying a client without anybody else's server |
| `llm_eval` | compares the engine's logits against a reference dump |
| `bench_gemm`, `bench_attn`, `bench_long`, ... | the pieces measured on their own |
@@ -1071,140 +540,68 @@ They are built into `bin/x86_64-linux/` along with everything else.
## Helping it run on more hardware
-This is where help is worth most. The engine decides everything from what it
-measures, but it has only ever measured **one** machine, so the decisions are
-tuned to one shape of CPU, one disk and one GPU.
+This is where help is worth most. The engine decides everything from what it measures, but it has only ever measured **one** machine, so the decisions are tuned to one shape of CPU, one disk and one GPU.
-**The easy way: one command.** From a fresh clone, on Linux, with a C
-compiler and `curl` and nothing else:
+**The easy way: one command.** From a fresh clone, on Linux, with a C compiler and `curl` and nothing else:
```sh
git clone https://github.com/prabanta-dev/janas && cd janas
./tools/janas-try.sh
```
-It builds Janas and runs its tests, downloads a model from Hugging Face
-(checking its SHA-256), converts it (checking the result against the
-fingerprints of [MODELS.md](MODELS.md)), checks that the model's answer at
-temperature 0 is the very text every other machine gets, measures the speed
-with `janas-bench`, tries `janas-server`, and writes a report with no host
-name, user name or paths in it. It asks before every long step and shows
-the report before anything is sent. **Run it with the machine to itself**
-(close the browser, builds, other models): before measuring it checks how
-idle the CPU is and, if it is busy, offers to wait; the report says how idle
-it was, in general terms only (a load average and a percentage, never which
-programs ran). If you agree, it opens the issue with
-`gh`, or gives you a link to a filled
-[test report form](https://github.com/prabanta-dev/janas/issues/new?template=04-test-report.yml).
-Four levels: `quick` (Qwen3-4B, 2.5 GB to download), `medium`
-(Qwen3.6-35B-A3B, 22 GB), `full` (Qwen3-Next-80B-A3B with its MTP block,
-about 52 GB) and `gemma` (Gemma-4-E4B with its assistant, 5.1 GB, runs in
-about 3 GB of memory); it offers those your machine can hold, and deletes at the end
-only what it downloaded, if you say so. `--help` lists the options.
-
-**What to send, by hand.** Run the benchmark and attach the report it writes (a
-`janas-bench-<date>.txt` in the current directory):
+It builds Janas and runs its tests, downloads a model from Hugging Face (checking its SHA-256), converts it (checking the result against the fingerprints of [MODELS.md](MODELS.md)), checks that the model's answer at temperature 0 is the very text every other machine gets, measures the speed with `janas-bench`, tries `janas-server`, and writes a report with no host name, user name or paths in it. It asks before every long step and shows the report before anything is sent. **Run it with the machine to itself** (close the browser, builds, other models): before measuring it checks how idle the CPU is and, if it is busy, offers to wait; the report says how idle it was, in general terms only (a load average and a percentage, never which programs ran). If you agree, it opens the issue with `gh`, or gives you a link to a filled [test report form](https://github.com/prabanta-dev/janas/issues/new?template=04-test-report.yml). Four levels: `quick` (Qwen3-4B, 2.5 GB to download), `medium` (Qwen3.6-35B-A3B, 22 GB), `full` (Qwen3-Next-80B-A3B with its MTP block, about 52 GB) and `gemma` (Gemma-4-E4B with its assistant, 5.1 GB, runs in about 3 GB of memory); it offers those your machine can hold, and deletes at the end only what it downloaded, if you say so. `--help` lists the options.
+
+**What to send, by hand.** Run the benchmark and attach the report it writes (a `janas-bench-<date>.txt` in the current directory):
```sh
bin/x86_64-linux/janas-bench <model.jns>
```
-The report already carries the CPU's name, the core layout, the GPU if there is
-one, and the speed of every configuration tried. Add:
+The report already carries the CPU's name, the core layout, the GPU if there is one, and the speed of every configuration tried. Add:
- the **distribution** and kernel (`uname -a`), and the **RAM** (`free -g`);
- the **disk** the model sits on (NVMe? SATA? over USB?);
- the **model** you used and its file size;
-- what you saw: numbers that look wrong, a reply that made no sense, a crash, a
- machine that went unresponsive — with what you were doing at the time.
+- what you saw: numbers that look wrong, a reply that made no sense, a crash, a machine that went unresponsive — with what you were doing at the time.
-The [hardware report form](https://github.com/prabanta-dev/janas/issues/new?template=01-hardware-report.yml)
-asks for exactly that, in that order. There are two more forms, for
-[something that went wrong](https://github.com/prabanta-dev/janas/issues/new?template=02-something-went-wrong.yml)
-and for [a model that will not convert](https://github.com/prabanta-dev/janas/issues/new?template=03-a-model-will-not-work.yml).
+The [hardware report form](https://github.com/prabanta-dev/janas/issues/new?template=01-hardware-report.yml) asks for exactly that, in that order. There are two more forms, for [something that went wrong](https://github.com/prabanta-dev/janas/issues/new?template=02-something-went-wrong.yml) and for [a model that will not convert](https://github.com/prabanta-dev/janas/issues/new?template=03-a-model-will-not-work.yml).
**What is most wanted, in order.**
-1. **CPUs without AVX-VNNI**, and **AMD** — the arithmetic has a path for them
- and it is the least exercised of all.
-2. **Discrete GPUs** (NVIDIA, AMD, Intel Arc). The GPU support is correct,
- bit for bit, and it pays where it was measured: on the development
- laptop's integrated GPU a dense model whose weights all fit in memory
- reads a prompt about 29% faster (Qwen3-4B, 83 to 107 tokens/s), and on an
- RTX 5080 (issue #15) Qwen3-4B read 13% faster and, with the GPU on single
- tokens too, replied 11-16% faster. Every other card is unknown.
- **Careful:** a GPU driver reset takes the desktop with it. Start with
- `janas-bench`, not with a long chat.
-3. **Machines with 16 GB or less.** The engine is supposed to trade quality for
- memory on its own — fewer bits per weight, fewer experts per token — and the
- thresholds for that were measured on 32 GB.
-4. **Slower disks.** Everything assumes an NVMe SSD; on a SATA disk the engine
- should still work and simply wait more, but nobody has watched it do so.
-5. **Other models** of the supported families. A file that will not convert, or
- converts and then answers nonsense, is a useful bug.
-
-**What not to bother with yet:** Windows and macOS (not supported), and models
-outside the Qwen3 MoE families (they are refused with a message).
-
-Patches are welcome too, but a measurement from a machine nobody here can buy is
-worth more than most patches.
+1. **CPUs without AVX-VNNI**, and **AMD** — the arithmetic has a path for them and it is the least exercised of all.
+2. **Discrete GPUs** (NVIDIA, AMD, Intel Arc). The GPU support is correct, bit for bit, and it pays where it was measured: on the development laptop's integrated GPU a dense model whose weights all fit in memory reads a prompt about 29% faster (Qwen3-4B, 83 to 107 tokens/s), and on an RTX 5080 (issue #15) Qwen3-4B read 13% faster and, with the GPU on single tokens too, replied 11-16% faster. Every other card is unknown. **Careful:** a GPU driver reset takes the desktop with it. Start with `janas-bench`, not with a long chat.
+3. **Machines with 16 GB or less.** The engine is supposed to trade quality for memory on its own — fewer bits per weight, fewer experts per token — and the thresholds for that were measured on 32 GB.
+4. **Slower disks.** Everything assumes an NVMe SSD; on a SATA disk the engine should still work and simply wait more, but nobody has watched it do so.
+5. **Other models** of the supported families. A file that will not convert, or converts and then answers nonsense, is a useful bug.
+
+**What not to bother with yet:** Windows and macOS (not supported), and models outside the Qwen3 MoE families (they are refused with a message).
+
+Patches are welcome too, but a measurement from a machine nobody here can buy is worth more than most patches.
## Credits
-Janas is designed and written by **Maurizio "camauri" Cammalleri**
-([LinkedIn](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/),
-[Substack](https://cammalleri.substack.com/)).
+Janas is designed and written by **Maurizio "camauri" Cammalleri** ([LinkedIn](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/), [Substack](https://cammalleri.substack.com/)).
It stands on the work of others, and says so:
-- **The models** it runs are their authors': Qwen3, Qwen3.5, Qwen3.6 and
- Qwen3-Next by the Qwen team of Alibaba Cloud, Gemma 4 by Google; the GGUF
- quantizations by Qwen, bartowski and unsloth ([MODELS.md](MODELS.md) has
- every source).
-- **llama.cpp and ggml** are the reference the engine is checked against
- (logits, tokens, speed); none of their code is in Janas. The one thing
- taken from ggml is data that defines a format: the IQ3_S grid, in
- `src/llm/iq3s_grid.h`, under ggml's MIT licence.
-- **The Unicode Character Database** gives the tokenizer its tables
- (`tools/gen_unicode`), and **OpenAI's OpenAPI specification** gives
- `janas-server` its route table (`tools/openapi_routes`).
-- **GNU libmicrohttpd, yyjson and Mbed TLS** are compiled into the programs
- named below.
-- **`janas-flights`** reads the positions of aircraft from
- [adsb.lol](https://adsb.lol) (data under the Open Database License) and
- [adsb.fi](https://adsb.fi), routes from
- [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's,
- schedules from [AviationStack](https://aviationstack.com); its tables of places are built from
- [OurAirports](https://ourairports.com) (public domain),
- [GeoNames](https://www.geonames.org) (CC BY 4.0) and
- [Natural Earth](https://www.naturalearthdata.com) (public domain).
-- **The people who tried it on their own machines** and reported what they
- saw, in the issues of this repository: their reports changed the engine
- more than once (the threads it picks, the prompt's progress, the GPU's
- diagnosis).
+- **The models** it runs are their authors': Qwen3, Qwen3.5, Qwen3.6 and Qwen3-Next by the Qwen team of Alibaba Cloud, Gemma 4 by Google; the GGUF quantizations by Qwen, bartowski and unsloth ([MODELS.md](MODELS.md) has every source).
+- **llama.cpp and ggml** are the reference the engine is checked against (logits, tokens, speed); none of their code is in Janas. The one thing taken from ggml is data that defines a format: the IQ3_S grid, in `src/llm/iq3s_grid.h`, under ggml's MIT licence.
+- **The Unicode Character Database** gives the tokenizer its tables (`tools/gen_unicode`), and **OpenAI's OpenAPI specification** gives `janas-server` its route table (`tools/openapi_routes`).
+- **GNU libmicrohttpd, yyjson and Mbed TLS** are compiled into the programs named below.
+- **`janas-flights`** reads the positions of aircraft from [adsb.lol](https://adsb.lol) (data under the Open Database License) and [adsb.fi](https://adsb.fi), routes from [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's, schedules from [AviationStack](https://aviationstack.com); its tables of places are built from [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0) and [Natural Earth](https://www.naturalearthdata.com) (public domain).
+- **`janas-weather`** reads forecasts and the sea from [Open-Meteo](https://open-meteo.com) (CC BY 4.0) and [MET Norway](https://api.met.no) (CC BY 4.0), the stations' reports from [aviationweather.gov](https://aviationweather.gov) (NOAA), warnings from [MeteoAlarm](https://meteoalarm.org) (EUMETNET) and the Italian alert levels from the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica) (CC BY 4.0). With no place named, the services ask [GeoJS](https://www.geojs.io) or [ipwho.is](https://ipwho.is) where the internet connection is.
+- **The people who tried it on their own machines** and reported what they saw, in the issues of this repository: their reports changed the engine more than once (the threads it picks, the prompt's progress, the GPU's diagnosis).
## Licence
Copyright © 2026 Maurizio "camauri" Cammalleri.
-Janas is free software under the **GNU General Public License, version 3 or
-later** — see [LICENSE](LICENSE). Every source file carries its SPDX line.
+Janas is free software under the **GNU General Public License, version 3 or later** — see [LICENSE](LICENSE). Every source file carries its SPDX line.
-`janas-server`, and only it, has two libraries of others compiled in, their
-sources unchanged in [`src/third_party/`](src/third_party) with their
-licences and where they came from: **GNU libmicrohttpd** 1.0.10 (LGPL 2.1 or
-later, or the eCos licence without HTTPS, as it is built here) and **yyjson**
-0.13.0 (MIT). `libjanas_mcp`, and the programs with it, have **Mbed TLS**
-4.2.0 with TF-PSA-Crypto (Apache-2.0 or GPL-2.0-or-later), for `https://`
-MCP servers. `libjanas_llm` has none.
+`janas-server`, and only it, has two libraries of others compiled in, their sources unchanged in [`src/third_party/`](src/third_party) with their licences and where they came from: **GNU libmicrohttpd** 1.0.10 (LGPL 2.1 or later, or the eCos licence without HTTPS, as it is built here) and **yyjson** 0.13.0 (MIT). `libjanas_mcp`, and the programs with it, have **Mbed TLS** 4.2.0 with TF-PSA-Crypto (Apache-2.0 or GPL-2.0-or-later), for `https://` MCP servers. `libjanas_llm` has none.
-**The models are not covered by it.** A converted `.jns` file is a derivative of
-the model, not of Janas, and keeps the licence its authors gave it;
-[MODELS.md](MODELS.md) says what this project will and will not redistribute,
-and what to check before you pass a converted model on.
+**The models are not covered by it.** A converted `.jns` file is a derivative of the model, not of Janas, and keeps the licence its authors gave it; [MODELS.md](MODELS.md) says what this project will and will not redistribute, and what to check before you pass a converted model on.
## Contributing
-[CONTRIBUTING.md](CONTRIBUTING.md). The short version: a measurement from a
-machine nobody here owns is worth more than most patches, and every commit needs
-a `Signed-off-by` line (`git commit -s`).
+[CONTRIBUTING.md](CONTRIBUTING.md). The short version: a measurement from a machine nobody here owns is worth more than most patches, and every commit needs a `Signed-off-by` line (`git commit -s`).
diff --git a/build.sh b/build.sh
index 1830248..8258bc2 100755
--- a/build.sh
+++ b/build.sh
@@ -336,6 +336,9 @@ if [ "$VARIANT" = release ]; then
case "$o" in
*/common_mcp_*.o) mcp_objs+=("$o") ;;
*/common_hf_*.o) ;; # for the tools, with libjanas.a only
+ # the services': the geography's tables, the GET over HTTPS and
+ # where the user is
+ */common_geo.o | */common_https_get.o | */common_locate.o) ;;
*/llm_json.o) mcp_objs+=("$o") llm_objs+=("$o") ;;
*) llm_objs+=("$o") ;;
esac
diff --git a/docs/code-completion.md b/docs/code-completion.md
index af31ed3..42b4c10 100644
--- a/docs/code-completion.md
+++ b/docs/code-completion.md
@@ -1,25 +1,12 @@
# Code completion in the editor
-`janas-server` fills in code at the cursor of an editor, as the
-completion extensions of VS Code and VSCodium ask for it: the code before
-the cursor and the code after it go to the model, which writes what goes
-between. It runs on the processor, with a model for code; nothing leaves
-the machine.
+`janas-server` fills in code at the cursor of an editor, as the completion extensions of VS Code and VSCodium ask for it: the code before the cursor and the code after it go to the model, which writes what goes between. It runs on the processor, with a model for code; nothing leaves the machine.
## The model
-A model trained to fill in the middle is needed, with the
-`<|fim_prefix|>`, `<|fim_suffix|>` and `<|fim_middle|>` tokens of the Qwen
-coders. Every Qwen3-Coder is, says its
-[README](https://github.com/QwenLM/Qwen3-Coder). The one tried is
-**Qwen3-Coder-30B-A3B-Instruct**, Q4_K_M (unsloth's GGUF, converted with
-`gguf2jns`): 18.6 GB, a mixture of experts with 3 billion parameters
-active a token, which on a 32 GB machine fits in memory whole
-(`--cache 18`).
+A model trained to fill in the middle is needed, with the `<|fim_prefix|>`, `<|fim_suffix|>` and `<|fim_middle|>` tokens of the Qwen coders. Every Qwen3-Coder is, says its [README](https://github.com/QwenLM/Qwen3-Coder). The one tried is **Qwen3-Coder-30B-A3B-Instruct**, Q4_K_M (unsloth's GGUF, converted with `gguf2jns`): 18.6 GB, a mixture of experts with 3 billion parameters active a token, which on a 32 GB machine fits in memory whole (`--cache 18`).
-Qwen3-Coder-Next fills in too, but its recurrent layers cannot go back to
-a point of a sequence: every keystroke would read the window again from
-its start.
+Qwen3-Coder-Next fills in too, but its recurrent layers cannot go back to a point of a sequence: every keystroke would read the window again from its start.
## Starting the server
@@ -27,53 +14,28 @@ its start.
janas-server models/jns/qwen3-coder-30b-a3b-q4km.jns --cache 18
```
-It listens on `http://127.0.0.1:8080`. `--verbose` writes on stderr, for
-each request, where its window was cut and why.
+It listens on `http://127.0.0.1:8080`. `--verbose` writes on stderr, for each request, where its window was cut and why.
## The two routes
-- **`POST /v1/completions` with a `suffix`**, OpenAI's: the `prompt` is
- the code before the cursor, the `suffix` the code after it.
-- **`POST /infill`**, llama.cpp's, which the extensions made for
- llama.cpp's server ask: `input_prefix` (the lines before the cursor),
- `prompt` (the line up to it), `input_suffix` (what follows), and the
- answer as llama.cpp gives it (`content`, `timings`). It reads
- `n_predict` (0: the prompt only, read so that the next request finds it
- computed), `n_indent` (a new line indented less ends the text) and
- `t_max_predict_ms` (after a new line, past that time the text ends), as
- llama.cpp does. The code of other files (`input_extra`) is not used: it
- comes first, changes often, and every change would have the whole
- prompt read again. The most likely token is always taken, so the same
- place gives the same proposal.
+- **`POST /v1/completions` with a `suffix`**, OpenAI's: the `prompt` is the code before the cursor, the `suffix` the code after it.
+- **`POST /infill`**, llama.cpp's, which the extensions made for llama.cpp's server ask: `input_prefix` (the lines before the cursor), `prompt` (the line up to it), `input_suffix` (what follows), and the answer as llama.cpp gives it (`content`, `timings`). It reads `n_predict` (0: the prompt only, read so that the next request finds it computed), `n_indent` (a new line indented less ends the text) and `t_max_predict_ms` (after a new line, past that time the text ends), as llama.cpp does. The code of other files (`input_extra`) is not used: it comes first, changes often, and every change would have the whole prompt read again. The most likely token is always taken, so the same place gives the same proposal.
## The window
-An editor asks at every keystroke. The server keeps computed what the
-previous request shares from its start, so what matters is that the
-start of the text sent does not move; and the extensions move it, sending
-"the last N lines before the cursor". So, for requests that fill in:
-
-- the code before the cursor is read up to `--fim-prefix` tokens (2048);
- over that it is cut at a line to three quarters of it, which leaves
- room for many lines before the next cut;
-- the start of each window is remembered, for a few files, and a later
- request holding it is cut there;
-- a request whose text starts inside the head of a window before, past
- its start, comes from an editor that slides its window: its start is put
- a quarter of the way in, so that the lines it slides next keep it in;
-- the code after the cursor, read again at every request, is cut after
- `--fim-suffix` lines (8);
-- the text written is at most `--fim-max` tokens (256), whatever the
- request asks: the extensions ask for thousands, and the requests of the
- next keystrokes would wait for them.
-
-Each cut costs one reading of the whole window; the keystrokes after it
-read only what they changed and the lines after the cursor.
+An editor asks at every keystroke. The server keeps computed what the previous request shares from its start, so what matters is that the start of the text sent does not move; and the extensions move it, sending "the last N lines before the cursor". So, for requests that fill in:
+
+- the code before the cursor is read up to `--fim-prefix` tokens (2048); over that it is cut at a line to three quarters of it, which leaves room for many lines before the next cut;
+- the start of each window is remembered, for a few files, and a later request holding it is cut there;
+- a request whose text starts inside the head of a window before, past its start, comes from an editor that slides its window: its start is put a quarter of the way in, so that the lines it slides next keep it in;
+- the code after the cursor, read again at every request, is cut after `--fim-suffix` lines (8);
+- the text written is at most `--fim-max` tokens (256), whatever the request asks: the extensions ask for thousands, and the requests of the next keystrokes would wait for them.
+
+Each cut costs one reading of the whole window; the keystrokes after it read only what they changed and the lines after the cursor.
## In VSCodium (and VS Code): llama.vscode
-[llama.vscode](https://github.com/ggml-org/llama.vscode), by the authors of
-llama.cpp, is on Open VSX, where VSCodium finds it. In the settings:
+[llama.vscode](https://github.com/ggml-org/llama.vscode), by the authors of llama.cpp, is on Open VSX, where VSCodium finds it. In the settings:
```json
{
@@ -86,24 +48,13 @@ llama.cpp, is on Open VSX, where VSCodium finds it. In the settings:
}
```
-One proposal is written (`max_parallel_completions`), the chunks of other
-files would not be used (`ring_n_chunks`), and the editor's own list of
-suggestions is kept from opening by itself: while it is open, a proposal
-that does not extend its selected entry is not shown. Its welcome page
-offers to install llama.cpp: it is not needed.
+One proposal is written (`max_parallel_completions`), the chunks of other files would not be used (`ring_n_chunks`), and the editor's own list of suggestions is kept from opening by itself: while it is open, a proposal that does not extend its selected entry is not shown. Its welcome page offers to install llama.cpp: it is not needed.
-Tab takes the proposal, Shift+Tab its first line, Ctrl+Right its first
-word; Ctrl+L asks for one.
+Tab takes the proposal, Shift+Tab its first line, Ctrl+Right its first word; Ctrl+L asks for one.
## Continue
-[Continue](https://www.continue.dev) works too, with three things to know:
-the provider must be one that sends the suffix (`siliconflow`, whose
-requests go to `{apiBase}completions` with `prompt` and `suffix`: the
-`openai` provider builds the prompt itself and sends it as raw text), its
-default `modelTimeout` of 150 ms cuts a proposal after ten pieces, and the
-snippets of other files it puts in front of the prefix change at every
-request. In `~/.continue/config.yaml`:
+[Continue](https://www.continue.dev) works too, with three things to know: the provider must be one that sends the suffix (`siliconflow`, whose requests go to `{apiBase}completions` with `prompt` and `suffix`: the `openai` provider builds the prompt itself and sends it as raw text), its default `modelTimeout` of 150 ms cuts a proposal after ten pieces, and the snippets of other files it puts in front of the prefix change at every request. In `~/.continue/config.yaml`:
```yaml
name: Janas
@@ -133,20 +84,13 @@ models:
experimental_includeDiff: false
```
-With Continue some proposals the server wrote were not shown, and the
-editor was not seen to ask again after some keystrokes; why was not found
-(Continue filters, caches and reuses proposals before showing them).
-llama.vscode's behaviour was easier to follow.
+With Continue some proposals the server wrote were not shown, and the editor was not seen to ask again after some keystrokes; why was not found (Continue filters, caches and reuses proposals before showing them). llama.vscode's behaviour was easier to follow.
## What has been run
-1 October 2026, Qwen3-Coder-30B-A3B-Instruct Q4_K_M on an Intel Core
-Ultra 9 185H with every expert in memory (`--cache 18`), VSCodium 1.135
-with llama.vscode 0.0.67 and Continue 2.0.0.
+1 October 2026, Qwen3-Coder-30B-A3B-Instruct Q4_K_M on an Intel Core Ultra 9 185H with every expert in memory (`--cache 18`), VSCodium 1.135 with llama.vscode 0.0.67 and Continue 2.0.0.
-The window, with requests as an editor makes them on the 1,445 lines of
-`src/chat/main.c`, the cursor going down a line a request, time to the
-first token:
+The window, with requests as an editor makes them on the 1,445 lines of `src/chat/main.c`, the cursor going down a line a request, time to the first token:
| Requests | first request | the ones after |
|---|---|---|
@@ -155,24 +99,11 @@ first token:
| now: the 200 lines before the cursor, slid a line (cut to 1,527 tokens) | 19 s | 1.5-2.2 s |
| now: the file from its start to the cursor (cut to 1,566 tokens) | 20 s | 1.6-1.8 s |
-In VSCodium with llama.vscode, writing in `src/flights/schedule.c`: after
-the first request of a window, each request found 680-800 of its 750-870
-tokens computed and was answered in one to two seconds (about 90 tokens
-read, the lines after the cursor and what had changed, and 2-30
-written).
+In VSCodium with llama.vscode, writing in `src/flights/schedule.c`: after the first request of a window, each request found 680-800 of its 750-870 tokens computed and was answered in one to two seconds (about 90 tokens read, the lines after the cursor and what had changed, and 2-30 written).
What it proposed:
-- under the comment "how many answers are kept and still fresh", the body
- of a new function counting the answers kept, with the names of the file
- (`kept[]`, `N_KEPT`); with `time_t now = time(NULL);` written first, it
- added the test on their age (`now - kept[i].at < KEEP_S`) by itself;
-- for a line taken out of `local_time` (`tm.tm_mon -= 1;`), the right line
- first (`tm.tm_mon--;`), and then lines of its own: a handling of time
- zones the file does not have. With 8, 16, 32 or 64 lines after the
- cursor given to it the first line was always right and the rest always
- invented: the model does not see that only one line was missing.
- Shift+Tab takes the first line only.
-
-The first request of a new window reads all of it, at 65-80 tokens a
-second: 10-20 s for the 750-1,500 tokens of a window.
+- under the comment "how many answers are kept and still fresh", the body of a new function counting the answers kept, with the names of the file (`kept[]`, `N_KEPT`); with `time_t now = time(NULL);` written first, it added the test on their age (`now - kept[i].at < KEEP_S`) by itself;
+- for a line taken out of `local_time` (`tm.tm_mon -= 1;`), the right line first (`tm.tm_mon--;`), and then lines of its own: a handling of time zones the file does not have. With 8, 16, 32 or 64 lines after the cursor given to it the first line was always right and the rest always invented: the model does not see that only one line was missing. Shift+Tab takes the first line only.
+
+The first request of a new window reads all of it, at 65-80 tokens a second: 10-20 s for the 750-1,500 tokens of a window.
diff --git a/docs/services/README.md b/docs/services/README.md
index a657b1a..a201801 100644
--- a/docs/services/README.md
+++ b/docs/services/README.md
@@ -1,58 +1,37 @@
# Janas's services
-A service of Janas is a program that brings data of the world - flights,
-for now - to a model, as tools of the
-[Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is
-an MCP server of its own, over its standard input and output, so that any
-MCP client can use it: `janas-chat`, and the assistants of others.
+A service of Janas is a program that brings data of the world - flights, the weather - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
| Service | What it answers | Key |
|---|---|---|
| [`janas-flights`](flights.md) | where a flight is and what it is doing, its times, the flights of a route, what flies over a sea or near a place | none for live data; a free one of your own for schedules |
+| [`janas-weather`](weather.md) | the weather now (a model's and a station's), the forecast, the sea and its waves, the warnings in force | none |
What every service does the same way:
-- **Facts already worked out.** The answers are text for the model, with
- places, distances and times already computed and put into words, so that
- the model telling them has nothing to compute; what is not known is said
- to be not known.
-- **Open data first.** Questions about an area or a list are answered from
- open sources only; a source with a small quota (a key of yours) is kept
- for questions about one thing.
-- **It says when to use it.** A service tells the client's model when its
- tools apply: a question on the subject is enough, the tools need not be
- named, and the model is told not to name them in its answers.
-- **Keys stay put.** A key is read from the service's file under
- `~/.config/janas/` or from a variable of its environment, and never
- printed, not even in an error.
+- **Facts already worked out.** The answers are text for the model, with places, distances and times already computed and put into words, so that the model telling them has nothing to compute; what is not known is said to be not known.
+- **Open data first.** Questions about an area or a list are answered from open sources only; a source with a small quota (a key of yours) is kept for questions about one thing.
+- **It says when to use it.** A service tells the client's model when its tools apply: a question on the subject is enough, the tools need not be named, and the model is told not to name them in its answers.
+- **Keys stay put.** A key is read from the service's file under `~/.config/janas/` or from a variable of its environment, and never printed, not even in an error.
+- **Here, when no place is named.** A question about "here" takes where the user is: `JANAS_LOCATION` when set (a city, `lat,lon`, or `off`), else the internet connection's position (GeoJS, ipwho.is), else the city of the computer's time zone; the answer says which, so the model can say it is a guess ([details](weather.md#when-no-place-is-named)).
## In janas-chat
-`janas-chat` starts by itself the services it finds beside it (in the same
-directory as the program), gives their tools to the model with what each
-says of when to use them, and runs their calls without asking: they read
-public data and change nothing. A call shows as a dimmed line. Nothing to
-configure, nothing to name: ask your question.
+`janas-chat` starts by itself the services it finds beside it (in the same directory as the program), gives their tools to the model with what each says of when to use them, and runs their calls without asking: they read public data and change nothing. A call shows as a dimmed line. Nothing to configure, nothing to name: ask your question.
- `/mcp` lists the servers running, the services marked as Janas's.
- `--no-services` starts none of them; `--no-mcp` no server at all.
-- A server of the same name in `~/.config/janas/mcp.json` takes the place
- of the service (to give it options, say).
+- A server of the same name in `~/.config/janas/mcp.json` takes the place of the service (to give it options, say).
## In other clients
-A service is configured like any other stdio MCP server. In
-[Claude Code](https://code.claude.com/docs/en/mcp):
+A service is configured like any other stdio MCP server. In [Claude Code](https://code.claude.com/docs/en/mcp):
```sh
claude mcp add flights -- /path/to/janas-flights
```
-`--scope user` makes it available in every project, `-e NAME=value` gives
-it a variable (a key), and `claude mcp list` shows whether it started. In
-the clients that read an `mcpServers` file - Claude Desktop's
-`claude_desktop_config.json`, Cursor's `mcp.json`, `janas-chat`'s own
-`~/.config/janas/mcp.json`:
+`--scope user` makes it available in every project, `-e NAME=value` gives it a variable (a key), and `claude mcp list` shows whether it started. In the clients that read an `mcpServers` file - Claude Desktop's `claude_desktop_config.json`, Cursor's `mcp.json`, `janas-chat`'s own `~/.config/janas/mcp.json`:
```json
{"mcpServers": {"flights": {
diff --git a/docs/services/flights.md b/docs/services/flights.md
index 7fe91fe..1012e8b 100644
--- a/docs/services/flights.md
+++ b/docs/services/flights.md
@@ -1,33 +1,15 @@
# janas-flights
-Where a flight is and what it is doing, its scheduled and actual times,
-the flights of a route, what flies over a sea or near a place - for
-`janas-chat` or any other MCP client (see [the services](README.md)). The
-live data needs no key and no account; the schedules need a free key of
-your own.
+Where a flight is and what it is doing, its scheduled and actual times, the flights of a route, what flies over a sea or near a place - for `janas-chat` or any other MCP client (see [the services](README.md)). The live data needs no key and no account; the schedules need a free key of your own.
## The tools
-- **`flight_status`** - a flight by its number (`VY1595`, `AZ1631`) or its
- callsign (`VLG1595`). With a key: scheduled, estimated and actual
- departure and arrival, in each airport's local time and in UTC, delay,
- terminal, gate and baggage belt. On the ground: parked, taxiing or on the
- runway, and at which airport. In the air: altitude, speed, climbing or
- descending, where it is in words ("over the Tyrrhenian Sea, between
- Sicily, Italy and Campania, Italy; 86 km NNE of Palermo"), its route, and
- an arrival time estimated from its speed, next to the airline's.
-- **`flights_between`** - the flights from one airport to another, today's
- and the latest ones, each with its times and, if in the air, where it is
- now. Needs the key.
-- **`flights_over`** - how many and which aircraft fly now over a sea, by
- its name in English or Italian ("Tyrrhenian Sea", "Tirreno", "mar
- Ligure"), one line each: callsign, aircraft, altitude, speed, heading,
- where, and its route when one on record fits its position.
-- **`flights_nearby`** - what flies now near an airport (`TRN`, `LICT`,
- "Birgi"), a city ("Turin") or a point, nearest first.
-
-Airports are found by IATA or ICAO code, by city, or by the names people use
-("Trapani-Birgi", "Birgi", "Fiumicino").
+- **`flight_status`** - a flight by its number (`VY1595`, `AZ1631`) or its callsign (`VLG1595`). With a key: scheduled, estimated and actual departure and arrival, in each airport's local time and in UTC, delay, terminal, gate and baggage belt. On the ground: parked, taxiing or on the runway, and at which airport. In the air: altitude, speed, climbing or descending, where it is in words ("over the Tyrrhenian Sea, between Sicily, Italy and Campania, Italy; 86 km NNE of Palermo"), its route, and an arrival time estimated from its speed, next to the airline's.
+- **`flights_between`** - the flights from one airport to another, today's and the latest ones, each with its times and, if in the air, where it is now. Needs the key.
+- **`flights_over`** - how many and which aircraft fly now over a sea, by its name in English or Italian ("Tyrrhenian Sea", "Tirreno", "mar Ligure"), one line each: callsign, aircraft, altitude, speed, heading, where, and its route when one on record fits its position.
+- **`flights_nearby`** - what flies now near an airport (`TRN`, `LICT`, "Birgi"), a city ("Turin") or a point, nearest first; with none of them, near where the user is (`JANAS_LOCATION`, or the internet connection's position: [as for the weather](weather.md#when-no-place-is-named)).
+
+Airports are found by IATA or ICAO code, by city, or by the names people use ("Trapani-Birgi", "Birgi", "Fiumicino").
## Where the data comes from
@@ -38,44 +20,26 @@ Airports are found by IATA or ICAO code, by city, or by the names people use
| schedules and times | [AviationStack](https://aviationstack.com) | yours, free: 100 calls a month |
| airports, cities, seas | [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0), [Natural Earth](https://www.naturalearthdata.com) (public domain), built into the program by `tools/gen_geo` | - |
-The lists - over a sea, near a place - use open data only; AviationStack is
-asked only about one flight (`flight_status`) or one route
-(`flights_between`), and the service tells the model not to call those for
-each aircraft of a list.
+The lists - over a sea, near a place - use open data only; AviationStack is asked only about one flight (`flight_status`) or one route (`flights_between`), and the service tells the model not to call those for each aircraft of a list.
-The routes on record at adsbdb are often wrong for airlines that reuse
-their callsigns (Ryanair, Wizz Air): a route that does not fit the
-aircraft's position is reported as probably wrong, or left out of a list.
+The routes on record at adsbdb are often wrong for airlines that reuse their callsigns (Ryanair, Wizz Air): a route that does not fit the aircraft's position is reported as probably wrong, or left out of a list.
## The key
-Register at [aviationstack.com](https://aviationstack.com) for the free
-plan: 100 calls a month, today's flights only. Every question about a
-flight number or a route is one call; the answers are kept for ten
-minutes. Put the key in `~/.config/janas/flights.conf`:
+Register at [aviationstack.com](https://aviationstack.com) for the free plan: 100 calls a month, today's flights only. Every question about a flight number or a route is one call; the answers are kept for ten minutes. Put the key in `~/.config/janas/flights.conf`:
```
aviationstack_key = YOUR_KEY
```
-or in another file named by `--config FILE` or `JANAS_FLIGHTS_CONFIG`, or
-in the variable `JANAS_AVIATIONSTACK_KEY` (which wins). Without a key the
-service runs on open data only; `flight_status` then tells where a flight
-is, not its times.
+or in another file named by `--config FILE` or `JANAS_FLIGHTS_CONFIG`, or in the variable `JANAS_AVIATIONSTACK_KEY` (which wins). Without a key the service runs on open data only; `flight_status` then tells where a flight is, not its times.
## What it does with AviationStack's answers
-- The times come in each airport's local time though marked `+00:00`: they
- are read in the airport's zone.
-- AviationStack's status of a flight lags (a flight still "active" an hour
- after landing, another "active" an hour before leaving): the state
- reported comes from the actual times.
-- An aircraft flies several flights a day: a live position is given to a
- flight only when the aircraft with its transponder is on its route and
- heading for its destination, or on the ground at the right airport.
-- A question about a number brings its codeshares too (AZ1731 and Volotea's
- V76064, the same flight): the number asked is the one answered, and in a
- list the others show as "also sold as".
+- The times come in each airport's local time though marked `+00:00`: they are read in the airport's zone.
+- AviationStack's status of a flight lags (a flight still "active" an hour after landing, another "active" an hour before leaving): the state reported comes from the actual times.
+- An aircraft flies several flights a day: a live position is given to a flight only when the aircraft with its transponder is on its route and heading for its destination, or on the ground at the right airport.
+- A question about a number brings its codeshares too (AZ1731 and Volotea's V76064, the same flight): the number asked is the one answered, and in a list the others show as "also sold as".
## Running it
@@ -83,9 +47,7 @@ is, not its times.
janas-flights [--config FILE]
```
-It speaks MCP over its standard input and output (both eras of the
-protocol, as `janas-mcp`) and writes what it does on its standard error.
-In other clients:
+It speaks MCP over its standard input and output (both eras of the protocol, as `janas-mcp`) and writes what it does on its standard error. In other clients:
```sh
claude mcp add flights -- /path/to/janas-flights
@@ -100,19 +62,7 @@ claude mcp add flights -e JANAS_AVIATIONSTACK_KEY=YOUR_KEY -- /path/to/janas-fli
1 October 2026:
-- Over the protocol, with a key: ITA Airways' AZ1709 from Fiumicino to
- Catania, departed at 08:19 with 19 minutes of delay, seen over the
- Tyrrhenian Sea with the airline's estimate (09:11) and the one from its
- speed (09:08); the 21 flights from Fiumicino to Catania; Turin-Trapani,
- whose last flight on record was the evening before.
-- Without a key: `flights_over` the Tyrrhenian Sea at 09:07 found 45
- aircraft in the air, from a business jet north of Bastia to a Ryanair
- descending towards Calabria.
-- `janas-chat` with Qwen3-Next-80B-A3B asked in Italian where Vueling's
- VY1595 from Cairo to Barcelona was and what flew near Fiumicino: it called
- `flight_status` and `flights_nearby` by itself and told what they
- returned (configured by hand, before the chat started the services by
- itself).
-- `janas-chat` finding and starting the service beside it, with its tools
- and instructions, checked without a model. In Claude Code and the other
- clients it has not been run yet.
+- Over the protocol, with a key: ITA Airways' AZ1709 from Fiumicino to Catania, departed at 08:19 with 19 minutes of delay, seen over the Tyrrhenian Sea with the airline's estimate (09:11) and the one from its speed (09:08); the 21 flights from Fiumicino to Catania; Turin-Trapani, whose last flight on record was the evening before.
+- Without a key: `flights_over` the Tyrrhenian Sea at 09:07 found 45 aircraft in the air, from a business jet north of Bastia to a Ryanair descending towards Calabria.
+- `janas-chat` with Qwen3-Next-80B-A3B asked in Italian where Vueling's VY1595 from Cairo to Barcelona was and what flew near Fiumicino: it called `flight_status` and `flights_nearby` by itself and told what they returned (configured by hand, before the chat started the services by itself).
+- `janas-chat` finding and starting the service beside it, with its tools and instructions, checked without a model. In Claude Code and the other clients it has not been run yet.
diff --git a/docs/services/weather.md b/docs/services/weather.md
new file mode 100644
index 0000000..a33d2ce
--- /dev/null
+++ b/docs/services/weather.md
@@ -0,0 +1,69 @@
+# janas-weather
+
+The weather now and in the next days, the sea and its waves, and the weather warnings in force - for `janas-chat` or any other MCP client (see [the services](README.md)). Free sources only: no key, no account.
+
+## The tools
+
+- **`weather_now`** - the weather now at a place: sky, temperature and how it feels, humidity, wind and gusts (with their name on the Beaufort scale), rain, pressure, today's lowest and highest, sunrise and sunset, from a forecast model; and next to it what the nearest weather station (an airport's, within 40 km) measured, with when and how far away. When the model and the station disagree - by 3 °C or more, or on rain - the answer says so, and says which is the measure.
+- **`weather_forecast`** - day by day up to 16 days (sky, lowest and highest, rain and its chance, wind and gusts, UV index, sunrise and sunset), and the next 24 hours every three hours, or the next 48 every hour.
+- **`weather_sea`** - the state of the sea, now and up to 8 days ahead: waves with their name on the Douglas scale (calm, smooth, slight, moderate, rough...), wind waves and swell, the water's temperature and the wind. For a whole sea by its name in English or Italian ("Tyrrhenian Sea", "Tirreno", "Adriatico", "mar Ligure"), at up to nine points across it with a summary on top, or for the sea off a coastal place.
+- **`weather_alerts`** - the warnings in force for a place, from the national weather services gathered by MeteoAlarm (wind, thunderstorms, heat, snow; yellow, orange, red), the place's region first and the expired and green ones left out; and in Italy the Civil Protection's official levels for the zone of alert the place is in, for floods, landslides and thunderstorms, today and tomorrow.
+
+A place is a name in Italian or English ("Trapani", "Firenze", "Florence"), with its region or country when several share it ("Trapani, Sicilia"), an airport's code (`TRN`, `LICT`), or a latitude and longitude. A point is put into words (the town it is in or near, or the sea it is over: "the Tyrrhenian Sea, between Lazio, Italy and Sicily, Italy; 191 km SSW of Anzio"). Times are given in the place's local time.
+
+## When no place is named
+
+"What's the weather like?" names no place: the service then takes where the user is, and says how it knows it, so that the model can tell the user which place that is and that it may be off. In this order:
+
+1. **`JANAS_LOCATION`**, when set in the environment: a city of the built-in tables by its English name (`Trapani`), or `lat,lon` (`38.02,12.51`); `off` for no guess at all - the model is then told to ask.
+2. **The internet connection's position**, from [GeoJS](https://www.geojs.io), or [ipwho.is](https://ipwho.is) when it does not answer: free and with no key, but the address seen is the connection's, so the town can be the provider's rather than yours (a town nearby, more often than not). Asked once an hour at most.
+3. **The city of the computer's time zone** (`Europe/Rome`: Rome), a rough guess, when neither answers.
+
+The same applies to `janas-flights`' `flights_nearby`; the code is shared (`src/common/locate.c`), for the services to come. `janas-chat` passes its environment to the services it starts, so `JANAS_LOCATION` set for the chat reaches them.
+
+## Where the data comes from
+
+| Data | Source | Key |
+|---|---|---|
+| forecasts, the weather now, places by name | [Open-Meteo](https://open-meteo.com) (CC BY 4.0; free for non-commercial use) | none |
+| the same, when Open-Meteo does not answer | [MET Norway](https://api.met.no) (CC BY 4.0) | none |
+| the sea | Open-Meteo's marine models | none |
+| what a station measured | the airports' METAR, from [aviationweather.gov](https://aviationweather.gov) (NOAA) | none |
+| warnings | [MeteoAlarm](https://meteoalarm.org) (EUMETNET) | none |
+| Italy's alert levels | the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica)'s bulletin (CC BY 4.0) | none |
+| where the user is | [GeoJS](https://www.geojs.io), [ipwho.is](https://ipwho.is) | none |
+| airports, cities, seas | the tables `janas-flights` uses: OurAirports, GeoNames, Natural Earth | - |
+
+A forecast is a model's value and a station's report a measure: the answers say which is which, and where the model's cell lies. The answers are kept for a few minutes (forecasts and warnings 15, a station's report 10, the Civil Protection's bulletin an hour), so a conversation that comes back to a place does not ask again.
+
+What the service does with its sources:
+
+- **MeteoAlarm's Italian warnings** are the Air Force weather service's, about the phenomena; the official alerts are the Civil Protection's: the answer gives both and says so.
+- **The Civil Protection's bulletin** comes out around 16:00 for today and tomorrow: until then, yesterday's "tomorrow" is today's. The zone of alert is found by the municipality's name, or, when the bulletin does not name it (an airport, a point), by the point in the zones' outlines.
+- **Names in the country's language.** MeteoAlarm and the Civil Protection write regions and municipalities in Italian (Piemonte, Torino); a place found in the built-in tables, in English, takes its names from Open-Meteo's geocoding.
+- **MET Norway** asks for a User-Agent naming the program: requests carry `janas-weather/<version> https://github.com/prabanta-dev/janas`.
+
+## Running it
+
+```sh
+janas-weather
+```
+
+It speaks MCP over its standard input and output (both eras of the protocol, as `janas-mcp`) and writes what it does on its standard error. In other clients:
+
+```sh
+claude mcp add weather -- /path/to/janas-weather
+claude mcp add weather -e JANAS_LOCATION=Trapani -- /path/to/janas-weather
+```
+
+```json
+{"mcpServers": {"weather": {"command": "/path/to/janas-weather"}}}
+```
+
+## What has been run
+
+1 October 2026:
+
+- Over the protocol, every tool, in the release and AddressSanitizer builds: the weather now in Trapani, with the station of Trapani-Birgi 13 km away; the forecast for Florence hour by hour and for Bolzano for three days; the Tyrrhenian Sea at nine points and the sea off Trapani; the warnings for Trapani (none from MeteoAlarm, the Civil Protection's levels for its zone), for a point in Turin and in Florence (found in Piemonte and Toscana, and in their zones of alert by the point), for the airport `LICT`, and for Oslo (three gale warnings elsewhere in Norway, given in Oslo's time though the feed is in UTC); the weather with no place, placed in Palermo by GeoJS. Once, Open-Meteo did not answer and MET Norway did.
+- `janas-chat` with Qwen3.6-35B-A3B, asked in Italian about the weather in Trapani, the Tyrrhenian Sea today and tomorrow, warnings in Genoa, the next three days in Bolzano, and "Che tempo fa?": it called the tools by itself and told what they returned, the last answer as "where you are estimated to be from the internet connection".
+- `janas-chat` starting the service beside it. In Claude Code and the other clients it has not been run yet.
diff --git a/src/chat/main.c b/src/chat/main.c
index 35be8b6..ca5f591 100644
--- a/src/chat/main.c
+++ b/src/chat/main.c
@@ -930,6 +930,45 @@ static char *call_part(const janas_llm_chat *c, int32_t i, int args)
* not, in auto mode or for a tool always allowed), run, and what the tools
* answered sent back to the model. 1 when a new reply follows.
*/
+/* The calls that failed in this exchange, as "name args": one asked for
+ again is not run (it would fail the same way), and at the second time
+ the exchange stops. A model at temperature 0 can otherwise ask for it
+ until the rounds run out, without ever answering. */
+#define FAILED_MAX 16
+static struct {
+ char *call[FAILED_MAX];
+ int n, again;
+} failed;
+
+static void failed_clear(void)
+{
+ for (int i = 0; i < failed.n; i++)
+ free(failed.call[i]);
+ failed.n = failed.again = 0;
+}
+
+static char *call_key(const char *name, const char *args)
+{
+ size_t a = strlen(name), b = strlen(args);
+ char *k = malloc(a + b + 2);
+ if (k) {
+ memcpy(k, name, a);
+ k[a] = ' ';
+ memcpy(k + a + 1, args, b + 1);
+ }
+ return k;
+}
+
+static int failed_before(const char *key)
+{
+ for (int i = 0; key && i < failed.n; i++)
+ if (strcmp(failed.call[i], key) == 0)
+ return 1;
+ return 0;
+}
+
+/* 1 when the results went back to the model for its next reply, 0 when
+ there is nothing more to do, -1 when the exchange stops here. */
static int run_calls(janas_llm_chat *c, int autorun)
{
int32_t n = janas_llm_chat_calls(c);
@@ -954,7 +993,18 @@ static int run_calls(janas_llm_chat *c, int autorun)
T_DIM(&term), "", 400, args,
strlen(args) > 400 ? " ..." : "", T_RESET(&term));
int go = autorun || mcpc_always(name) || mcpc_own(name);
- if (!go && interrupted) {
+ char *key = call_key(name, args);
+ if (failed_before(key)) {
+ go = 0;
+ failed.again++;
+ term_printf(&term, "%snot run: the same call failed already%s\n",
+ T_WARN(&term), T_RESET(&term));
+ texts[i] = strdup("Not run: this very call, with the same "
+ "arguments, failed already in this exchange "
+ "and would fail again. Do not ask for it "
+ "again: answer the user with what you have, "
+ "or ask them for what is missing.");
+ } else if (!go && interrupted) {
go = 0;
} else if (!go && !term.tty) {
term_printf(&term, "not run: on a pipe nobody can say yes "
@@ -968,16 +1018,21 @@ static int run_calls(janas_llm_chat *c, int autorun)
if (go) {
footer(idle_llm, c, "running a tool");
int rc = mcpc_call(name, args, &texts[i]);
+ if (rc != 0 && key && failed.n < FAILED_MAX) {
+ failed.call[failed.n++] = key;
+ key = NULL;
+ }
const char *t = texts[i] ? texts[i] : "";
size_t line = strcspn(t, "\n");
term_printf(
&term, "%s%s%.*s%s%s\n", rc ? T_WARN(&term) : T_DIM(&term),
rc > 0 ? "tool error: " : "", (int)(line < 200 ? line : 200), t,
line < strlen(t) || line > 200 ? " ..." : "", T_RESET(&term));
- } else {
+ } else if (!texts[i]) {
texts[i] = strdup("The user did not allow this call: it was "
"not run.");
}
+ free(key);
free(name);
free(args);
if (!texts[i])
@@ -995,6 +1050,13 @@ static int run_calls(janas_llm_chat *c, int autorun)
free(texts[i]);
free(texts);
interrupted = 0;
+ if (sent && failed.again >= 2) {
+ term_printf(&term,
+ "%sstopped: the model keeps asking for a call that "
+ "failed%s\n",
+ T_WARN(&term), T_RESET(&term));
+ return -1;
+ }
return sent;
}
@@ -1421,12 +1483,14 @@ int main(int argc, char **argv)
continue;
}
/* the reply, and while it calls tools and they answer, the next */
+ failed_clear();
for (int round = 0; round < 16; round++)
if (show_reply(llm, c, markdown, stats) != 0 ||
run_calls(c, mcp_auto) <= 0)
break;
footer(llm, c, NULL);
}
+ failed_clear();
free(msg);
free(system);
free(mcp_extra);
diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.c
index 56d2bea..87804fd 100644
--- a/src/chat/mcp_chat.c
+++ b/src/chat/mcp_chat.c
@@ -28,7 +28,7 @@ struct server {
beside it: janas-<name>. They read public data and change nothing, so
their tools run without asking, and what they say of their tools goes
to the model. */
-static const char *const SERVICES[] = {"flights"};
+static const char *const SERVICES[] = {"flights", "weather"};
static struct server *servers;
static size_t n_servers;
diff --git a/src/flights/geo.c b/src/common/geo.c
similarity index 96%
rename from src/flights/geo.c
rename to src/common/geo.c
index e8e6d7f..539fdd2 100644
--- a/src/flights/geo.c
+++ b/src/common/geo.c
@@ -1,8 +1,8 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * geo.c - janas-flights' geography (see geo.h): the generated tables, and a
- * position put into words.
+ * geo.c - the geography of Janas's services (see geo.h): the generated tables,
+ * and a position put into words.
*/
#include <ctype.h>
#include <math.h>
@@ -49,6 +49,11 @@ const char *geo_country_name(uint16_t i)
return i < N_OF(geo_countries) ? geo_countries[i].name : "";
}
+const char *geo_country_iso2(uint16_t i)
+{
+ return i < N_OF(geo_countries) ? geo_countries[i].iso2 : "";
+}
+
const char *geo_region_name(uint16_t i)
{
return i < N_OF(geo_regions) ? geo_regions[i].name : "";
@@ -344,12 +349,10 @@ static void where_of(const struct geo_city *c, struct janas_buf *b)
janas_buf_puts(b, geo_country_name(c->country));
}
-void geo_describe(double lat, double lon, struct janas_buf *b)
+const struct geo_city *geo_city_near(double lat, double lon, double *km)
{
- /* the nearest city, and the nearest of another region that lies the
- other way: the two the position is between */
- const struct geo_city *near = NULL, *other = NULL;
- double d_near = 1e30, d_other = 1e30;
+ const struct geo_city *near = NULL;
+ double d_near = 1e30;
for (size_t i = 0; i < N_OF(geo_cities); i++) {
const struct geo_city *c = &geo_cities[i];
if (fabs(DEG(c->lat) - lat) > 5)
@@ -364,6 +367,17 @@ void geo_describe(double lat, double lon, struct janas_buf *b)
near = c;
}
}
+ *km = d_near;
+ return near;
+}
+
+void geo_describe(double lat, double lon, struct janas_buf *b)
+{
+ /* the nearest city, and the nearest of another region that lies the
+ other way: the two the position is between */
+ const struct geo_city *other = NULL;
+ double d_near, d_other = 1e30;
+ const struct geo_city *near = geo_city_near(lat, lon, &d_near);
if (!near) {
janas_buf_printf(b, "at %.2f, %.2f", lat, lon);
return;
diff --git a/src/flights/geo.h b/src/common/geo.h
similarity index 88%
rename from src/flights/geo.h
rename to src/common/geo.h
index fe94d7d..ce08a76 100644
--- a/src/flights/geo.h
+++ b/src/common/geo.h
@@ -1,7 +1,8 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * geo.h - janas-flights' geography: airports, cities, seas, and a position
+ * geo.h - the geography of Janas's services (janas-flights, janas-weather):
+ * airports, cities, seas, and a position
* put into words ("over the Tyrrhenian Sea, between Corsica (France) and
* Tuscany (Italy), 85 km WSW of Livorno"), so that the model telling it
* never has to work out where a latitude and a longitude are.
@@ -10,8 +11,8 @@
* OurAirports (public domain), GeoNames (CC BY 4.0) and Natural Earth
* (public domain). Coordinates are in hundred-thousandths of a degree.
*/
-#ifndef JANAS_FLIGHTS_GEO_H
-#define JANAS_FLIGHTS_GEO_H
+#ifndef JANAS_COMMON_GEO_H
+#define JANAS_COMMON_GEO_H
#include <stdint.h>
@@ -65,10 +66,14 @@ const struct geo_airport *geo_airport_find(const char *what);
/* A city by name (its ASCII name, case ignored; the most populous of those
of that name); NULL when none. */
const struct geo_city *geo_city_find(const char *name);
+/* The nearest city (within 5 degrees of latitude; one under 10,000
+ people only within 3 km), and its distance; NULL when none. */
+const struct geo_city *geo_city_near(double lat, double lon, double *km);
/* The nearest airport with scheduled flights, and its distance. */
const struct geo_airport *geo_airport_near(double lat, double lon, double *km);
const char *geo_country_name(uint16_t i);
+const char *geo_country_iso2(uint16_t i); /* "IT" */
const char *geo_region_name(uint16_t i);
const char *geo_tz_name(uint16_t i);
diff --git a/src/flights/geo_data.h b/src/common/geo_data.h
similarity index 100%
rename from src/flights/geo_data.h
rename to src/common/geo_data.h
diff --git a/src/flights/net.c b/src/common/https_get.c
similarity index 81%
rename from src/flights/net.c
rename to src/common/https_get.c
index 670a9b1..4caf84a 100644
--- a/src/flights/net.c
+++ b/src/common/https_get.c
@@ -1,21 +1,23 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * net.c - a GET over HTTPS for janas-flights, with the HTTP client and TLS
- * of the MCP transport (common/mcp_http.c, mcp_tls.c).
+ * https_get.c - a GET over HTTPS for Janas's services, with the HTTP client
+ * and TLS of the MCP transport (common/mcp_http.c, mcp_tls.c).
*/
#include <stdio.h>
#include <string.h>
+#include "https_get.h"
+
#include "common/mcp_http.h"
-#include "flights.h"
#define TIMEOUT_MS 15000
#define MAX_REDIRECTS 4
#define MAX_BODY (16u << 20)
-int fl_get(const char *url, const char *const *headers, size_t n_headers,
- struct janas_buf *out, char *err, size_t err_len)
+int janas_https_get(const char *url, const char *const *headers,
+ size_t n_headers, struct janas_buf *out, char *err,
+ size_t err_len)
{
char where[4096];
snprintf(where, sizeof where, "%s", url);
diff --git a/src/common/https_get.h b/src/common/https_get.h
new file mode 100644
index 0000000..033e06d
--- /dev/null
+++ b/src/common/https_get.h
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * https_get.h - a GET over HTTPS (https_get.c), for Janas's services.
+ */
+#ifndef JANAS_COMMON_HTTPS_GET_H
+#define JANAS_COMMON_HTTPS_GET_H
+
+#include <stddef.h>
+
+#include "llm/json.h"
+
+/* GET of url (https), following redirects, the body into out (with a 0
+ after it, not counted). The HTTP status (200...), or -1 with the reason
+ in err. */
+int janas_https_get(const char *url, const char *const *headers,
+ size_t n_headers, struct janas_buf *out, char *err,
+ size_t err_len);
+
+#endif
diff --git a/src/common/locate.c b/src/common/locate.c
new file mode 100644
index 0000000..fc56756
--- /dev/null
+++ b/src/common/locate.c
@@ -0,0 +1,243 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * locate.c - where the user is (locate.h): JANAS_LOCATION, the internet
+ * connection's position, the machine's time zone.
+ */
+#define _GNU_SOURCE
+#include <math.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "common/geo.h"
+#include "common/https_get.h"
+#include "common/locate.h"
+
+#define DEG(x) ((x) * 1e-5)
+#define KEEP_S 3600 /* a connection seldom moves within the hour */
+
+static void copy(char *dst, size_t cap, const char *src)
+{
+ snprintf(dst, cap, "%s", src ? src : "");
+}
+
+/* the region, country and zone of the nearest city of the tables, for
+ what a source left out */
+static void fill_from_tables(struct janas_where *w)
+{
+ double km;
+ const struct geo_city *c = geo_city_near(w->lat, w->lon, &km);
+ if (!c)
+ return;
+ if (!w->city[0] && km < 3)
+ copy(w->city, sizeof w->city, c->name);
+ if (!w->region[0] && c->region != 0xFFFF)
+ copy(w->region, sizeof w->region, geo_region_name(c->region));
+ if (!w->country[0])
+ copy(w->country, sizeof w->country, geo_country_name(c->country));
+ if (!w->cc[0])
+ copy(w->cc, sizeof w->cc, geo_country_iso2(c->country));
+ if (!w->tz[0])
+ copy(w->tz, sizeof w->tz, geo_tz_name(c->tz));
+}
+
+static void from_city(const struct geo_city *c, struct janas_where *w)
+{
+ w->lat = DEG(c->lat);
+ w->lon = DEG(c->lon);
+ copy(w->city, sizeof w->city, c->name);
+ fill_from_tables(w);
+}
+
+/* "38.02, 12.51" */
+static int as_point(const char *q, double *lat, double *lon)
+{
+ char *end;
+ double a = strtod(q, &end);
+ if (end == q)
+ return 0;
+ while (*end == ' ' || *end == ',' || *end == ';')
+ end++;
+ char *end2;
+ double b = strtod(end, &end2);
+ while (*end2 == ' ')
+ end2++;
+ if (end2 == end || *end2 || fabs(a) > 90 || fabs(b) > 180)
+ return 0;
+ *lat = a;
+ *lon = b;
+ return 1;
+}
+
+/* a number given as a number or as a string (GeoJS: "38.1302") */
+static double num(const struct janas_json *v)
+{
+ const char *s = janas_json_str(v);
+ if (s) {
+ char *end;
+ double d = strtod(s, &end);
+ return end != s ? d : NAN;
+ }
+ return janas_json_num(v, NAN);
+}
+
+static int point_ok(const struct janas_where *w)
+{
+ return !isnan(w->lat) && !isnan(w->lon) && fabs(w->lat) <= 90 &&
+ fabs(w->lon) <= 180 && (w->lat != 0 || w->lon != 0);
+}
+
+int janas_where_geojs(const char *text, size_t n, struct janas_where *w)
+{
+ struct janas_json_doc *d = janas_json_parse(text, n, NULL, 0);
+ const struct janas_json *r = d ? janas_json_root(d) : NULL;
+ memset(w, 0, sizeof *w);
+ w->lat = num(janas_json_get(r, "latitude"));
+ w->lon = num(janas_json_get(r, "longitude"));
+ copy(w->city, sizeof w->city, janas_json_str(janas_json_get(r, "city")));
+ copy(w->region, sizeof w->region,
+ janas_json_str(janas_json_get(r, "region")));
+ copy(w->country, sizeof w->country,
+ janas_json_str(janas_json_get(r, "country")));
+ copy(w->cc, sizeof w->cc,
+ janas_json_str(janas_json_get(r, "country_code")));
+ copy(w->tz, sizeof w->tz, janas_json_str(janas_json_get(r, "timezone")));
+ int ok = r && point_ok(w);
+ janas_json_free(d);
+ return ok ? 0 : -1;
+}
+
+int janas_where_ipwhois(const char *text, size_t n, struct janas_where *w)
+{
+ struct janas_json_doc *d = janas_json_parse(text, n, NULL, 0);
+ const struct janas_json *r = d ? janas_json_root(d) : NULL;
+ memset(w, 0, sizeof *w);
+ const struct janas_json *ok = janas_json_get(r, "success");
+ w->lat = num(janas_json_get(r, "latitude"));
+ w->lon = num(janas_json_get(r, "longitude"));
+ copy(w->city, sizeof w->city, janas_json_str(janas_json_get(r, "city")));
+ copy(w->region, sizeof w->region,
+ janas_json_str(janas_json_get(r, "region")));
+ copy(w->country, sizeof w->country,
+ janas_json_str(janas_json_get(r, "country")));
+ copy(w->cc, sizeof w->cc,
+ janas_json_str(janas_json_get(r, "country_code")));
+ copy(w->tz, sizeof w->tz,
+ janas_json_str(janas_json_get(janas_json_get(r, "timezone"), "id")));
+ int good = r && ok && ok->type == JANAS_JSON_TRUE && point_ok(w);
+ janas_json_free(d);
+ return good ? 0 : -1;
+}
+
+static int from_net(const char *url, const char *who,
+ int (*parse)(const char *, size_t, struct janas_where *),
+ struct janas_where *w)
+{
+ struct janas_buf b = {0};
+ char why[256];
+ int status = janas_https_get(url, NULL, 0, &b, why, sizeof why);
+ int r = status == 200 && b.p ? parse(b.p, b.n, w) : -1;
+ janas_buf_free(&b);
+ if (r == 0) {
+ snprintf(w->how, sizeof w->how,
+ "estimated from the internet connection (%s)", who);
+ fill_from_tables(w);
+ }
+ return r;
+}
+
+/* the city of the machine's zone: TZ, or where /etc/localtime points */
+static int from_zone(struct janas_where *w)
+{
+ char path[256] = "";
+ const char *tz = getenv("TZ");
+ if (tz && *tz) {
+ copy(path, sizeof path, tz[0] == ':' ? tz + 1 : tz);
+ } else {
+ ssize_t n = readlink("/etc/localtime", path, sizeof path - 1);
+ if (n <= 0)
+ return -1;
+ path[n] = 0;
+ }
+ const char *z = strstr(path, "zoneinfo/");
+ z = z ? z + 9 : path; /* "Europe/Rome" */
+ const char *slash = strrchr(z, '/');
+ if (!slash) /* "UTC", "CET": no city */
+ return -1;
+ char city[64];
+ copy(city, sizeof city, slash + 1);
+ for (char *c = city; *c; c++)
+ if (*c == '_')
+ *c = ' '; /* "New_York" */
+ const struct geo_city *c = geo_city_find(city);
+ if (!c)
+ return -1;
+ memset(w, 0, sizeof *w);
+ copy(w->tz, sizeof w->tz, z);
+ from_city(c, w);
+ copy(w->how, sizeof w->how,
+ "a rough guess, the city of the computer's time zone");
+ return 0;
+}
+
+static pthread_mutex_t kept_mu = PTHREAD_MUTEX_INITIALIZER;
+static struct janas_where kept;
+static time_t kept_at;
+
+int janas_where(struct janas_where *w, char *err, size_t err_len)
+{
+ const char *set = getenv("JANAS_LOCATION");
+ memset(w, 0, sizeof *w);
+ if (set && *set) {
+ if (strcmp(set, "off") == 0) {
+ snprintf(err, err_len,
+ "where the user is is not known (JANAS_LOCATION=off): "
+ "ask them which place");
+ return -1;
+ }
+ const struct geo_city *c = NULL;
+ if (as_point(set, &w->lat, &w->lon))
+ fill_from_tables(w);
+ else if ((c = geo_city_find(set)) != NULL)
+ from_city(c, w);
+ else {
+ snprintf(err, err_len,
+ "JANAS_LOCATION is \"%.60s\": neither a city of the "
+ "tables (its English name) nor \"lat,lon\"",
+ set);
+ return -1;
+ }
+ copy(w->how, sizeof w->how, "as set on the computer (JANAS_LOCATION)");
+ return 0;
+ }
+ pthread_mutex_lock(&kept_mu);
+ int fresh = kept_at && time(NULL) - kept_at < KEEP_S;
+ if (fresh)
+ *w = kept;
+ pthread_mutex_unlock(&kept_mu);
+ if (fresh)
+ return 0;
+ if (from_net("https://get.geojs.io/v1/ip/geo.json", "GeoJS",
+ janas_where_geojs, w) != 0 &&
+ from_net("https://ipwho.is/", "ipwho.is", janas_where_ipwhois, w) !=
+ 0) {
+ /* not kept: the connection is asked again next time */
+ if (from_zone(w) == 0)
+ return 0;
+ memset(w, 0, sizeof *w);
+ snprintf(err, err_len,
+ "where the user is could not be told (no answer from GeoJS "
+ "or ipwho.is, and no city for the computer's time zone): "
+ "ask them which place");
+ return -1;
+ }
+ pthread_mutex_lock(&kept_mu);
+ kept = *w;
+ kept_at = time(NULL);
+ pthread_mutex_unlock(&kept_mu);
+ return 0;
+}
diff --git a/src/common/locate.h b/src/common/locate.h
new file mode 100644
index 0000000..37cf778
--- /dev/null
+++ b/src/common/locate.h
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * locate.h - where the user is, for Janas's services when a question
+ * names no place ("what's the weather like?", "what flies over here?").
+ *
+ * In this order: JANAS_LOCATION when set (a place's name, or "lat,lon";
+ * "off" for no guess at all); else the internet connection's position
+ * (GeoJS, then ipwho.is: free, no key, a city or so off, the provider's
+ * rather than the user's at times); else the city of the machine's time
+ * zone (Europe/Rome: Rome), a rough one. Kept for an hour.
+ */
+#ifndef JANAS_COMMON_LOCATE_H
+#define JANAS_COMMON_LOCATE_H
+
+#include <stddef.h>
+
+struct janas_where {
+ double lat, lon;
+ char city[96]; /* "Palermo"; "" when only the point is known */
+ char region[64]; /* "Sicily" */
+ char country[64];
+ char cc[3]; /* "IT" */
+ char tz[48]; /* "Europe/Rome" */
+ char how[96]; /* "estimated from the internet connection (GeoJS)" */
+};
+
+/* 0, or -1 with the reason in err (nothing known, or JANAS_LOCATION=off). */
+int janas_where(struct janas_where *w, char *err, size_t err_len);
+
+/* The parsers, for the tests: 0 when the answer gave a position. */
+int janas_where_geojs(const char *text, size_t n, struct janas_where *w);
+int janas_where_ipwhois(const char *text, size_t n, struct janas_where *w);
+
+#endif
diff --git a/src/common/mcp_http.c b/src/common/mcp_http.c
index f896035..ac677cb 100644
--- a/src/common/mcp_http.c
+++ b/src/common/mcp_http.c
@@ -405,10 +405,13 @@ int janas_http_request(struct janas_http *h, const struct janas_url *u,
janas_buf_printf(&q, "%s %s HTTP/1.1\r\nHost: %s%s%s%s%s\r\n", method,
u->path, v6 ? "[" : "", u->host, v6 ? "]" : "",
dflt ? "" : ":", dflt ? "" : u->port);
- janas_buf_printf(&q,
- "Content-Length: %zu\r\nConnection: close\r\n"
- "User-Agent: janas\r\n",
- n);
+ /* the program's own User-Agent, when it gives one (MET Norway asks
+ for one that names the program and how to reach its authors) */
+ int agent = 0;
+ for (size_t i = 0; i < n_headers; i++)
+ agent |= strncasecmp(headers[i], "User-Agent:", 11) == 0;
+ janas_buf_printf(&q, "Content-Length: %zu\r\nConnection: close\r\n%s", n,
+ agent ? "" : "User-Agent: janas\r\n");
for (size_t i = 0; i < n_headers; i++)
janas_buf_printf(&q, "%s\r\n", headers[i]);
janas_buf_puts(&q, "\r\n");
diff --git a/src/flights/adsb.c b/src/flights/adsb.c
index 385bbcb..2731f4b 100644
--- a/src/flights/adsb.c
+++ b/src/flights/adsb.c
@@ -75,7 +75,8 @@ int fl_adsb(const char *query, struct fl_ac **ac, size_t *n,
char url[512];
snprintf(url, sizeof url, "%s%s", NETS[k].base, query);
struct janas_buf body = {0};
- int status = fl_get(url, NULL, 0, &body, why[k], sizeof why[k]);
+ int status =
+ janas_https_get(url, NULL, 0, &body, why[k], sizeof why[k]);
if (status != 200) {
if (status > 0)
snprintf(why[k], sizeof why[k], "HTTP %d", status);
diff --git a/src/flights/flights.h b/src/flights/flights.h
index cdd73ba..4a6a9f4 100644
--- a/src/flights/flights.h
+++ b/src/flights/flights.h
@@ -2,7 +2,7 @@
Copyright (C) 2026 Maurizio Cammalleri */
/*
* flights.h - janas-flights, flights as an MCP service: what its parts
- * share. net.c fetches, adsb.c reads the community ADS-B networks
+ * share. common/https_get.c fetches, adsb.c reads the community ADS-B networks
* (adsb.lol, adsb.fi as the fallback), route.c asks adsbdb for a
* callsign's route and an airline's codes, schedule.c asks AviationStack
* for the times (with a key of the user's), tools.c offers the tools.
@@ -13,15 +13,9 @@
#include <stddef.h>
#include <time.h>
+#include "common/https_get.h"
#include "llm/json.h"
-/* ---- net.c ---- */
-
-/* GET of url (https), following redirects, the body into out. The HTTP
- status (200...), or -1 with the reason in err. */
-int fl_get(const char *url, const char *const *headers, size_t n_headers,
- struct janas_buf *out, char *err, size_t err_len);
-
/* ---- adsb.c ---- */
/* One aircraft as the receivers last heard it. */
diff --git a/src/flights/route.c b/src/flights/route.c
index d03e06d..1a84fda 100644
--- a/src/flights/route.c
+++ b/src/flights/route.c
@@ -28,7 +28,7 @@ static int ask(const char *path, struct janas_json_doc **doc,
char url[256], err[160];
snprintf(url, sizeof url, BASE "%s", path);
struct janas_buf body = {0};
- int status = fl_get(url, NULL, 0, &body, err, sizeof err);
+ int status = janas_https_get(url, NULL, 0, &body, err, sizeof err);
*doc = NULL;
if (status == 404) {
janas_buf_free(&body);
diff --git a/src/flights/schedule.c b/src/flights/schedule.c
index f30c62a..9a919b6 100644
--- a/src/flights/schedule.c
+++ b/src/flights/schedule.c
@@ -220,7 +220,7 @@ int fl_schedule(const char *query, struct fl_sched **v, size_t *n, char *err,
snprintf(url, sizeof url, BASE "%s&%s", key, query);
struct janas_buf body = {0};
char why[256];
- int status = fl_get(url, NULL, 0, &body, why, sizeof why);
+ int status = janas_https_get(url, NULL, 0, &body, why, sizeof why);
if (status < 0) {
/* the address's errors quote it, and it holds the key */
if (strstr(why, key))
diff --git a/src/flights/tools.c b/src/flights/tools.c
index 20c8e02..f9f44a2 100644
--- a/src/flights/tools.c
+++ b/src/flights/tools.c
@@ -21,9 +21,10 @@
#include <time.h>
#include <unistd.h>
+#include "common/locate.h"
#include "common/mcp_server.h"
#include "flights.h"
-#include "geo.h"
+#include "common/geo.h"
#define DEG(x) ((x) * 1e-5)
#define KM_PER_NM 1.852
@@ -103,7 +104,10 @@ void fl_tools_list(void *ctx, struct janas_buf *b)
"Turin, Milan, Rome) or a latitude and longitude.\", "
"\"inputSchema\": {\"type\": \"object\", \"properties\": {");
schema_str(b, "place",
- "An airport code (TRN, LIMF) or a city name in English.");
+ "An airport code (TRN, LIMF) or a city name in English. "
+ "Leave out place and coordinates only when the user names "
+ "no place: then where the user is (as set on the computer, "
+ "or estimated from the internet connection).");
janas_buf_puts(
b, ", \"latitude\": {\"type\": \"number\", \"minimum\": -90, "
"\"maximum\": 90}, \"longitude\": {\"type\": \"number\", "
@@ -1124,7 +1128,7 @@ static int flights_nearby(const struct janas_json *args, struct janas_buf *b)
limit = 1;
if (limit > MAX_LIST)
limit = MAX_LIST;
- char where[200] = "";
+ char where[256] = "";
if (place && *place) {
const struct geo_airport *ap = geo_airport_find(place);
const struct geo_city *c = ap ? NULL : geo_city_find(place);
@@ -1148,9 +1152,19 @@ static int flights_nearby(const struct janas_json *args, struct janas_buf *b)
return 0;
}
} else if (lat > 90 || lat < -90 || lon > 180 || lon < -180) {
- const char *m = "Give a place, or a latitude and longitude.";
- janas_mcps_text_result(b, m, strlen(m), 1);
- return 0;
+ struct janas_where w;
+ char why[300];
+ if (janas_where(&w, why, sizeof why) != 0) {
+ char m[400];
+ snprintf(m, sizeof m, "No place given, and %s.", why);
+ janas_mcps_text_result(b, m, strlen(m), 1);
+ return 0;
+ }
+ lat = w.lat;
+ lon = w.lon;
+ snprintf(where, sizeof where, "%s (where the user is, %s)",
+ w.city[0] ? w.city : "the user's position", w.how);
+ place = where; /* named: no point to put into words */
} else {
snprintf(where, sizeof where, "%.3f, %.3f", lat, lon);
}
diff --git a/src/llm/tools.c b/src/llm/tools.c
index 80db70c..d36663b 100644
--- a/src/llm/tools.c
+++ b/src/llm/tools.c
@@ -906,12 +906,24 @@ static uint32_t args_rule(struct janas_jsg *j, const struct janas_json *f)
return janas_jsg_schema(j, p, p);
}
+/* Whether property p of a function's parameters is a required one. */
+static int xml_required(const struct janas_json *req,
+ const struct janas_json *p)
+{
+ for (const struct janas_json *q = req ? req->child : NULL; q; q = q->next)
+ if (q->type == JANAS_JSON_STRING && q->n == p->key_n &&
+ memcmp(q->s, p->key, q->n) == 0)
+ return 1;
+ return 0;
+}
+
/*
* The parameters of an XML call, in the schema's order, the required ones
* always there: R[i][x] as for a JSON object (schema.c), with no commas.
+ * For the functions with more parameters than XML_ANY_ORDER.
*/
-static uint32_t xml_params_rule(struct janas_gbuild *b, struct janas_jsg *j,
- const struct janas_json *f)
+static uint32_t xml_params_in_order(struct janas_gbuild *b, struct janas_jsg *j,
+ const struct janas_json *f)
{
const struct janas_json *params = janas_json_get(f, "parameters");
const struct janas_json *props = janas_json_get(params, "properties");
@@ -930,12 +942,7 @@ static uint32_t xml_params_rule(struct janas_gbuild *b, struct janas_jsg *j,
uint32_t text = janas_gb_until(b, close, strlen(close));
size_t i = 0;
for (const struct janas_json *p = props->child; p; p = p->next, i++) {
- int must = 0;
- for (const struct janas_json *q = req ? req->child : NULL; q && !must;
- q = q->next)
- must = q->type == JANAS_JSON_STRING && q->n == p->key_n &&
- memcmp(q->s, p->key, q->n) == 0;
- if (!must)
+ if (!xml_required(req, p))
janas_gb_ref(b, janas_gb_alt(b, r[i]), r[i + 1]);
uint32_t a = janas_gb_alt(b, r[i]);
janas_gb_lit(b, a, "<parameter=", 11);
@@ -956,6 +963,65 @@ static uint32_t xml_params_rule(struct janas_gbuild *b, struct janas_jsg *j,
return first;
}
+/*
+ * The parameters of an XML call in any order, each at most once, the
+ * required ones always there: a model held to the schema's order, having
+ * begun with a later parameter, could no longer write an earlier one, and
+ * at temperature 0 called the tool without it again and again (Qwen3.6
+ * with janas-weather: "days" first, and the place lost). R[S] is "the
+ * parameters of the set S written": 2^n rules, so only up to XML_ANY_ORDER.
+ */
+#define XML_ANY_ORDER 8
+
+static uint32_t xml_params_rule(struct janas_gbuild *b, struct janas_jsg *j,
+ const struct janas_json *f)
+{
+ const struct janas_json *params = janas_json_get(f, "parameters");
+ const struct janas_json *props = janas_json_get(params, "properties");
+ const struct janas_json *req = janas_json_get(params, "required");
+ if (!props || props->type != JANAS_JSON_OBJECT || props->n == 0)
+ return janas_gb_empty(b);
+ size_t n = props->n;
+ if (n > XML_ANY_ORDER)
+ return xml_params_in_order(b, j, f);
+ uint32_t ws = janas_jsg_ws(j);
+ const char *close = "\n</parameter>";
+ uint32_t text = janas_gb_until(b, close, strlen(close));
+ const struct janas_json *p_of[XML_ANY_ORDER];
+ uint32_t val[XML_ANY_ORDER], must = 0;
+ size_t i = 0;
+ for (const struct janas_json *p = props->child; p; p = p->next, i++) {
+ p_of[i] = p;
+ val[i] = is_text(p) ? text : janas_jsg_schema(j, p, params);
+ if (xml_required(req, p))
+ must |= 1u << i;
+ }
+ uint32_t sets = 1u << n, r[1u << XML_ANY_ORDER];
+ for (uint32_t s = 0; s < sets; s++)
+ r[s] = janas_gb_rule(b);
+ for (uint32_t s = 0; s < sets; s++) {
+ if ((s & must) == must)
+ janas_gb_alt(b, r[s]); /* the end */
+ for (i = 0; i < n; i++) {
+ if (s & (1u << i))
+ continue;
+ const struct janas_json *p = p_of[i];
+ uint32_t a = janas_gb_alt(b, r[s]);
+ janas_gb_lit(b, a, "<parameter=", 11);
+ janas_gb_lit(b, a, p->key, p->key_n);
+ janas_gb_lit(b, a, ">\n", 2);
+ janas_gb_ref(b, a, val[i]);
+ if (val[i] != text) {
+ janas_gb_ref(b, a, ws);
+ janas_gb_lit(b, a, "</parameter>", 12);
+ }
+ janas_gb_ref(b, a, ws);
+ janas_gb_ref(b, a, r[s | (1u << i)]);
+ }
+ }
+ return r[0];
+}
+
/*
* Gemma's notation, any value: strings between quote tokens, numbers and
* words, objects of bare keys, lists. Not held to the function's schema -
diff --git a/src/weather/alerts.c b/src/weather/alerts.c
new file mode 100644
index 0000000..330148c
--- /dev/null
+++ b/src/weather/alerts.c
@@ -0,0 +1,518 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * alerts.c - warnings (see weather.h). MeteoAlarm gathers the warnings of
+ * Europe's weather services, by country and region: wind, thunderstorms,
+ * heat, by level (green, yellow, orange, red); its feed holds warnings
+ * already expired, which are left out, and green ones, which say there is
+ * nothing to be warned of. For Italy, where those are the Air Force's and
+ * the official alerts are the Civil Protection's, the national bulletin of
+ * criticality is read too (CC BY 4.0, on GitHub, once a day about 16:00):
+ * the zone of alert a municipality is in, and its levels for floods,
+ * landslides and thunderstorms, today and tomorrow.
+ */
+#define _GNU_SOURCE /* strcasestr */
+#include <ctype.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+
+#include "weather.h"
+
+#define KEEP_ALARM 900 /* MeteoAlarm's feed */
+#define KEEP_LATEST 1800 /* which bulletin is the latest */
+#define KEEP_DPC 3600 /* a bulletin */
+#define DPC_REPO "pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica"
+
+/* MeteoAlarm's feeds, by ISO country code */
+static const struct {
+ const char cc[3], *feed;
+} FEEDS[] = {
+ {"AT", "austria"},
+ {"BA", "bosnia-herzegovina"},
+ {"BE", "belgium"},
+ {"BG", "bulgaria"},
+ {"CH", "switzerland"},
+ {"CY", "cyprus"},
+ {"CZ", "czechia"},
+ {"DE", "germany"},
+ {"DK", "denmark"},
+ {"EE", "estonia"},
+ {"ES", "spain"},
+ {"FI", "finland"},
+ {"FR", "france"},
+ {"GB", "united-kingdom"},
+ {"GR", "greece"},
+ {"HR", "croatia"},
+ {"HU", "hungary"},
+ {"IE", "ireland"},
+ {"IL", "israel"},
+ {"IS", "iceland"},
+ {"IT", "italy"},
+ {"LT", "lithuania"},
+ {"LU", "luxembourg"},
+ {"LV", "latvia"},
+ {"MD", "moldova"},
+ {"ME", "montenegro"},
+ {"MK", "republic-of-north-macedonia"},
+ {"MT", "malta"},
+ {"NL", "netherlands"},
+ {"NO", "norway"},
+ {"PL", "poland"},
+ {"PT", "portugal"},
+ {"RO", "romania"},
+ {"RS", "serbia"},
+ {"SE", "sweden"},
+ {"SI", "slovenia"},
+ {"SK", "slovakia"},
+ {"UA", "ukraine"},
+};
+
+static void copy(char *to, size_t cap, const char *s)
+{
+ snprintf(to, cap, "%s", s ? s : "");
+}
+
+/* "2026-10-01T23:59:00+02:00" */
+time_t wx_iso_time(const char *s)
+{
+ struct tm tm = {0};
+ int oh = 0, om = 0;
+ char sign = '+';
+ if (!s || sscanf(s, "%d-%d-%dT%d:%d:%d%c%d:%d", &tm.tm_year, &tm.tm_mon,
+ &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &sign,
+ &oh, &om) < 6)
+ return 0;
+ tm.tm_year -= 1900;
+ tm.tm_mon -= 1;
+ time_t t = timegm(&tm);
+ int off = (oh * 60 + om) * 60;
+ return sign == '-' ? t + off : t - off;
+}
+
+/* the value of a parameter: "awareness_level" -> "2; yellow; Moderate" */
+static const char *param(const struct janas_json *info, const char *name)
+{
+ const struct janas_json *ps = janas_json_get(info, "parameter");
+ for (const struct janas_json *p =
+ ps && ps->type == JANAS_JSON_ARRAY ? ps->child : NULL;
+ p; p = p->next)
+ if (janas_json_is(janas_json_get(p, "valueName"), name))
+ return janas_json_str(janas_json_get(p, "value"));
+ return NULL;
+}
+
+static int area_is(const struct janas_json *info, const char *region,
+ char *desc, size_t cap)
+{
+ const struct janas_json *as = janas_json_get(info, "area");
+ int mine = 0;
+ desc[0] = 0;
+ for (const struct janas_json *a =
+ as && as->type == JANAS_JSON_ARRAY ? as->child : NULL;
+ a; a = a->next) {
+ const char *d = janas_json_str(janas_json_get(a, "areaDesc"));
+ if (!d)
+ continue;
+ if (!desc[0])
+ copy(desc, cap, d);
+ if (region && *region &&
+ (strcasestr(d, region) || strcasestr(region, d))) {
+ mine = 1;
+ copy(desc, cap, d);
+ }
+ }
+ return mine;
+}
+
+int wx_meteoalarm_parse(const char *text, size_t len, const char *region,
+ const char *lang, time_t now, struct wx_alert **v,
+ size_t *n, char *err, size_t err_len)
+{
+ *v = NULL;
+ *n = 0;
+ struct janas_buf b = {.p = (char *)text, .n = len};
+ struct janas_json_doc *d = wx_parse(&b, "MeteoAlarm", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *ws =
+ janas_json_get(janas_json_root(d), "warnings");
+ size_t cap = ws && ws->type == JANAS_JSON_ARRAY ? ws->n : 0;
+ struct wx_alert *out = cap ? calloc(cap, sizeof *out) : NULL;
+ size_t got = 0;
+ for (const struct janas_json *w = cap ? ws->child : NULL; w && out;
+ w = w->next) {
+ const struct janas_json *infos =
+ janas_json_get(janas_json_get(w, "alert"), "info");
+ /* the info in the language asked, else in English, else the
+ first */
+ const struct janas_json *pick = NULL, *en = NULL, *first = NULL;
+ for (const struct janas_json *i =
+ infos && infos->type == JANAS_JSON_ARRAY ? infos->child : NULL;
+ i; i = i->next) {
+ const char *l = janas_json_str(janas_json_get(i, "language"));
+ if (!first)
+ first = i;
+ if (l && lang && strncasecmp(l, lang, strlen(lang)) == 0)
+ pick = i;
+ if (l && strncasecmp(l, "en", 2) == 0)
+ en = i;
+ }
+ const struct janas_json *i = pick ? pick : en ? en : first;
+ if (!i)
+ continue;
+ const char *exp = janas_json_str(janas_json_get(i, "expires"));
+ if (wx_iso_time(exp) <= now)
+ continue; /* over */
+ const char *lv = param(i, "awareness_level"); /* "2; yellow; ..." */
+ const char *col = lv ? strchr(lv, ';') : NULL;
+ char level[16] = "";
+ if (col)
+ sscanf(col + 1, " %15[a-z]", level);
+ if (!level[0] || strcmp(level, "green") == 0)
+ continue; /* nothing to be warned of */
+ if (got == cap)
+ break;
+ struct wx_alert *a = &out[got];
+ copy(a->level, sizeof a->level, level);
+ copy(a->event, sizeof a->event,
+ janas_json_str(janas_json_get(i, "event")));
+ a->mine = area_is(i, region, a->area, sizeof a->area);
+ copy(a->onset, sizeof a->onset,
+ janas_json_str(janas_json_get(i, "onset")));
+ copy(a->expires, sizeof a->expires, exp);
+ copy(a->sender, sizeof a->sender,
+ janas_json_str(janas_json_get(i, "senderName")));
+ copy(a->text, sizeof a->text,
+ janas_json_str(janas_json_get(i, "description")));
+ /* the same warning given again, for the same area and times */
+ int dup = 0;
+ for (size_t k = 0; k < got && !dup; k++)
+ dup = strcmp(out[k].event, a->event) == 0 &&
+ strcmp(out[k].area, a->area) == 0 &&
+ strcmp(out[k].onset, a->onset) == 0 &&
+ strcmp(out[k].expires, a->expires) == 0;
+ if (!dup)
+ got++;
+ }
+ janas_json_free(d);
+ if (cap && !out) {
+ snprintf(err, err_len, "out of memory");
+ return -1;
+ }
+ /* the place's region first */
+ for (size_t i = 0, j = 0; i < got; i++)
+ if (out[i].mine) {
+ struct wx_alert t = out[i];
+ memmove(&out[j + 1], &out[j], (i - j) * sizeof *out);
+ out[j++] = t;
+ }
+ *v = out;
+ *n = got;
+ return 0;
+}
+
+int wx_meteoalarm(const struct wx_place *p, const char *lang,
+ struct wx_alert **v, size_t *n, char *err, size_t err_len)
+{
+ *v = NULL;
+ *n = 0;
+ const char *feed = NULL;
+ for (size_t i = 0; i < sizeof FEEDS / sizeof FEEDS[0]; i++)
+ if (strcasecmp(FEEDS[i].cc, p->cc) == 0)
+ feed = FEEDS[i].feed;
+ if (!feed) {
+ snprintf(err, err_len, "MeteoAlarm has no warnings for %s",
+ p->country[0] ? p->country : "that country");
+ return 1;
+ }
+ char url[160];
+ snprintf(url, sizeof url,
+ "https://feeds.meteoalarm.org/api/v1/warnings/feeds-%s", feed);
+ struct janas_buf b = {0};
+ char why[256];
+ int status = wx_fetch(url, KEEP_ALARM, 0, &b, why, sizeof why);
+ int r = -1;
+ if (status == 200)
+ r = wx_meteoalarm_parse(b.p, b.n, p->region, lang, time(NULL), v, n,
+ err, err_len);
+ else if (status < 0)
+ snprintf(err, err_len, "MeteoAlarm did not answer: %s", why);
+ else
+ snprintf(err, err_len, "MeteoAlarm: HTTP %d", status);
+ janas_buf_free(&b);
+ return r;
+}
+
+/* ---- the Civil Protection's bulletin ---- */
+
+static int rank(const char *level)
+{
+ if (!level)
+ return -1;
+ if (strcasestr(level, "ROSSA"))
+ return 3;
+ if (strcasestr(level, "ARANCIONE"))
+ return 2;
+ if (strcasestr(level, "GIALLA"))
+ return 1;
+ return 0;
+}
+
+/* Whether the point is inside a ring of [lon, lat] pairs: the edges a
+ ray to the east crosses, odd. */
+static int ring_has(const struct janas_json *ring, double lat, double lon)
+{
+ int in = 0;
+ const struct janas_json *a = NULL, *first = NULL;
+ for (const struct janas_json *b =
+ ring && ring->type == JANAS_JSON_ARRAY ? ring->child : NULL;
+ ; b = b->next) {
+ const struct janas_json *q = b ? b : first; /* closed at the end */
+ if (!q || !q->child || !q->child->next)
+ break;
+ if (!first)
+ first = q;
+ if (a) {
+ double x1 = janas_json_num(a->child, NAN),
+ y1 = janas_json_num(a->child->next, NAN),
+ x2 = janas_json_num(q->child, NAN),
+ y2 = janas_json_num(q->child->next, NAN);
+ if ((y1 > lat) != (y2 > lat) &&
+ lon < x1 + (lat - y1) * (x2 - x1) / (y2 - y1))
+ in = !in;
+ }
+ a = q;
+ if (!b)
+ break;
+ }
+ return in;
+}
+
+/* Whether the point is inside a GeoJSON Polygon or MultiPolygon: inside an
+ odd number of its rings (holes are rings too). */
+static int geometry_has(const struct janas_json *g, double lat, double lon)
+{
+ const struct janas_json *c = janas_json_get(g, "coordinates");
+ int multi = janas_json_is(janas_json_get(g, "type"), "MultiPolygon");
+ if (!multi && !janas_json_is(janas_json_get(g, "type"), "Polygon"))
+ return 0;
+ int in = 0;
+ for (const struct janas_json *p =
+ c && c->type == JANAS_JSON_ARRAY ? c->child : NULL;
+ p; p = p->next) {
+ const struct janas_json *rings = multi ? p->child : p;
+ if (!multi) { /* p is a ring itself */
+ in ^= ring_has(p, lat, lon);
+ continue;
+ }
+ for (const struct janas_json *r = rings; r; r = r->next)
+ in ^= ring_has(r, lat, lon);
+ }
+ return in;
+}
+
+/* the zone's levels, the highest of each risk, and its name, into out */
+static void dpc_take(const struct janas_json *pr, char out[3][96], char *zones,
+ size_t zones_len, size_t *zn)
+{
+ static const char *const keys[3] = {"Per rischio idraulico",
+ "Per rischio idrogeologico",
+ "Per rischio temporali"};
+ const char *zone = janas_json_str(janas_json_get(pr, "Nome zona"));
+ if (zone && *zn < zones_len)
+ *zn += (size_t)snprintf(zones + *zn, zones_len - *zn, "%s%s",
+ *zn ? "; " : "", zone);
+ for (int k = 0; k < 3; k++) {
+ const char *lv = janas_json_str(janas_json_get(pr, keys[k]));
+ if (lv && rank(lv) > rank(out[k][0] ? out[k] : NULL))
+ copy(out[k], 96, lv);
+ }
+}
+
+int wx_dpc_parse(const char *text, size_t len, const char *comune, double lat,
+ double lon, char out[3][96], char *zones, size_t zones_len,
+ char *err, size_t err_len)
+{
+ struct janas_buf b = {.p = (char *)text, .n = len};
+ struct janas_json_doc *d =
+ wx_parse(&b, "the Civil Protection's bulletin", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *fs =
+ janas_json_get(janas_json_root(d), "features");
+ int found = 0;
+ size_t zn = 0;
+ zones[0] = 0;
+ for (int k = 0; k < 3; k++)
+ out[k][0] = 0;
+ for (const struct janas_json *f =
+ fs && fs->type == JANAS_JSON_ARRAY ? fs->child : NULL;
+ f; f = f->next) {
+ const struct janas_json *pr = janas_json_get(f, "properties");
+ const struct janas_json *cs = janas_json_get(pr, "Comuni");
+ int in = 0;
+ for (const struct janas_json *c =
+ cs && cs->type == JANAS_JSON_ARRAY ? cs->child : NULL;
+ c && !in; c = c->next)
+ in =
+ janas_json_str(c) && strcasecmp(janas_json_str(c), comune) == 0;
+ if (!in)
+ continue;
+ found = 1;
+ dpc_take(pr, out, zones, zones_len, &zn);
+ }
+ /* a name the bulletin does not have (Turin, an airport's, the
+ internet connection's town): the zone the point is in */
+ for (const struct janas_json *f = !found && !isnan(lat) && !isnan(lon) &&
+ fs && fs->type == JANAS_JSON_ARRAY
+ ? fs->child
+ : NULL;
+ f; f = f->next)
+ if (geometry_has(janas_json_get(f, "geometry"), lat, lon)) {
+ found = 1;
+ dpc_take(janas_json_get(f, "properties"), out, zones, zones_len,
+ &zn);
+ }
+ janas_json_free(d);
+ return found;
+}
+
+/* The latest bulletin's stamp ("20260930_1423"), from the last commit
+ that touched its files. 0, or -1. */
+static int latest(char stamp[16], char *err, size_t err_len)
+{
+ struct janas_buf b = {0};
+ char why[256];
+ const char *url = "https://api.github.com/repos/" DPC_REPO
+ "/commits?path=files/geojson&per_page=1";
+ int status = wx_fetch(url, KEEP_LATEST, 0, &b, why, sizeof why);
+ char sha[48] = "";
+ if (status == 200) {
+ struct janas_json_doc *d = wx_parse(&b, "GitHub", why, sizeof why);
+ const struct janas_json *r = d ? janas_json_root(d) : NULL;
+ if (r && r->type == JANAS_JSON_ARRAY && r->child)
+ copy(sha, sizeof sha,
+ janas_json_str(janas_json_get(r->child, "sha")));
+ janas_json_free(d);
+ }
+ if (!sha[0]) {
+ snprintf(err, err_len,
+ "GitHub did not say which bulletin is the "
+ "latest%s%s",
+ status < 0 ? ": " : "", status < 0 ? why : "");
+ janas_buf_free(&b);
+ return -1;
+ }
+ char url2[256];
+ snprintf(url2, sizeof url2,
+ "https://api.github.com/repos/" DPC_REPO "/commits/%s", sha);
+ status = wx_fetch(url2, 7 * 24 * 3600, 0, &b, why, sizeof why);
+ stamp[0] = 0;
+ if (status == 200) {
+ struct janas_json_doc *d = wx_parse(&b, "GitHub", why, sizeof why);
+ const struct janas_json *fl =
+ d ? janas_json_get(janas_json_root(d), "files") : NULL;
+ for (const struct janas_json *f =
+ fl && fl->type == JANAS_JSON_ARRAY ? fl->child : NULL;
+ f && !stamp[0]; f = f->next) {
+ const char *name = janas_json_str(janas_json_get(f, "filename"));
+ const char *g = name ? strstr(name, "files/geojson/") : NULL;
+ if (g)
+ sscanf(g + 14, "%13[0-9_]", stamp);
+ }
+ janas_json_free(d);
+ }
+ janas_buf_free(&b);
+ if (strlen(stamp) != 13) {
+ snprintf(err, err_len, "the latest bulletin could not be found");
+ return -1;
+ }
+ return 0;
+}
+
+static int read_day(const char *stamp, const char *which,
+ const struct wx_place *p, char out[3][96], char *zones,
+ size_t zones_len, char *err, size_t err_len)
+{
+ char url[256];
+ snprintf(url, sizeof url,
+ "https://raw.githubusercontent.com/" DPC_REPO
+ "/master/files/geojson/%s_%s.json",
+ stamp, which);
+ struct janas_buf b = {0};
+ char why[256];
+ int status = wx_fetch(url, KEEP_DPC, 0, &b, why, sizeof why);
+ int r = -1;
+ if (status == 200)
+ r = wx_dpc_parse(b.p, b.n, p->name, p->lat, p->lon, out, zones,
+ zones_len, err, err_len);
+ else if (status == 404)
+ r = 0;
+ else if (status < 0)
+ snprintf(err, err_len, "GitHub did not answer: %s", why);
+ else
+ snprintf(err, err_len, "GitHub: HTTP %d", status);
+ janas_buf_free(&b);
+ return r;
+}
+
+int wx_dpc(const struct wx_place *p, struct wx_dpc *d, char *err,
+ size_t err_len)
+{
+ memset(d, 0, sizeof *d);
+ if (strcasecmp(p->cc, "IT") != 0)
+ return 0;
+ if (latest(d->issued, err, err_len) != 0)
+ return -1;
+ /* the bulletin's day, and today in Italy */
+ char bday[11];
+ snprintf(bday, sizeof bday, "%.4s-%.2s-%.2s", d->issued, d->issued + 4,
+ d->issued + 6);
+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;
+ setenv("TZ", "Europe/Rome", 1);
+ tzset();
+ time_t now = time(NULL), tom_t = now + 24 * 3600;
+ char today[11], tomorrow[11];
+ struct tm lt;
+ strftime(today, sizeof today, "%Y-%m-%d", localtime_r(&now, &lt));
+ strftime(tomorrow, sizeof tomorrow, "%Y-%m-%d", localtime_r(&tom_t, &lt));
+ struct tm bt = {0};
+ sscanf(bday, "%d-%d-%d", &bt.tm_year, &bt.tm_mon, &bt.tm_mday);
+ bt.tm_year -= 1900;
+ bt.tm_mon -= 1;
+ bt.tm_hour = 12;
+ bt.tm_isdst = -1;
+ time_t bnext_t = mktime(&bt) + 24 * 3600;
+ char bnext[11];
+ strftime(bnext, sizeof bnext, "%Y-%m-%d", localtime_r(&bnext_t, &lt));
+ if (old) {
+ setenv("TZ", old, 1);
+ free(old);
+ } else {
+ unsetenv("TZ");
+ }
+ tzset();
+ /* the bulletin's today and tomorrow, as far as they are still ahead:
+ yesterday's bulletin's tomorrow is today */
+ static const char *const which[2] = {"today", "tomorrow"};
+ const char *date[2] = {bday, bnext};
+ int found = 0, k = 0;
+ for (int i = 0; i < 2; i++) {
+ if (strcmp(date[i], today) != 0 && strcmp(date[i], tomorrow) != 0)
+ continue;
+ int r = read_day(d->issued, which[i], p, d->level[k], d->zones,
+ sizeof d->zones, err, err_len);
+ if (r < 0)
+ return found ? 1 : -1;
+ if (r > 0) {
+ copy(d->day[k], sizeof d->day[k], date[i]);
+ found = 1;
+ k++;
+ }
+ }
+ return found;
+}
diff --git a/src/weather/fetch.c b/src/weather/fetch.c
new file mode 100644
index 0000000..c578c21
--- /dev/null
+++ b/src/weather/fetch.c
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * fetch.c - janas-weather asks its sources (see weather.h): a GET over
+ * HTTPS, the answers kept a while. A forecast changes once an hour at most
+ * and a bulletin once a day, while a conversation asks again and again
+ * about the same place: the sources are spared, Open-Meteo's free use is a
+ * number of calls a day.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/https_get.h"
+#include "weather.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+#define N_KEPT 32
+
+static struct {
+ char *url;
+ time_t at;
+ int keep_s;
+ struct janas_buf body;
+} kept[N_KEPT];
+
+int wx_fetch(const char *url, int keep_s, int with_agent, struct janas_buf *out,
+ char *err, size_t err_len)
+{
+ time_t now = time(NULL);
+ int slot = 0;
+ for (int i = 0; i < N_KEPT; i++) {
+ if (kept[i].url && strcmp(kept[i].url, url) == 0 &&
+ now - kept[i].at < kept[i].keep_s) {
+ out->n = 0;
+ janas_buf_put(out, kept[i].body.p, kept[i].body.n);
+ janas_buf_put(out, "", 1);
+ out->n--;
+ return out->oom ? -1 : 200;
+ }
+ if (kept[i].at < kept[slot].at)
+ slot = i;
+ }
+ /* MET Norway asks for a User-Agent naming the program and a way to
+ reach its authors; requests without one are refused */
+ static const char *const agent[] = {
+ "User-Agent: janas-weather/" JANAS_VERSION
+ " https://github.com/prabanta-dev/janas"};
+ int status = janas_https_get(url, with_agent ? agent : NULL,
+ with_agent ? 1 : 0, out, err, err_len);
+ if (status == 200 && keep_s > 0 && !out->oom) {
+ free(kept[slot].url);
+ janas_buf_free(&kept[slot].body);
+ kept[slot].url = strdup(url);
+ kept[slot].at = now;
+ kept[slot].keep_s = keep_s;
+ kept[slot].body = (struct janas_buf){0};
+ janas_buf_put(&kept[slot].body, out->p, out->n);
+ if (!kept[slot].url || kept[slot].body.oom) {
+ free(kept[slot].url);
+ janas_buf_free(&kept[slot].body);
+ kept[slot].url = NULL;
+ kept[slot].at = 0;
+ }
+ }
+ return status;
+}
+
+void wx_fetch_free(void)
+{
+ for (int i = 0; i < N_KEPT; i++) {
+ free(kept[i].url);
+ janas_buf_free(&kept[i].body);
+ }
+ memset(kept, 0, sizeof kept);
+}
+
+struct janas_json_doc *wx_parse(const struct janas_buf *b, const char *who,
+ char *err, size_t err_len)
+{
+ char why[128];
+ struct janas_json_doc *d =
+ janas_json_parse(b->p ? b->p : "", b->n, why, sizeof why);
+ if (!d)
+ snprintf(err, err_len, "%s: an answer it could not read (%s)", who,
+ why);
+ return d;
+}
diff --git a/src/weather/main.c b/src/weather/main.c
new file mode 100644
index 0000000..a2a4c5f
--- /dev/null
+++ b/src/weather/main.c
@@ -0,0 +1,80 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * main.c - janas-weather: the weather as an MCP server over stdio, for
+ * janas-chat (which starts it by itself) and any other MCP client. Free
+ * sources only, no key: Open-Meteo (MET Norway when it does not answer),
+ * the airports' stations, MeteoAlarm and the Italian Civil Protection.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "common/mcp_server.h"
+#include "weather.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+static const char INSTRUCTIONS[] =
+ "Use these tools by yourself whenever the user asks about the weather, "
+ "the temperature, rain, wind, the sea and its waves, or weather "
+ "warnings, now or in the next days: the user does not need to name "
+ "them or ask for them. In your reply never name the tools, the server "
+ "or the service: just give the answer, with the sources the tool "
+ "lists. Tell the user what the tools return, in the user's language, "
+ "without adding figures of your own: they already give the times in "
+ "the place's local time and the wind and the sea in words. A forecast "
+ "is a model's value and a station's is a measure: say which is which "
+ "when both are given, and when they disagree say so. For a sea as a "
+ "whole use weather_sea with its name; for warnings use weather_alerts, "
+ "and say plainly when there is none. When the user names no place, "
+ "give none: the tools take where the user is and say how they know "
+ "it; tell the user which place that is, and that it may be off.";
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "usage: janas-weather\n"
+ "An MCP server over stdio: a client starts it and calls its\n"
+ "tools - weather_now (the weather now at a place, with what\n"
+ "the nearest station measured), weather_forecast (by the day\n"
+ "and by the hour), weather_sea (waves, swell, the water, the\n"
+ "wind, over a sea or off a place) and weather_alerts (the\n"
+ "warnings in force; in Italy the Civil Protection's levels).\n"
+ "Data, all free and without a key: Open-Meteo (CC BY 4.0;\n"
+ "free for non-commercial use), MET Norway (CC BY 4.0) when\n"
+ "Open-Meteo does not answer, the airports' METAR from\n"
+ "aviationweather.gov (NOAA), MeteoAlarm (EUMETNET) and the\n"
+ "Dipartimento della Protezione Civile (CC BY 4.0); places\n"
+ "from GeoNames (CC BY 4.0) and Natural Earth.\n"
+ "janas-chat starts it by itself when it is beside it.\n"
+ "Configured in a client as, for instance:\n"
+ " {\"mcpServers\": {\"weather\": {\"command\": "
+ "\"janas-weather\"}}}\n");
+}
+
+int main(int argc, char **argv)
+{
+ for (int i = 1; i < argc; i++) {
+ usage();
+ return strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 ? 0
+ : 2;
+ }
+ struct janas_mcps srv = {.name = "janas-weather",
+ .version = JANAS_VERSION,
+ .instructions = INSTRUCTIONS,
+ .tools_list = wx_tools_list,
+ .tools_call = wx_tools_call};
+ if (janas_mcps_open(&srv) != 0) {
+ fprintf(stderr, "janas-weather: cannot set its output aside\n");
+ return 1;
+ }
+ fprintf(stderr,
+ "janas-weather %s: ready, 4 tools (weather_now, "
+ "weather_forecast, weather_sea, weather_alerts)\n",
+ JANAS_VERSION);
+ janas_mcps_run(&srv);
+ wx_fetch_free();
+ return 0;
+}
diff --git a/src/weather/metar.c b/src/weather/metar.c
new file mode 100644
index 0000000..26703a5
--- /dev/null
+++ b/src/weather/metar.c
@@ -0,0 +1,159 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * metar.c - what a station measured (see weather.h): the METAR of the
+ * airports, the hourly observations pilots read, from the Aviation Weather
+ * Center of the United States' weather service (aviationweather.gov, no
+ * key, public domain). A forecast is a model's value at a cell of its
+ * grid; this is a thermometer and an anemometer at a known place and
+ * minute, the measure to set the forecast against.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common/geo.h"
+#include "weather.h"
+
+#define METAR_KEEP_S 600 /* a METAR comes every half hour or hour */
+
+static double obs_num(const struct janas_json *o, const char *k)
+{
+ const struct janas_json *v = janas_json_get(o, k);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, NAN) : NAN;
+}
+
+static const char *cover_words(const char *c)
+{
+ static const struct {
+ const char *code, *words;
+ } w[] = {{"FEW", "few clouds"},
+ {"SCT", "scattered clouds"},
+ {"BKN", "broken clouds"},
+ {"OVC", "overcast"},
+ {"VV", "sky obscured"},
+ {"CLR", "clear"},
+ {"SKC", "clear"},
+ {"NSC", "no significant cloud"},
+ {"NCD", "no cloud detected"},
+ {"CAVOK", "no significant cloud"}};
+ for (size_t i = 0; i < sizeof w / sizeof w[0]; i++)
+ if (c && strcmp(c, w[i].code) == 0)
+ return w[i].words;
+ return c ? c : "";
+}
+
+static void clouds_of(const struct janas_json *cl, char *out, size_t cap)
+{
+ size_t n = 0;
+ out[0] = 0;
+ for (const struct janas_json *c =
+ cl && cl->type == JANAS_JSON_ARRAY ? cl->child : NULL;
+ c && n < cap; c = c->next) {
+ const char *cov = janas_json_str(janas_json_get(c, "cover"));
+ double base = obs_num(c, "base");
+ n += (size_t)snprintf(out + n, cap - n, "%s%s", n ? ", " : "",
+ cover_words(cov));
+ if (!isnan(base) && n < cap)
+ n += (size_t)snprintf(out + n, cap - n, " at %.0f ft (%.0f m)",
+ base, base * 0.3048);
+ }
+}
+
+int wx_metar_parse(const char *text, size_t len, double lat, double lon,
+ double max_km, struct wx_obs *o, char *err, size_t err_len)
+{
+ struct janas_buf b = {.p = (char *)text, .n = len};
+ if (len == 0) /* no station reported in the box */
+ return 0;
+ struct janas_json_doc *d =
+ wx_parse(&b, "aviationweather.gov", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *r = janas_json_root(d);
+ const struct janas_json *best = NULL;
+ double best_km = max_km;
+ for (const struct janas_json *m =
+ r && r->type == JANAS_JSON_ARRAY ? r->child : NULL;
+ m; m = m->next) {
+ double la = obs_num(m, "lat"), lo = obs_num(m, "lon");
+ if (isnan(la) || isnan(lo) || isnan(obs_num(m, "temp")))
+ continue;
+ double km = geo_km(lat, lon, la, lo);
+ if (km <= best_km) {
+ best = m;
+ best_km = km;
+ }
+ }
+ int found = 0;
+ if (best) {
+ memset(o, 0, sizeof *o);
+ snprintf(o->icao, sizeof o->icao, "%s",
+ janas_json_str(janas_json_get(best, "icaoId"))
+ ? janas_json_str(janas_json_get(best, "icaoId"))
+ : "");
+ snprintf(o->name, sizeof o->name, "%s",
+ janas_json_str(janas_json_get(best, "name"))
+ ? janas_json_str(janas_json_get(best, "name"))
+ : "");
+ o->lat = obs_num(best, "lat");
+ o->lon = obs_num(best, "lon");
+ o->km = best_km;
+ o->at = (time_t)obs_num(best, "obsTime");
+ o->temp = obs_num(best, "temp");
+ o->dew = obs_num(best, "dewp");
+ const struct janas_json *wd = janas_json_get(best, "wdir");
+ o->variable_wind = janas_json_is(wd, "VRB");
+ o->wind_dir = obs_num(best, "wdir");
+ o->wind_kt = obs_num(best, "wspd");
+ o->gust_kt = obs_num(best, "wgst");
+ o->pressure = obs_num(best, "altim");
+ const struct janas_json *vis = janas_json_get(best, "visib");
+ if (janas_json_str(vis))
+ snprintf(o->visib, sizeof o->visib, "%s", janas_json_str(vis));
+ else if (vis && vis->type == JANAS_JSON_NUMBER)
+ snprintf(o->visib, sizeof o->visib, "%.2f",
+ fmin(fmax(janas_json_num(vis, 0), 0), 99));
+ snprintf(o->wx, sizeof o->wx, "%s",
+ janas_json_str(janas_json_get(best, "wxString"))
+ ? janas_json_str(janas_json_get(best, "wxString"))
+ : "");
+ clouds_of(janas_json_get(best, "clouds"), o->clouds, sizeof o->clouds);
+ snprintf(o->raw, sizeof o->raw, "%s",
+ janas_json_str(janas_json_get(best, "rawOb"))
+ ? janas_json_str(janas_json_get(best, "rawOb"))
+ : "");
+ found = 1;
+ }
+ janas_json_free(d);
+ return found;
+}
+
+int wx_metar_near(double lat, double lon, double max_km, struct wx_obs *o,
+ char *err, size_t err_len)
+{
+ double dlat = max_km / 111.0;
+ double dlon = max_km / (111.0 * fmax(cos(lat * M_PI / 180), 0.05));
+ char url[256];
+ snprintf(url, sizeof url,
+ "https://aviationweather.gov/api/data/metar?bbox=%.2f,%.2f,%.2f,"
+ "%.2f&format=json",
+ lat - dlat, lon - dlon, lat + dlat, lon + dlon);
+ struct janas_buf b = {0};
+ char why[256];
+ int status = wx_fetch(url, METAR_KEEP_S, 0, &b, why, sizeof why);
+ int r;
+ if (status == 200 || status == 204)
+ r = wx_metar_parse(b.p ? b.p : "", b.n, lat, lon, max_km, o, err,
+ err_len);
+ else if (status < 0) {
+ snprintf(err, err_len, "aviationweather.gov did not answer: %s", why);
+ r = -1;
+ } else {
+ snprintf(err, err_len, "aviationweather.gov: HTTP %d", status);
+ r = -1;
+ }
+ janas_buf_free(&b);
+ return r;
+}
diff --git a/src/weather/metno.c b/src/weather/metno.c
new file mode 100644
index 0000000..1bc155d
--- /dev/null
+++ b/src/weather/metno.c
@@ -0,0 +1,211 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * metno.c - MET Norway's locationforecast (see weather.h), when Open-Meteo
+ * does not answer: free for any use under CC BY 4.0, asked with a
+ * User-Agent naming the program. Its series is in UTC, by the hour for the
+ * first two days and by six hours after; it is put into the place's own
+ * zone, its hours into days. It has no gusts, no chance of rain and no
+ * sunrise in its compact form: those are left unknown.
+ */
+#define _GNU_SOURCE /* timegm */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "weather.h"
+
+#define MET_KEEP_S 900
+
+static double det(const struct janas_json *d, const char *k)
+{
+ const struct janas_json *v = janas_json_get(d, k);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, NAN) : NAN;
+}
+
+/* "2026-10-01T11:00:00Z" */
+static time_t utc_of(const char *s)
+{
+ struct tm tm = {0};
+ if (!s || sscanf(s, "%d-%d-%dT%d:%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
+ &tm.tm_hour, &tm.tm_min) != 5)
+ return (time_t)-1;
+ tm.tm_year -= 1900;
+ tm.tm_mon -= 1;
+ return timegm(&tm);
+}
+
+static void symbol_of(const struct janas_json *next, char *out, size_t cap)
+{
+ const char *s = janas_json_str(
+ janas_json_get(janas_json_get(next, "summary"), "symbol_code"));
+ snprintf(out, cap, "%s", s ? s : "");
+}
+
+static void max_in(double *m, double v)
+{
+ if (!isnan(v) && (isnan(*m) || v > *m))
+ *m = v;
+}
+
+static void min_in(double *m, double v)
+{
+ if (!isnan(v) && (isnan(*m) || v < *m))
+ *m = v;
+}
+
+int wx_met_parse(const char *text, size_t n, const char *tz,
+ struct wx_forecast *f, char *err, size_t err_len)
+{
+ memset(f, 0, sizeof *f);
+ f->source = "MET Norway";
+ struct janas_buf b = {.p = (char *)text, .n = n};
+ struct janas_json_doc *d = wx_parse(&b, "MET Norway", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *r = janas_json_root(d);
+ const struct janas_json *coords =
+ janas_json_get(janas_json_get(r, "geometry"), "coordinates");
+ const struct janas_json *ts =
+ janas_json_get(janas_json_get(r, "properties"), "timeseries");
+ if (!ts || ts->type != JANAS_JSON_ARRAY || !ts->child) {
+ snprintf(err, err_len, "MET Norway: an answer without a forecast");
+ janas_json_free(d);
+ return -1;
+ }
+ if (coords && coords->type == JANAS_JSON_ARRAY && coords->child) {
+ f->grid_lon = janas_json_num(coords->child, NAN);
+ f->grid_lat = coords->child->next
+ ? janas_json_num(coords->child->next, NAN)
+ : NAN;
+ f->grid_elev = coords->child->next && coords->child->next->next
+ ? janas_json_num(coords->child->next->next, NAN)
+ : NAN;
+ }
+ snprintf(f->tz, sizeof f->tz, "%s", tz && *tz ? tz : "UTC");
+
+ /* the series is put into the place's zone */
+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;
+ setenv("TZ", f->tz, 1);
+ tzset();
+ time_t prev_day_t = 0;
+ for (const struct janas_json *e = ts->child; e; e = e->next) {
+ time_t t = utc_of(janas_json_str(janas_json_get(e, "time")));
+ if (t == (time_t)-1)
+ continue;
+ struct tm lt;
+ localtime_r(&t, &lt);
+ const struct janas_json *data = janas_json_get(e, "data");
+ const struct janas_json *in =
+ janas_json_get(janas_json_get(data, "instant"), "details");
+ const struct janas_json *n1 = janas_json_get(data, "next_1_hours");
+ const struct janas_json *n6 = janas_json_get(data, "next_6_hours");
+ const struct janas_json *n12 = janas_json_get(data, "next_12_hours");
+ double temp = det(in, "air_temperature");
+ double wind = det(in, "wind_speed") * 3.6; /* m/s */
+ double dir = det(in, "wind_from_direction");
+ double rain1 =
+ det(janas_json_get(n1, "details"), "precipitation_amount");
+ double rain6 =
+ det(janas_json_get(n6, "details"), "precipitation_amount");
+ if (!f->has_now) {
+ struct wx_now *w = &f->now;
+ strftime(w->time, sizeof w->time, "%Y-%m-%dT%H:%M", &lt);
+ w->temp = temp;
+ w->feels = NAN;
+ w->humidity = det(in, "relative_humidity");
+ w->cloud = det(in, "cloud_area_fraction");
+ w->pressure = det(in, "air_pressure_at_sea_level");
+ w->wind = wind;
+ w->wind_dir = dir;
+ w->gust = NAN;
+ w->precip = rain1;
+ w->code = -1;
+ symbol_of(n1 ? n1 : n6, w->symbol, sizeof w->symbol);
+ f->has_now = 1;
+ snprintf(f->tz_abbr, sizeof f->tz_abbr, "%s", lt.tm_zone);
+ }
+ if (n1 && f->n_hour < WX_HOURS) {
+ struct wx_hour *h = &f->hour[f->n_hour++];
+ strftime(h->time, sizeof h->time, "%Y-%m-%dT%H:%M", &lt);
+ h->temp = temp;
+ h->rain = rain1;
+ h->rain_prob = NAN;
+ h->wind = wind;
+ h->wind_dir = dir;
+ h->gust = NAN;
+ h->code = -1;
+ symbol_of(n1, h->symbol, sizeof h->symbol);
+ }
+ char date[11];
+ strftime(date, sizeof date, "%Y-%m-%d", &lt);
+ struct wx_day *y = f->n_day ? &f->day[f->n_day - 1] : NULL;
+ if (!y || strcmp(y->date, date) != 0) {
+ if (f->n_day == WX_DAYS)
+ break;
+ y = &f->day[f->n_day++];
+ memset(y, 0, sizeof *y);
+ snprintf(y->date, sizeof y->date, "%s", date);
+ y->code = -1;
+ y->tmin = y->tmax = y->rain = y->wind = y->wind_dir = NAN;
+ y->gust = y->rain_prob = y->uv = NAN;
+ y->rain = 0;
+ }
+ min_in(&y->tmin, temp);
+ max_in(&y->tmax, temp);
+ if (isnan(y->wind) || wind > y->wind) {
+ y->wind = wind;
+ y->wind_dir = dir;
+ }
+ /* the rain: an hour's while the series is by the hour, six
+ hours' after */
+ const struct janas_json *nx = e->next;
+ time_t tn = nx ? utc_of(janas_json_str(janas_json_get(nx, "time")))
+ : (time_t)-1;
+ if (!isnan(rain1) && tn != (time_t)-1 && tn - t <= 3600)
+ y->rain += rain1;
+ else if (!isnan(rain6) && t - prev_day_t >= 6 * 3600) {
+ y->rain += rain6;
+ prev_day_t = t;
+ }
+ /* the day's sky: the next twelve hours' from the morning */
+ if (!y->symbol[0] && n12 && lt.tm_hour >= 6)
+ symbol_of(n12, y->symbol, sizeof y->symbol);
+ }
+ if (old) {
+ setenv("TZ", old, 1);
+ free(old);
+ } else {
+ unsetenv("TZ");
+ }
+ tzset();
+ janas_json_free(d);
+ return 0;
+}
+
+int wx_met_forecast(const struct wx_place *p, int days, struct wx_forecast *f,
+ char *err, size_t err_len)
+{
+ char url[256];
+ /* four decimals at most, as MET Norway asks: more are refused */
+ snprintf(url, sizeof url,
+ "https://api.met.no/weatherapi/locationforecast/2.0/compact?"
+ "lat=%.4f&lon=%.4f",
+ p->lat, p->lon);
+ struct janas_buf b = {0};
+ char why[256];
+ int status = wx_fetch(url, MET_KEEP_S, 1, &b, why, sizeof why);
+ int r = -1;
+ if (status == 200)
+ r = wx_met_parse(b.p, b.n, p->tz, f, err, err_len);
+ else if (status < 0)
+ snprintf(err, err_len, "MET Norway did not answer: %s", why);
+ else
+ snprintf(err, err_len, "MET Norway: HTTP %d", status);
+ janas_buf_free(&b);
+ if (r == 0 && f->n_day > days)
+ f->n_day = days;
+ return r;
+}
diff --git a/src/weather/openmeteo.c b/src/weather/openmeteo.c
new file mode 100644
index 0000000..136ce06
--- /dev/null
+++ b/src/weather/openmeteo.c
@@ -0,0 +1,394 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * openmeteo.c - Open-Meteo's forecasts (see weather.h): the weather now,
+ * by the day and by the hour at a place, and the sea at a few points.
+ * Free for non-commercial use, no key, its data under CC BY 4.0. Its
+ * values are a model's, at the cell of its grid nearest the place - on
+ * land, asked so - not a station's measures.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "weather.h"
+
+#define OM_KEEP_S 900 /* a forecast changes once an hour at most */
+
+/* The numbers of a JSON array, NAN for a null; how many, at most max. */
+static int nums(const struct janas_json *a, double *out, int max)
+{
+ int n = 0;
+ for (const struct janas_json *v =
+ a && a->type == JANAS_JSON_ARRAY ? a->child : NULL;
+ v && n < max; v = v->next)
+ out[n++] = v->type == JANAS_JSON_NUMBER ? janas_json_num(v, NAN) : NAN;
+ return n;
+}
+
+static double num(const struct janas_json *o, const char *k)
+{
+ const struct janas_json *v = janas_json_get(o, k);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, NAN) : NAN;
+}
+
+static void str_at(const struct janas_json *a, int i, char *out, size_t cap)
+{
+ const struct janas_json *v =
+ a && a->type == JANAS_JSON_ARRAY ? a->child : NULL;
+ while (v && i-- > 0)
+ v = v->next;
+ snprintf(out, cap, "%s", v && janas_json_str(v) ? janas_json_str(v) : "");
+}
+
+static void hhmm(const struct janas_json *a, int i, char *out, size_t cap)
+{
+ char t[24];
+ str_at(a, i, t, sizeof t); /* "2026-10-01T07:05" */
+ const char *T = strchr(t, 'T');
+ snprintf(out, cap, "%.5s", T ? T + 1 : "");
+}
+
+static void tz_of(const struct janas_json *r, struct wx_forecast *f)
+{
+ snprintf(f->tz, sizeof f->tz, "%s",
+ janas_json_str(janas_json_get(r, "timezone"))
+ ? janas_json_str(janas_json_get(r, "timezone"))
+ : "");
+ snprintf(f->tz_abbr, sizeof f->tz_abbr, "%s",
+ janas_json_str(janas_json_get(r, "timezone_abbreviation"))
+ ? janas_json_str(janas_json_get(r, "timezone_abbreviation"))
+ : "");
+}
+
+static int error_of(const struct janas_json *r, char *err, size_t err_len)
+{
+ const struct janas_json *e = janas_json_get(r, "error");
+ if (!e || e->type != JANAS_JSON_TRUE)
+ return 0;
+ const char *why = janas_json_str(janas_json_get(r, "reason"));
+ snprintf(err, err_len, "Open-Meteo: %s", why ? why : "an error");
+ return 1;
+}
+
+int wx_om_parse(const char *text, size_t n, struct wx_forecast *f, char *err,
+ size_t err_len)
+{
+ memset(f, 0, sizeof *f);
+ f->source = "Open-Meteo";
+ struct janas_buf b = {.p = (char *)text, .n = n};
+ struct janas_json_doc *d = wx_parse(&b, "Open-Meteo", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *r = janas_json_root(d);
+ if (error_of(r, err, err_len)) {
+ janas_json_free(d);
+ return -1;
+ }
+ f->grid_lat = num(r, "latitude");
+ f->grid_lon = num(r, "longitude");
+ f->grid_elev = num(r, "elevation");
+ tz_of(r, f);
+
+ const struct janas_json *c = janas_json_get(r, "current");
+ if (c && c->type == JANAS_JSON_OBJECT) {
+ struct wx_now *w = &f->now;
+ snprintf(w->time, sizeof w->time, "%s",
+ janas_json_str(janas_json_get(c, "time"))
+ ? janas_json_str(janas_json_get(c, "time"))
+ : "");
+ w->temp = num(c, "temperature_2m");
+ w->feels = num(c, "apparent_temperature");
+ w->humidity = num(c, "relative_humidity_2m");
+ w->precip = num(c, "precipitation");
+ w->cloud = num(c, "cloud_cover");
+ w->pressure = num(c, "pressure_msl");
+ w->wind = num(c, "wind_speed_10m");
+ w->wind_dir = num(c, "wind_direction_10m");
+ w->gust = num(c, "wind_gusts_10m");
+ double code = num(c, "weather_code");
+ w->code = isnan(code) ? -1 : (int)code;
+ w->is_day = num(c, "is_day") == 1;
+ f->has_now = 1;
+ }
+
+ const struct janas_json *dl = janas_json_get(r, "daily");
+ if (dl && dl->type == JANAS_JSON_OBJECT) {
+ double v[10][WX_DAYS];
+ static const char *const k[10] = {"weather_code",
+ "temperature_2m_min",
+ "temperature_2m_max",
+ "precipitation_sum",
+ "precipitation_probability_max",
+ "wind_speed_10m_max",
+ "wind_gusts_10m_max",
+ "wind_direction_10m_dominant",
+ "uv_index_max",
+ NULL};
+ int nd = nums(janas_json_get(dl, "time"), v[9], WX_DAYS);
+ for (int i = 0; i < 9; i++)
+ for (int j = nums(janas_json_get(dl, k[i]), v[i], WX_DAYS); j < nd;
+ j++)
+ v[i][j] = NAN;
+ for (int i = 0; i < nd; i++) {
+ struct wx_day *y = &f->day[i];
+ str_at(janas_json_get(dl, "time"), i, y->date, sizeof y->date);
+ y->code = isnan(v[0][i]) ? -1 : (int)v[0][i];
+ y->tmin = v[1][i];
+ y->tmax = v[2][i];
+ y->rain = v[3][i];
+ y->rain_prob = v[4][i];
+ y->wind = v[5][i];
+ y->gust = v[6][i];
+ y->wind_dir = v[7][i];
+ y->uv = v[8][i];
+ hhmm(janas_json_get(dl, "sunrise"), i, y->sunrise,
+ sizeof y->sunrise);
+ hhmm(janas_json_get(dl, "sunset"), i, y->sunset, sizeof y->sunset);
+ }
+ f->n_day = nd;
+ }
+
+ const struct janas_json *hl = janas_json_get(r, "hourly");
+ if (hl && hl->type == JANAS_JSON_OBJECT) {
+ double v[8][WX_HOURS];
+ static const char *const k[8] = {
+ "weather_code", "temperature_2m",
+ "precipitation", "precipitation_probability",
+ "wind_speed_10m", "wind_direction_10m",
+ "wind_gusts_10m", NULL};
+ int nh = nums(janas_json_get(hl, "time"), v[7], WX_HOURS);
+ for (int i = 0; i < 7; i++)
+ for (int j = nums(janas_json_get(hl, k[i]), v[i], WX_HOURS); j < nh;
+ j++)
+ v[i][j] = NAN;
+ for (int i = 0; i < nh; i++) {
+ struct wx_hour *h = &f->hour[i];
+ str_at(janas_json_get(hl, "time"), i, h->time, sizeof h->time);
+ h->code = isnan(v[0][i]) ? -1 : (int)v[0][i];
+ h->temp = v[1][i];
+ h->rain = v[2][i];
+ h->rain_prob = v[3][i];
+ h->wind = v[4][i];
+ h->wind_dir = v[5][i];
+ h->gust = v[6][i];
+ }
+ f->n_hour = nh;
+ }
+ janas_json_free(d);
+ if (!f->has_now && !f->n_day) {
+ snprintf(err, err_len, "Open-Meteo: an answer without a forecast");
+ return -1;
+ }
+ return 0;
+}
+
+int wx_om_forecast(const struct wx_place *p, int days, struct wx_forecast *f,
+ char *err, size_t err_len)
+{
+ if (days < 1)
+ days = 1;
+ if (days > WX_DAYS)
+ days = WX_DAYS;
+ /* the place's zone when known: "auto" gives a sea's nautical one */
+ char tz[96] = "auto";
+ if (p->tz[0]) {
+ size_t k = 0;
+ for (const char *c = p->tz; *c && k + 4 < sizeof tz; c++)
+ k += (size_t)snprintf(tz + k, sizeof tz - k,
+ *c == '/' ? "%%2F" : "%c", *c);
+ }
+ char url[1536];
+ snprintf(url, sizeof url,
+ "https://api.open-meteo.com/v1/forecast?latitude=%.4f&"
+ "longitude=%.4f&cell_selection=land&current=temperature_2m,"
+ "relative_humidity_2m,apparent_temperature,precipitation,"
+ "weather_code,cloud_cover,pressure_msl,wind_speed_10m,"
+ "wind_direction_10m,wind_gusts_10m,is_day&hourly=weather_code,"
+ "temperature_2m,precipitation,precipitation_probability,"
+ "wind_speed_10m,wind_direction_10m,wind_gusts_10m&daily="
+ "weather_code,temperature_2m_min,temperature_2m_max,"
+ "precipitation_sum,precipitation_probability_max,"
+ "wind_speed_10m_max,wind_gusts_10m_max,"
+ "wind_direction_10m_dominant,uv_index_max,sunrise,sunset&"
+ "timezone=%s&forecast_days=%d&forecast_hours=%d",
+ p->lat, p->lon, tz, days, WX_HOURS);
+ struct janas_buf b = {0};
+ char why[256];
+ int status = wx_fetch(url, OM_KEEP_S, 0, &b, why, sizeof why);
+ int r;
+ if (status < 0) {
+ snprintf(err, err_len, "Open-Meteo did not answer: %s", why);
+ r = -1;
+ } else {
+ r = wx_om_parse(b.p ? b.p : "", b.n, f, err, err_len);
+ if (r == 0 && status != 200) {
+ snprintf(err, err_len, "Open-Meteo: HTTP %d", status);
+ r = -1;
+ }
+ }
+ janas_buf_free(&b);
+ return r;
+}
+
+/* The answer for n points: an array of them, or the one object. */
+static const struct janas_json *point(const struct janas_json *r, int i, int n)
+{
+ if (r && r->type == JANAS_JSON_OBJECT)
+ return n == 1 && i == 0 ? r : NULL;
+ const struct janas_json *v =
+ r && r->type == JANAS_JSON_ARRAY ? r->child : NULL;
+ while (v && i-- > 0)
+ v = v->next;
+ return v;
+}
+
+int wx_om_marine_parse(const char *text, size_t len, struct wx_sea *s, int n,
+ char *err, size_t err_len)
+{
+ struct janas_buf b = {.p = (char *)text, .n = len};
+ struct janas_json_doc *d = wx_parse(&b, "Open-Meteo", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *r = janas_json_root(d);
+ if (r->type == JANAS_JSON_OBJECT && error_of(r, err, err_len)) {
+ janas_json_free(d);
+ return -1;
+ }
+ for (int i = 0; i < n; i++) {
+ const struct janas_json *o = point(r, i, n);
+ const struct janas_json *c = janas_json_get(o, "current");
+ s[i].cell_lat = num(o, "latitude");
+ s[i].cell_lon = num(o, "longitude");
+ s[i].wave = num(c, "wave_height");
+ s[i].wave_dir = num(c, "wave_direction");
+ s[i].period = num(c, "wave_period");
+ s[i].wind_wave = num(c, "wind_wave_height");
+ s[i].swell = num(c, "swell_wave_height");
+ s[i].swell_dir = num(c, "swell_wave_direction");
+ s[i].sst = num(c, "sea_surface_temperature");
+ snprintf(s[i].time, sizeof s[i].time, "%s",
+ janas_json_str(janas_json_get(c, "time"))
+ ? janas_json_str(janas_json_get(c, "time"))
+ : "");
+ s[i].ok = !isnan(s[i].wave);
+ const struct janas_json *dl = janas_json_get(o, "daily");
+ double v[3][WX_DAYS];
+ int nd = nums(janas_json_get(dl, "time"), v[0], WX_DAYS);
+ int a = nums(janas_json_get(dl, "wave_height_max"), v[0], WX_DAYS);
+ int bdir =
+ nums(janas_json_get(dl, "wave_direction_dominant"), v[1], WX_DAYS);
+ int c3 = nums(janas_json_get(dl, "wave_period_max"), v[2], WX_DAYS);
+ for (int j = 0; j < nd; j++) {
+ struct wx_sea_day *y = &s[i].day[j];
+ str_at(janas_json_get(dl, "time"), j, y->date, sizeof y->date);
+ y->wave_max = j < a ? v[0][j] : NAN;
+ y->wave_dir = j < bdir ? v[1][j] : NAN;
+ y->period_max = j < c3 ? v[2][j] : NAN;
+ y->wind_max = y->gust_max = y->wind_dir = NAN;
+ }
+ s[i].n_day = nd;
+ }
+ janas_json_free(d);
+ return 0;
+}
+
+int wx_om_wind_parse(const char *text, size_t len, struct wx_sea *s, int n,
+ char *err, size_t err_len)
+{
+ struct janas_buf b = {.p = (char *)text, .n = len};
+ struct janas_json_doc *d = wx_parse(&b, "Open-Meteo", err, err_len);
+ if (!d)
+ return -1;
+ const struct janas_json *r = janas_json_root(d);
+ if (r->type == JANAS_JSON_OBJECT && error_of(r, err, err_len)) {
+ janas_json_free(d);
+ return -1;
+ }
+ for (int i = 0; i < n; i++) {
+ const struct janas_json *o = point(r, i, n);
+ const struct janas_json *c = janas_json_get(o, "current");
+ s[i].wind = num(c, "wind_speed_10m");
+ s[i].wind_dir = num(c, "wind_direction_10m");
+ s[i].gust = num(c, "wind_gusts_10m");
+ const struct janas_json *dl = janas_json_get(o, "daily");
+ double v[3][WX_DAYS];
+ int a = nums(janas_json_get(dl, "wind_speed_10m_max"), v[0], WX_DAYS);
+ int g = nums(janas_json_get(dl, "wind_gusts_10m_max"), v[1], WX_DAYS);
+ int w = nums(janas_json_get(dl, "wind_direction_10m_dominant"), v[2],
+ WX_DAYS);
+ for (int j = 0; j < s[i].n_day; j++) {
+ s[i].day[j].wind_max = j < a ? v[0][j] : NAN;
+ s[i].day[j].gust_max = j < g ? v[1][j] : NAN;
+ s[i].day[j].wind_dir = j < w ? v[2][j] : NAN;
+ }
+ }
+ janas_json_free(d);
+ return 0;
+}
+
+static void url_tz(struct janas_buf *u, const char *tz)
+{
+ for (const char *c = tz && *tz ? tz : "GMT"; *c; c++)
+ if (*c == '/')
+ janas_buf_puts(u, "%2F");
+ else
+ janas_buf_put(u, c, 1);
+}
+
+int wx_om_marine(struct wx_sea *s, int n, int days, const char *tz, char *err,
+ size_t err_len)
+{
+ if (days < 1)
+ days = 1;
+ if (days > 8) /* the sea model's reach */
+ days = 8;
+ struct janas_buf la = {0}, lo = {0};
+ for (int i = 0; i < n; i++) {
+ janas_buf_printf(&la, "%s%.3f", i ? "," : "", s[i].lat);
+ janas_buf_printf(&lo, "%s%.3f", i ? "," : "", s[i].lon);
+ }
+ struct janas_buf u = {0}, b = {0};
+ janas_buf_printf(&u,
+ "https://marine-api.open-meteo.com/v1/marine?latitude=%s&"
+ "longitude=%s&current=wave_height,wave_direction,"
+ "wave_period,wind_wave_height,swell_wave_height,"
+ "swell_wave_direction,sea_surface_temperature&daily="
+ "wave_height_max,wave_direction_dominant,wave_period_max&"
+ "forecast_days=%d&timezone=",
+ la.p ? la.p : "", lo.p ? lo.p : "", days);
+ url_tz(&u, tz);
+ janas_buf_put(&u, "", 1);
+ u.n--;
+ for (int i = 0; i < n; i++)
+ s[i].wind = s[i].wind_dir = s[i].gust = NAN;
+ char why[256];
+ int r = -1;
+ int status = u.oom ? -1 : wx_fetch(u.p, OM_KEEP_S, 0, &b, why, sizeof why);
+ if (status == 200)
+ r = wx_om_marine_parse(b.p, b.n, s, n, err, err_len);
+ else if (status < 0)
+ snprintf(err, err_len, "Open-Meteo did not answer: %s", why);
+ else
+ snprintf(err, err_len, "Open-Meteo: HTTP %d", status);
+ u.n = 0;
+ janas_buf_printf(&u,
+ "https://api.open-meteo.com/v1/forecast?latitude=%s&"
+ "longitude=%s&current=wind_speed_10m,wind_direction_10m,"
+ "wind_gusts_10m&daily=wind_speed_10m_max,"
+ "wind_gusts_10m_max,wind_direction_10m_dominant&"
+ "forecast_days=%d&timezone=",
+ la.p ? la.p : "", lo.p ? lo.p : "", days);
+ url_tz(&u, tz);
+ janas_buf_put(&u, "", 1);
+ /* without the wind, the waves alone */
+ if (r == 0 && !u.oom &&
+ wx_fetch(u.p, OM_KEEP_S, 0, &b, why, sizeof why) == 200)
+ wx_om_wind_parse(b.p, b.n, s, n, why, sizeof why);
+ janas_buf_free(&la);
+ janas_buf_free(&lo);
+ janas_buf_free(&u);
+ janas_buf_free(&b);
+ return r;
+}
diff --git a/src/weather/place.c b/src/weather/place.c
new file mode 100644
index 0000000..e97bc75
--- /dev/null
+++ b/src/weather/place.c
@@ -0,0 +1,303 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * place.c - a place by its name (see weather.h): Open-Meteo's geocoding,
+ * from GeoNames, which knows the names in Italian and in English
+ * ("Trapani", "Firenze", "Florence"), the municipality's region and
+ * province, its zone and height; an airport by its code, or a point, from
+ * the tables built into the program, which also stand in when the
+ * geocoding does not answer.
+ */
+#define _GNU_SOURCE /* strcasestr */
+#include <ctype.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+#include "common/geo.h"
+#include "weather.h"
+
+#define DEG(x) ((x) * 1e-5)
+#define PLACE_KEEP_S (7 * 24 * 3600) /* places do not move */
+
+static void copy(char *to, size_t cap, const char *s)
+{
+ snprintf(to, cap, "%s", s ? s : "");
+}
+
+static void url_put(struct janas_buf *b, const char *s, size_t n)
+{
+ static const char hex[] = "0123456789ABCDEF";
+ for (size_t i = 0; i < n; i++) {
+ unsigned char c = (unsigned char)s[i];
+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
+ janas_buf_put(b, (const char *)&c, 1);
+ else
+ janas_buf_printf(b, "%%%c%c", hex[c >> 4], hex[c & 15]);
+ }
+}
+
+/*
+ * The names of the tables are in English (Sicily, Turin); MeteoAlarm's
+ * regions and the Civil Protection's municipalities are in the country's
+ * language (Sicilia, Torino). The geocoding's place called as the city of
+ * the tables, when it lies within 30 km of the point, gives them: its
+ * region and province, and with rename its name too.
+ */
+static int find_named(const char *query, double near_lat, double near_lon,
+ struct wx_place *p, char *err, size_t err_len);
+
+static void localize(struct wx_place *p, const char *city, int rename)
+{
+ struct wx_place q;
+ char err[256];
+ if (!city || !*city ||
+ find_named(city, p->lat, p->lon, &q, err, sizeof err) != 0 ||
+ geo_km(p->lat, p->lon, q.lat, q.lon) > 30 ||
+ (p->cc[0] && strcasecmp(p->cc, q.cc) != 0))
+ return;
+ if (q.region[0])
+ copy(p->region, sizeof p->region, q.region);
+ if (q.area2[0])
+ copy(p->area2, sizeof p->area2, q.area2);
+ if (q.country[0])
+ copy(p->country, sizeof p->country, q.country);
+ if (rename)
+ copy(p->name, sizeof p->name, q.name);
+}
+
+void wx_place_at(double lat, double lon, struct wx_place *p)
+{
+ memset(p, 0, sizeof *p);
+ p->lat = lat;
+ p->lon = lon;
+ p->elevation = NAN;
+ double km;
+ const struct geo_city *c = geo_city_near(lat, lon, &km);
+ if (geo_sea_at(lat, lon) || !c) {
+ /* "the Tyrrhenian Sea, between ...; 39 km N of Trapani" */
+ struct janas_buf b = {0};
+ geo_describe(lat, lon, &b);
+ const char *s = b.p ? b.p : "";
+ copy(p->name, sizeof p->name, strncmp(s, "over ", 5) == 0 ? s + 5 : s);
+ janas_buf_free(&b);
+ const struct geo_airport *a = geo_airport_near(lat, lon, &km);
+ if (a)
+ copy(p->tz, sizeof p->tz, geo_tz_name(a->tz));
+ return;
+ }
+ if (km < 3)
+ copy(p->name, sizeof p->name, c->name);
+ else
+ snprintf(p->name, sizeof p->name, "%.0f km %s of %s", km,
+ geo_compass(geo_bearing(DEG(c->lat), DEG(c->lon), lat, lon)),
+ c->name);
+ if (c->region != 0xFFFF)
+ copy(p->region, sizeof p->region, geo_region_name(c->region));
+ copy(p->country, sizeof p->country, geo_country_name(c->country));
+ copy(p->cc, sizeof p->cc, geo_country_iso2(c->country));
+ copy(p->tz, sizeof p->tz, geo_tz_name(c->tz));
+ localize(p, c->name, km < 3);
+}
+
+static int from_tables(const char *q, struct wx_place *p)
+{
+ size_t n = strlen(q);
+ int code = (n == 3 || n == 4);
+ for (size_t i = 0; code && i < n; i++)
+ code = isupper((unsigned char)q[i]) != 0;
+ const struct geo_airport *a = code ? geo_airport_find(q) : NULL;
+ if (a) {
+ memset(p, 0, sizeof *p);
+ snprintf(p->name, sizeof p->name, "%s (%s)", a->name,
+ a->iata[0] ? a->iata : a->icao);
+ p->lat = DEG(a->lat);
+ p->lon = DEG(a->lon);
+ p->elevation = NAN;
+ copy(p->tz, sizeof p->tz, geo_tz_name(a->tz));
+ copy(p->country, sizeof p->country, geo_country_name(a->country));
+ copy(p->cc, sizeof p->cc, geo_country_iso2(a->country));
+ /* the region, for the warnings: the nearest city's */
+ double km;
+ const struct geo_city *c = geo_city_near(p->lat, p->lon, &km);
+ if (c && c->country == a->country && c->region != 0xFFFF)
+ copy(p->region, sizeof p->region, geo_region_name(c->region));
+ if (c && c->country == a->country)
+ localize(p, c->name, 0);
+ return 1;
+ }
+ const struct geo_city *c = geo_city_find(q);
+ if (!c)
+ return 0;
+ memset(p, 0, sizeof *p);
+ copy(p->name, sizeof p->name, c->name);
+ p->lat = DEG(c->lat);
+ p->lon = DEG(c->lon);
+ p->elevation = NAN;
+ copy(p->tz, sizeof p->tz, geo_tz_name(c->tz));
+ copy(p->country, sizeof p->country, geo_country_name(c->country));
+ copy(p->cc, sizeof p->cc, geo_country_iso2(c->country));
+ if (c->region != 0xFFFF)
+ copy(p->region, sizeof p->region, geo_region_name(c->region));
+ return 1;
+}
+
+/* "38.02, 12.51" */
+static int as_point(const char *q, double *lat, double *lon)
+{
+ char *end;
+ double a = strtod(q, &end);
+ if (end == q)
+ return 0;
+ while (*end == ' ' || *end == ',' || *end == ';')
+ end++;
+ char *end2;
+ double b = strtod(end, &end2);
+ if (end2 == end || *end2 || fabs(a) > 90 || fabs(b) > 180)
+ return 0;
+ *lat = a;
+ *lon = b;
+ return 1;
+}
+
+static int same_name(const char *a, const char *b)
+{
+ return a && b && strcasecmp(a, b) == 0;
+}
+
+static int contains(const char *hay, const char *needle)
+{
+ return hay && needle && *needle && strcasestr(hay, needle) != NULL;
+}
+
+/* The geocoding's place of that name: the nearest to (near_lat, near_lon)
+ when given (the name of a point's city: Turin, not Turin in Georgia),
+ else the name itself first, then the most people. */
+static int find_named(const char *query, double near_lat, double near_lon,
+ struct wx_place *p, char *err, size_t err_len)
+{
+ /* "Trapani, Sicilia": the name, and what its region or country must
+ hold */
+ char name[128], hint[64] = "";
+ copy(name, sizeof name, query);
+ char *comma = strchr(name, ',');
+ if (comma) {
+ *comma = 0;
+ const char *h = comma + 1;
+ while (*h == ' ')
+ h++;
+ copy(hint, sizeof hint, h);
+ }
+ size_t nn = strlen(name);
+ while (nn && name[nn - 1] == ' ')
+ name[--nn] = 0;
+ if (!nn) {
+ snprintf(err, err_len, "no place given");
+ return -1;
+ }
+ struct janas_buf url = {0}, body = {0};
+ janas_buf_puts(&url,
+ "https://geocoding-api.open-meteo.com/v1/search?name=");
+ url_put(&url, name, nn);
+ janas_buf_puts(&url, "&count=10&language=it&format=json");
+ char why[256] = "";
+ int status =
+ url.oom ? -1 : wx_fetch(url.p, PLACE_KEEP_S, 0, &body, why, sizeof why);
+ janas_buf_free(&url);
+ struct janas_json_doc *d =
+ status == 200 ? wx_parse(&body, "Open-Meteo", why, sizeof why) : NULL;
+ const struct janas_json *res =
+ d ? janas_json_get(janas_json_root(d), "results") : NULL;
+ const struct janas_json *best = NULL;
+ double best_pop = -1, best_km = 1e30;
+ int best_exact = 0, near = !isnan(near_lat) && !isnan(near_lon);
+ for (const struct janas_json *r =
+ res && res->type == JANAS_JSON_ARRAY ? res->child : NULL;
+ r; r = r->next) {
+ const char *rn = janas_json_str(janas_json_get(r, "name"));
+ const char *a1 = janas_json_str(janas_json_get(r, "admin1"));
+ const char *a2 = janas_json_str(janas_json_get(r, "admin2"));
+ const char *co = janas_json_str(janas_json_get(r, "country"));
+ const char *cc = janas_json_str(janas_json_get(r, "country_code"));
+ if (hint[0] && !contains(a1, hint) && !contains(a2, hint) &&
+ !contains(co, hint) && !same_name(cc, hint))
+ continue;
+ if (near) {
+ double km =
+ geo_km(near_lat, near_lon,
+ janas_json_num(janas_json_get(r, "latitude"), NAN),
+ janas_json_num(janas_json_get(r, "longitude"), NAN));
+ if (km < best_km) { /* NAN never is */
+ best = r;
+ best_km = km;
+ }
+ continue;
+ }
+ int exact = same_name(rn, name);
+ double pop = janas_json_num(janas_json_get(r, "population"), 0);
+ /* the name itself before a longer one holding it, then the most
+ people: Trapani the town, not a hamlet called so */
+ if (!best || exact > best_exact ||
+ (exact == best_exact && pop > best_pop)) {
+ best = r;
+ best_pop = pop;
+ best_exact = exact;
+ }
+ }
+ int ok = 0;
+ if (best) {
+ memset(p, 0, sizeof *p);
+ copy(p->name, sizeof p->name,
+ janas_json_str(janas_json_get(best, "name")));
+ copy(p->region, sizeof p->region,
+ janas_json_str(janas_json_get(best, "admin1")));
+ copy(p->area2, sizeof p->area2,
+ janas_json_str(janas_json_get(best, "admin2")));
+ copy(p->country, sizeof p->country,
+ janas_json_str(janas_json_get(best, "country")));
+ copy(p->cc, sizeof p->cc,
+ janas_json_str(janas_json_get(best, "country_code")));
+ copy(p->tz, sizeof p->tz,
+ janas_json_str(janas_json_get(best, "timezone")));
+ p->lat = janas_json_num(janas_json_get(best, "latitude"), 0);
+ p->lon = janas_json_num(janas_json_get(best, "longitude"), 0);
+ p->elevation = janas_json_num(janas_json_get(best, "elevation"), NAN);
+ ok = 1;
+ }
+ janas_json_free(d);
+ janas_buf_free(&body);
+ if (ok)
+ return 0;
+ /* the geocoding did not answer, or knew nothing: the tables */
+ if (from_tables(name, p))
+ return 0;
+ if (why[0])
+ snprintf(err, err_len, "no place called \"%s\" found (%s)", query, why);
+ else
+ snprintf(err, err_len, "no place called \"%s\" found", query);
+ return -1;
+}
+
+int wx_place_find(const char *query, struct wx_place *p, char *err,
+ size_t err_len)
+{
+ while (*query == ' ')
+ query++;
+ double lat, lon;
+ if (as_point(query, &lat, &lon)) {
+ wx_place_at(lat, lon, p);
+ return 0;
+ }
+ /* an airport's code, as such (TRN: Turin's, not Trn in Bosnia) */
+ size_t n = strlen(query);
+ int code = n == 3 || n == 4;
+ for (size_t i = 0; code && i < n; i++)
+ code = isupper((unsigned char)query[i]) != 0;
+ const struct geo_airport *a = code ? geo_airport_find(query) : NULL;
+ if (a && (strcmp(a->iata, query) == 0 || strcmp(a->icao, query) == 0) &&
+ from_tables(query, p))
+ return 0;
+ return find_named(query, NAN, NAN, p, err, err_len);
+}
diff --git a/src/weather/report.c b/src/weather/report.c
new file mode 100644
index 0000000..e07515f
--- /dev/null
+++ b/src/weather/report.c
@@ -0,0 +1,353 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * report.c - weather_now and weather_forecast (see weather.h): Open-Meteo's
+ * forecast, MET Norway's when it does not answer, and next to the weather
+ * now what the nearest station measured. A forecast is a model's value at
+ * a cell of its grid and a station's is a measure at a known place and
+ * minute: both are given, said for what they are, and when they disagree
+ * it is said too, so that the model telling them need not guess which.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/geo.h"
+#include "weather.h"
+
+#define STATION_KM 40 /* the nearest station, within this */
+
+static int forecast(const struct wx_place *p, int days, struct wx_forecast *f,
+ char *err, size_t err_len)
+{
+ char e1[384];
+ if (wx_om_forecast(p, days, f, e1, sizeof e1) == 0)
+ return 0;
+ char e2[384];
+ if (wx_met_forecast(p, days, f, e2, sizeof e2) == 0)
+ return 0;
+ snprintf(err, err_len, "no forecast: %s; %s", e1, e2);
+ return -1;
+}
+
+static void sky(int code, const char *symbol, char *out, size_t cap)
+{
+ const char *t = code >= 0 ? wx_code_text(code) : NULL;
+ if (t)
+ snprintf(out, cap, "%s", t);
+ else if (symbol && *symbol)
+ wx_symbol_text(symbol, out, cap);
+ else
+ snprintf(out, cap, "not given");
+}
+
+/* "-SHRA" -> "light rain showers": the commonest codes of present
+ weather; the code itself is given too */
+static void wx_words(const char *wx, char *out, size_t cap)
+{
+ static const struct {
+ const char *code, *words;
+ } w[] = {
+ {"TS", "thunderstorm "}, {"SH", "showers of "}, {"FZ", "freezing "},
+ {"RA", "rain "}, {"DZ", "drizzle "}, {"SN", "snow "},
+ {"GR", "hail "}, {"GS", "small hail "}, {"FG", "fog "},
+ {"BR", "mist "}, {"HZ", "haze "}, {"VC", "nearby "}};
+ size_t n = 0;
+ out[0] = 0;
+ const char *s = wx;
+ if (*s == '-' || *s == '+') {
+ n += (size_t)snprintf(out, cap, "%s", *s == '-' ? "light " : "heavy ");
+ s++;
+ }
+ while (*s && n < cap) {
+ size_t i;
+ for (i = 0; i < sizeof w / sizeof w[0]; i++)
+ if (strncmp(s, w[i].code, 2) == 0) {
+ n += (size_t)snprintf(out + n, cap - n, "%s", w[i].words);
+ s += 2;
+ break;
+ }
+ if (i == sizeof w / sizeof w[0])
+ s++;
+ }
+ while (n && out[n - 1] == ' ')
+ out[--n] = 0;
+}
+
+static void visibility(const char *v, char *out, size_t cap)
+{
+ if (!v[0]) {
+ snprintf(out, cap, "not given");
+ return;
+ }
+ if (strchr(v, '+')) {
+ snprintf(out, cap, "%.0f km or more", atof(v) * 1.609);
+ return;
+ }
+ double mi = atof(v);
+ const char *frac = strchr(v, '/'); /* "1 1/2", "1/4" */
+ if (frac) {
+ const char *sp = strchr(v, ' ');
+ double whole = sp ? atof(v) : 0;
+ int a = atoi(sp ? sp + 1 : v), b = atoi(frac + 1);
+ mi = whole + (b ? (double)a / b : 0);
+ }
+ snprintf(out, cap, "%.1f km", mi * 1.609);
+}
+
+static void observation(const struct wx_place *p, const struct wx_obs *o,
+ const struct wx_forecast *f, struct janas_buf *out)
+{
+ char when[64], dir[64], vis[32], words[96];
+ wx_local_time(o->at, p->tz, when, sizeof when);
+ double bearing = geo_bearing(p->lat, p->lon, o->lat, o->lon);
+ long ago = (long)difftime(time(NULL), o->at) / 60;
+ janas_buf_printf(out,
+ "Measured by the station of %s (%s), %.0f km %s of the "
+ "place, at %s (%ld minutes ago): %.0f °C, dew point "
+ "%.0f °C",
+ o->name, o->icao, o->km, geo_compass(bearing), when, ago,
+ o->temp, o->dew);
+ if (!isnan(o->wind_kt)) {
+ if (o->wind_kt < 1)
+ janas_buf_puts(out, ", calm");
+ else if (o->variable_wind)
+ janas_buf_printf(out,
+ ", wind of variable direction at %.0f kt "
+ "(%.0f km/h)",
+ o->wind_kt, o->wind_kt * 1.852);
+ else {
+ wx_from_dir(o->wind_dir, dir, sizeof dir);
+ janas_buf_printf(out, ", wind %s at %.0f kt (%.0f km/h, %s)", dir,
+ o->wind_kt, o->wind_kt * 1.852,
+ wx_wind_words(o->wind_kt * 1.852));
+ }
+ if (!isnan(o->gust_kt))
+ janas_buf_printf(out, ", gusts %.0f kt (%.0f km/h)", o->gust_kt,
+ o->gust_kt * 1.852);
+ }
+ visibility(o->visib, vis, sizeof vis);
+ janas_buf_printf(out, ", visibility %s", vis);
+ if (o->wx[0]) {
+ wx_words(o->wx, words, sizeof words);
+ janas_buf_printf(out, ", %s (%s)", words[0] ? words : o->wx, o->wx);
+ } else {
+ janas_buf_puts(out, ", no rain or other weather");
+ }
+ if (o->clouds[0])
+ janas_buf_printf(out, ", %s", o->clouds);
+ if (!isnan(o->pressure))
+ janas_buf_printf(out, ", pressure %.0f hPa", o->pressure);
+ janas_buf_printf(out, ". As reported: %s\n", o->raw);
+ if (f->has_now && !isnan(f->now.temp) && fabs(f->now.temp - o->temp) >= 3)
+ janas_buf_printf(out,
+ "The model's temperature and the station's differ "
+ "by %.0f °C: the station's is the measure (the "
+ "station is %.0f km away).\n",
+ fabs(f->now.temp - o->temp), o->km);
+ int st_rain = strstr(o->wx, "RA") || strstr(o->wx, "DZ") ||
+ strstr(o->wx, "TS") || strstr(o->wx, "SN");
+ int fc_rain = f->has_now && (f->now.code >= 50 ||
+ (!isnan(f->now.precip) && f->now.precip > 0));
+ if (f->has_now && f->now.code >= 0 && st_rain != fc_rain)
+ janas_buf_printf(out,
+ "The model and the station disagree on rain: the "
+ "station %s, the model %s.\n",
+ st_rain ? "reports it" : "reports none",
+ fc_rain ? "has it" : "has none");
+}
+
+static void source_line(const struct wx_place *p, const struct wx_forecast *f,
+ struct janas_buf *out)
+{
+ double km = geo_km(p->lat, p->lon, f->grid_lat, f->grid_lon);
+ janas_buf_printf(out, "Forecast: %s's model, read at %.3f, %.3f", f->source,
+ f->grid_lat, f->grid_lon);
+ if (!isnan(f->grid_elev))
+ janas_buf_printf(out, " (%.0f m)", f->grid_elev);
+ janas_buf_printf(out,
+ ", %.1f km from the place: a model's value, not a "
+ "measure.\n",
+ km);
+}
+
+int wx_tool_now(const struct janas_json *args, struct janas_buf *b)
+{
+ struct wx_place p;
+ if (wx_arg_place(args, &p, b) != 0)
+ return 0;
+ struct wx_forecast *f = calloc(1, sizeof *f);
+ struct janas_buf out = {0};
+ char err[800], name[256], s[96], dir[64];
+ wx_place_name(&p, name, sizeof name);
+ if (!f || forecast(&p, 1, f, err, sizeof err) != 0) {
+ janas_buf_printf(&out, "No forecast for %s: %s.", name,
+ f ? err : "out of memory");
+ free(f);
+ return wx_result(&out, b, 1);
+ }
+ if (!p.tz[0])
+ snprintf(p.tz, sizeof p.tz, "%s", f->tz);
+ const struct wx_now *w = &f->now;
+ const char *T = strchr(w->time, 'T');
+ janas_buf_printf(&out, "The weather now in %s, at %.5s %s (local time):\n",
+ name, T ? T + 1 : w->time, f->tz_abbr);
+ sky(w->code, w->symbol, s, sizeof s);
+ janas_buf_printf(&out, "- sky: %s", s);
+ if (!isnan(w->cloud))
+ janas_buf_printf(&out, " (cloud cover %.0f%%)", w->cloud);
+ janas_buf_printf(&out, "\n- temperature %.1f °C", w->temp);
+ if (!isnan(w->feels))
+ janas_buf_printf(&out, ", feels like %.1f °C", w->feels);
+ if (!isnan(w->humidity))
+ janas_buf_printf(&out, "; humidity %.0f%%", w->humidity);
+ wx_from_dir(w->wind_dir, dir, sizeof dir);
+ janas_buf_printf(&out, "\n- wind %s at %.0f km/h (%s)", dir, w->wind,
+ wx_wind_words(w->wind));
+ if (!isnan(w->gust))
+ janas_buf_printf(&out, ", gusts up to %.0f km/h", w->gust);
+ if (!isnan(w->precip))
+ janas_buf_printf(&out,
+ "\n- rain in the last quarter of an hour: "
+ "%.1f mm",
+ w->precip);
+ if (!isnan(w->pressure))
+ janas_buf_printf(&out, "\n- pressure at sea level %.0f hPa",
+ w->pressure);
+ if (f->n_day) {
+ const struct wx_day *y = &f->day[0];
+ janas_buf_printf(&out, "\n- today: lowest %.1f °C, highest %.1f °C",
+ y->tmin, y->tmax);
+ if (!isnan(y->rain_prob))
+ janas_buf_printf(&out, ", chance of rain %.0f%%", y->rain_prob);
+ if (y->sunrise[0])
+ janas_buf_printf(&out, "; sunrise %s, sunset %s", y->sunrise,
+ y->sunset);
+ }
+ janas_buf_puts(&out, "\n");
+ source_line(&p, f, &out);
+
+ struct wx_obs o;
+ char why[384];
+ int r = wx_metar_near(p.lat, p.lon, STATION_KM, &o, why, sizeof why);
+ if (r == 1)
+ observation(&p, &o, f, &out);
+ else if (r == 0)
+ janas_buf_printf(&out, "No weather station reported within %d km.\n",
+ STATION_KM);
+ else
+ janas_buf_printf(&out, "The stations could not be asked (%s).\n", why);
+ janas_buf_printf(&out, "Sources: %s (%s, CC BY 4.0)%s.", f->source,
+ strcmp(f->source, "Open-Meteo") == 0 ? "open-meteo.com"
+ : "api.met.no",
+ r == 1 ? "; the station's METAR from aviationweather.gov "
+ "(NOAA)"
+ : "");
+ free(f);
+ wx_place_note(p.how, &out);
+ return wx_result(&out, b, 0);
+}
+
+static void day_line(const struct wx_day *y, struct janas_buf *out)
+{
+ char name[48], s[96], dir[64];
+ wx_day_name(y->date, name, sizeof name);
+ sky(y->code, y->symbol, s, sizeof s);
+ janas_buf_printf(out, "- %s: %s; %.1f to %.1f °C", name, s, y->tmin,
+ y->tmax);
+ if (!isnan(y->rain)) {
+ if (y->rain < 0.1)
+ janas_buf_puts(out, "; no rain");
+ else
+ janas_buf_printf(out, "; rain %.1f mm", y->rain);
+ }
+ if (!isnan(y->rain_prob))
+ janas_buf_printf(out, " (chance %.0f%%)", y->rain_prob);
+ if (!isnan(y->wind)) {
+ wx_from_dir(y->wind_dir, dir, sizeof dir);
+ janas_buf_printf(out, "; wind up to %.0f km/h (%s) %s", y->wind,
+ wx_wind_words(y->wind), dir);
+ }
+ if (!isnan(y->gust))
+ janas_buf_printf(out, ", gusts up to %.0f km/h", y->gust);
+ if (!isnan(y->uv))
+ janas_buf_printf(out, "; UV index %.0f", y->uv);
+ if (y->sunrise[0])
+ janas_buf_printf(out, "; sunrise %s, sunset %s", y->sunrise, y->sunset);
+ janas_buf_puts(out, "\n");
+}
+
+static void hour_line(const struct wx_hour *h, struct janas_buf *out)
+{
+ char s[96], dir[64];
+ sky(h->code, h->symbol, s, sizeof s);
+ const char *T = strchr(h->time, 'T');
+ janas_buf_printf(out, "- %.5s: %s, %.1f °C", T ? T + 1 : h->time, s,
+ h->temp);
+ if (!isnan(h->rain) && h->rain >= 0.1)
+ janas_buf_printf(out, ", rain %.1f mm", h->rain);
+ if (!isnan(h->rain_prob))
+ janas_buf_printf(out, " (chance %.0f%%)", h->rain_prob);
+ wx_from_dir(h->wind_dir, dir, sizeof dir);
+ janas_buf_printf(out, ", wind %.0f km/h %s", h->wind, dir);
+ if (!isnan(h->gust))
+ janas_buf_printf(out, ", gusts %.0f", h->gust);
+ janas_buf_puts(out, "\n");
+}
+
+int wx_tool_forecast(const struct janas_json *args, struct janas_buf *b)
+{
+ struct wx_place p;
+ if (wx_arg_place(args, &p, b) != 0)
+ return 0;
+ int days = (int)wx_arg_num(args, "days", 3);
+ if (days < 1)
+ days = 1;
+ if (days > WX_DAYS)
+ days = WX_DAYS;
+ int hourly = wx_arg_bool(args, "hourly", 0);
+ struct wx_forecast *f = calloc(1, sizeof *f);
+ struct janas_buf out = {0};
+ char err[800], name[256];
+ wx_place_name(&p, name, sizeof name);
+ if (!f || forecast(&p, days, f, err, sizeof err) != 0) {
+ janas_buf_printf(&out, "No forecast for %s: %s.", name,
+ f ? err : "out of memory");
+ free(f);
+ return wx_result(&out, b, 1);
+ }
+ janas_buf_printf(&out,
+ "Forecast for %s, by the day (times in local time, "
+ "%s):\n",
+ name, f->tz_abbr);
+ for (int i = 0; i < f->n_day && i < days; i++)
+ day_line(&f->day[i], &out);
+ if (f->n_day < days)
+ janas_buf_printf(&out, "(%s gives %d days.)\n", f->source, f->n_day);
+ int step = hourly ? 1 : 3, last = hourly ? WX_HOURS : 24;
+ if (f->n_hour) {
+ janas_buf_printf(&out, "The next %d hours, every %s:\n",
+ last < f->n_hour ? last : f->n_hour,
+ step == 1 ? "hour" : "three hours");
+ char prev[11] = "";
+ for (int i = 0; i < f->n_hour && i < last; i += step) {
+ if (strncmp(prev, f->hour[i].time, 10) != 0) {
+ char dn[48], date[11];
+ snprintf(date, sizeof date, "%.10s", f->hour[i].time);
+ wx_day_name(date, dn, sizeof dn);
+ janas_buf_printf(&out, "%s\n", dn);
+ snprintf(prev, sizeof prev, "%s", date);
+ }
+ hour_line(&f->hour[i], &out);
+ }
+ }
+ source_line(&p, f, &out);
+ janas_buf_printf(&out, "Source: %s (%s, CC BY 4.0).", f->source,
+ strcmp(f->source, "Open-Meteo") == 0 ? "open-meteo.com"
+ : "api.met.no");
+ free(f);
+ wx_place_note(p.how, &out);
+ return wx_result(&out, b, 0);
+}
diff --git a/src/weather/sea.c b/src/weather/sea.c
new file mode 100644
index 0000000..b00729e
--- /dev/null
+++ b/src/weather/sea.c
@@ -0,0 +1,225 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * sea.c - weather_sea (see weather.h): the state of the sea from
+ * Open-Meteo's sea model, for a whole sea at points spread across it (the
+ * same areas as janas-flights', from Natural Earth's polygons), or off a
+ * coastal place. Each point is said in words, the heights of the waves
+ * with their names on the Douglas scale, and the whole first: from what to
+ * what, and where the sea will be roughest in the next days.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common/geo.h"
+#include "weather.h"
+
+#define DEG(x) ((x) * 1e-5)
+#define GRID 5 /* candidate points a side, across the area's box */
+#define COAST_KM 30 /* off a place: the sea model's cell within this */
+
+/* Points over the area, spread: of a GRID x GRID net over its box those
+ over the sea, at most WX_SEA_POINTS of them taken evenly. */
+static int area_points(const struct geo_area *a, struct wx_sea *s)
+{
+ double c_lat[GRID * GRID], c_lon[GRID * GRID];
+ int n = 0;
+ for (int g = GRID; g <= 2 * GRID && n < 3; g += 2) {
+ n = 0;
+ for (int i = 0; i < g; i++)
+ for (int j = 0; j < g; j++) {
+ double lat = DEG(a->s_lat_min) +
+ (i + 0.5) * DEG(a->s_lat_max - a->s_lat_min) / g;
+ double lon = DEG(a->s_lon_min) +
+ (j + 0.5) * DEG(a->s_lon_max - a->s_lon_min) / g;
+ if (geo_area_has(a, lat, lon) && n < GRID * GRID) {
+ c_lat[n] = lat;
+ c_lon[n] = lon;
+ n++;
+ }
+ }
+ }
+ int k = n < WX_SEA_POINTS ? n : WX_SEA_POINTS;
+ for (int i = 0; i < k; i++) {
+ int at = k == n ? i : (int)((double)i * n / k);
+ memset(&s[i], 0, sizeof s[i]);
+ s[i].lat = c_lat[at];
+ s[i].lon = c_lon[at];
+ }
+ return k;
+}
+
+static void point_line(const struct wx_sea *s, int days, int with_place,
+ struct janas_buf *out)
+{
+ char dir[64];
+ janas_buf_puts(out, "- ");
+ if (with_place) {
+ geo_describe(s->lat, s->lon, out);
+ janas_buf_puts(out, ": ");
+ }
+ wx_from_dir(s->wave_dir, dir, sizeof dir);
+ janas_buf_printf(out, "waves %.1f m (%s) %s", s->wave,
+ wx_sea_words(s->wave), dir);
+ if (!isnan(s->period))
+ janas_buf_printf(out, ", period %.0f s", s->period);
+ if (!isnan(s->wind_wave))
+ janas_buf_printf(out, "; wind waves %.1f m", s->wind_wave);
+ if (!isnan(s->swell)) {
+ wx_from_dir(s->swell_dir, dir, sizeof dir);
+ janas_buf_printf(out, ", swell %.1f m %s", s->swell, dir);
+ }
+ if (!isnan(s->sst))
+ janas_buf_printf(out, "; water %.1f °C", s->sst);
+ if (!isnan(s->wind)) {
+ wx_from_dir(s->wind_dir, dir, sizeof dir);
+ janas_buf_printf(out, "; wind %.0f km/h (%s) %s", s->wind,
+ wx_wind_words(s->wind), dir);
+ if (!isnan(s->gust))
+ janas_buf_printf(out, ", gusts %.0f km/h", s->gust);
+ }
+ janas_buf_puts(out, "\n");
+ for (int d = 0; d < s->n_day && d < days; d++) {
+ const struct wx_sea_day *y = &s->day[d];
+ char name[48];
+ wx_day_name(y->date, name, sizeof name);
+ wx_from_dir(y->wave_dir, dir, sizeof dir);
+ janas_buf_printf(out, " %s: waves up to %.1f m (%s) %s", name,
+ y->wave_max, wx_sea_words(y->wave_max), dir);
+ if (!isnan(y->wind_max)) {
+ janas_buf_printf(out, ", wind up to %.0f km/h (%s)", y->wind_max,
+ wx_wind_words(y->wind_max));
+ if (!isnan(y->gust_max))
+ janas_buf_printf(out, ", gusts %.0f", y->gust_max);
+ }
+ janas_buf_puts(out, "\n");
+ }
+}
+
+static void summary(const struct wx_sea *s, int n, int days,
+ struct janas_buf *out)
+{
+ double lo = NAN, hi = NAN, t_lo = NAN, t_hi = NAN;
+ int ok = 0;
+ for (int i = 0; i < n; i++) {
+ if (!s[i].ok)
+ continue;
+ ok++;
+ if (isnan(lo) || s[i].wave < lo)
+ lo = s[i].wave;
+ if (isnan(hi) || s[i].wave > hi)
+ hi = s[i].wave;
+ if (!isnan(s[i].sst)) {
+ if (isnan(t_lo) || s[i].sst < t_lo)
+ t_lo = s[i].sst;
+ if (isnan(t_hi) || s[i].sst > t_hi)
+ t_hi = s[i].sst;
+ }
+ }
+ janas_buf_printf(out, "Now, at %d points: waves %.1f to %.1f m (%s", ok, lo,
+ hi, wx_sea_words(lo));
+ if (strcmp(wx_sea_words(lo), wx_sea_words(hi)) != 0)
+ janas_buf_printf(out, " to %s", wx_sea_words(hi));
+ janas_buf_puts(out, ")");
+ if (!isnan(t_lo))
+ janas_buf_printf(out, ", water %.1f to %.1f °C", t_lo, t_hi);
+ janas_buf_puts(out, ".\n");
+ for (int d = 0; d < days; d++) {
+ int at = -1;
+ for (int i = 0; i < n; i++)
+ if (s[i].ok && d < s[i].n_day && !isnan(s[i].day[d].wave_max) &&
+ (at < 0 || s[i].day[d].wave_max > s[at].day[d].wave_max))
+ at = i;
+ if (at < 0)
+ continue;
+ char name[48];
+ wx_day_name(s[at].day[d].date, name, sizeof name);
+ janas_buf_printf(out, "%s: highest waves %.1f m (%s), ", name,
+ s[at].day[d].wave_max,
+ wx_sea_words(s[at].day[d].wave_max));
+ geo_describe(s[at].lat, s[at].lon, out);
+ janas_buf_puts(out, ".\n");
+ }
+}
+
+int wx_tool_sea(const struct janas_json *args, struct janas_buf *b)
+{
+ int days = (int)wx_arg_num(args, "days", 2);
+ if (days < 1)
+ days = 1;
+ if (days > 8)
+ days = 8;
+ const char *area = wx_arg_str(args, "area");
+ struct wx_sea s[WX_SEA_POINTS];
+ struct janas_buf out = {0};
+ char err[512], tz[48] = "", title[256], how[96] = "";
+ int n;
+ struct geo_area a;
+ if (area) {
+ if (!geo_area_find(area, &a)) {
+ janas_buf_printf(&out,
+ "No sea called \"%s\" known: give its name "
+ "in English (Tyrrhenian Sea, Adriatic "
+ "Sea, Ligurian Sea) or a coastal place.",
+ area);
+ return wx_result(&out, b, 1);
+ }
+ n = area_points(&a, s);
+ double km;
+ const struct geo_airport *ap =
+ geo_airport_near(DEG(a.lat_min + a.lat_max) / 2,
+ DEG(a.lon_min + a.lon_max) / 2, &km);
+ if (ap)
+ snprintf(tz, sizeof tz, "%s", geo_tz_name(ap->tz));
+ snprintf(title, sizeof title, "the %s", a.name);
+ } else {
+ struct wx_place p;
+ if (wx_arg_place(args, &p, b) != 0)
+ return 0;
+ snprintf(how, sizeof how, "%s", p.how);
+ memset(&s[0], 0, sizeof s[0]);
+ s[0].lat = p.lat;
+ s[0].lon = p.lon;
+ n = 1;
+ snprintf(tz, sizeof tz, "%s", p.tz);
+ char name[200];
+ wx_place_name(&p, name, sizeof name);
+ snprintf(title, sizeof title, "the sea off %s", name);
+ }
+ if (n == 0) {
+ janas_buf_printf(&out, "No point of %s found to ask about.", title);
+ return wx_result(&out, b, 1);
+ }
+ if (wx_om_marine(s, n, days, tz, err, sizeof err) != 0) {
+ janas_buf_printf(&out, "No forecast of %s: %s.", title, err);
+ return wx_result(&out, b, 1);
+ }
+ if (!area && (!s[0].ok || geo_km(s[0].lat, s[0].lon, s[0].cell_lat,
+ s[0].cell_lon) > COAST_KM)) {
+ janas_buf_printf(&out,
+ "There is no sea within %d km of the place for "
+ "the sea model; ask about a coastal place or "
+ "a sea by its name.",
+ COAST_KM);
+ return wx_result(&out, b, 1);
+ }
+ const char *T = strchr(s[0].time, 'T');
+ janas_buf_printf(&out,
+ "The state of %s at %.5s local time (%s), and "
+ "the next %d days:\n",
+ title, T ? T + 1 : s[0].time, tz[0] ? tz : "UTC", days);
+ if (area)
+ summary(s, n, days, &out);
+ for (int i = 0; i < n; i++)
+ if (s[i].ok)
+ point_line(&s[i], days, area != NULL, &out);
+ janas_buf_puts(&out, "The waves' height is the significant height (the "
+ "mean of the highest third); single waves can be "
+ "almost twice as high. Source: Open-Meteo's sea "
+ "and weather models (open-meteo.com, CC BY 4.0): "
+ "forecasts, not measures.");
+ wx_place_note(how, &out);
+ return wx_result(&out, b, 0);
+}
diff --git a/src/weather/tools.c b/src/weather/tools.c
new file mode 100644
index 0000000..7c29703
--- /dev/null
+++ b/src/weather/tools.c
@@ -0,0 +1,256 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * tools.c - the tools janas-weather offers (see weather.h): weather_now,
+ * weather_forecast, weather_sea and weather_alerts, and what they share:
+ * their arguments, the place asked for, times in the place's own zone.
+ * The tools themselves are in report.c, sea.c and warn.c.
+ */
+#define _GNU_SOURCE /* timegm */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "common/locate.h"
+#include "common/mcp_server.h"
+#include "weather.h"
+
+static void schema_str(struct janas_buf *b, const char *name, const char *what)
+{
+ janas_buf_printf(b,
+ "\"%s\": {\"type\": \"string\", \"description\": ", name);
+ janas_json_write_str(b, what, strlen(what));
+ janas_buf_puts(b, "}");
+}
+
+static void place_props(struct janas_buf *b)
+{
+ schema_str(b, "place",
+ "A place's name, in Italian or English (Trapani, Firenze, "
+ "Florence, Milano); \"name, region\" or \"name, country\" "
+ "when several places share it; or an airport's code. "
+ "Leave out place and coordinates only when the user names "
+ "no place: then where the user is (as set on the computer, "
+ "or estimated from the internet connection).");
+ janas_buf_puts(b,
+ ", \"latitude\": {\"type\": \"number\", \"minimum\": -90, "
+ "\"maximum\": 90}, \"longitude\": {\"type\": \"number\", "
+ "\"minimum\": -180, \"maximum\": 180}");
+}
+
+void wx_tools_list(void *ctx, struct janas_buf *b)
+{
+ (void)ctx;
+ janas_buf_puts(
+ b, "\"tools\": [{\"name\": \"weather_now\", \"title\": \"The "
+ "weather now\", \"description\": \"The weather now at a place: "
+ "sky, temperature and how it feels, humidity, wind and gusts, "
+ "rain, pressure, today's lowest and highest and sunrise and "
+ "sunset, from a forecast model; and what the nearest weather "
+ "station (an airport's) measured, with when and how far away. "
+ "Give a place's name, or a latitude and longitude.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {");
+ place_props(b);
+ janas_buf_puts(
+ b, "}, \"additionalProperties\": false}}, "
+ "{\"name\": \"weather_forecast\", \"title\": \"Weather "
+ "forecast\", \"description\": \"The forecast for a place, day "
+ "by day (sky, lowest and highest temperature, rain and its "
+ "chance, wind and gusts, sunrise and sunset) and the next hours "
+ "(every three hours, or every hour when asked).\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {");
+ place_props(b);
+ janas_buf_puts(
+ b, ", \"days\": {\"type\": \"integer\", \"minimum\": 1, "
+ "\"maximum\": 16, \"description\": \"How many days, today "
+ "included (default 3).\"}, \"hourly\": {\"type\": \"boolean\", "
+ "\"description\": \"Every hour of the next two days, instead "
+ "of every three hours of the next one.\"}}, "
+ "\"additionalProperties\": false}}, "
+ "{\"name\": \"weather_sea\", \"title\": \"The sea\", "
+ "\"description\": \"The state of the sea, now and in the next "
+ "days: wave height (with its name: calm, slight, moderate, "
+ "rough...), direction and period, wind waves and swell, the "
+ "water's temperature and the wind. For a whole sea by its name "
+ "(Tyrrhenian Sea, Tirreno, Adriatico, mar Ligure), at several "
+ "points across it, or for the sea off a coastal place.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {");
+ schema_str(b, "area",
+ "A sea's name, in English or Italian (Tyrrhenian Sea, "
+ "Tirreno, Adriatic, mar Ligure, Ionio).");
+ janas_buf_puts(b, ", ");
+ place_props(b);
+ janas_buf_puts(
+ b, ", \"days\": {\"type\": \"integer\", \"minimum\": 1, "
+ "\"maximum\": 8, \"description\": \"How many days, today "
+ "included (default 2).\"}}, \"additionalProperties\": false}}, "
+ "{\"name\": \"weather_alerts\", \"title\": \"Weather "
+ "warnings\", \"description\": \"The weather warnings in force "
+ "for a place: those of the national weather services gathered "
+ "by MeteoAlarm (wind, thunderstorms, heat, snow, by level: "
+ "yellow, orange, red), the place's region first; and in Italy "
+ "the Civil Protection's official alert levels for its zone, for "
+ "floods, landslides and thunderstorms, today and tomorrow.\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {");
+ place_props(b);
+ janas_buf_puts(b, ", ");
+ schema_str(b, "language",
+ "The language of the warnings' texts when given in it: it, "
+ "en, fr, de, es (default en).");
+ janas_buf_puts(b, "}, \"additionalProperties\": false}}]");
+}
+
+int wx_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b)
+{
+ (void)ctx;
+ const struct janas_json *name = janas_json_get(params, "name");
+ const struct janas_json *args = janas_json_get(params, "arguments");
+ if (args && args->type != JANAS_JSON_OBJECT)
+ args = NULL;
+ if (janas_json_is(name, "weather_now"))
+ return wx_tool_now(args, b);
+ if (janas_json_is(name, "weather_forecast"))
+ return wx_tool_forecast(args, b);
+ if (janas_json_is(name, "weather_sea"))
+ return wx_tool_sea(args, b);
+ if (janas_json_is(name, "weather_alerts"))
+ return wx_tool_alerts(args, b);
+ return -1;
+}
+
+/* ---- what the tools share ---- */
+
+const char *wx_arg_str(const struct janas_json *args, const char *name)
+{
+ const char *s = janas_json_str(janas_json_get(args, name));
+ return s && *s ? s : NULL;
+}
+
+double wx_arg_num(const struct janas_json *args, const char *name, double def)
+{
+ const struct janas_json *v = janas_json_get(args, name);
+ return v && v->type == JANAS_JSON_NUMBER ? janas_json_num(v, def) : def;
+}
+
+int wx_arg_bool(const struct janas_json *args, const char *name, int def)
+{
+ const struct janas_json *v = janas_json_get(args, name);
+ if (v && v->type == JANAS_JSON_TRUE)
+ return 1;
+ if (v && v->type == JANAS_JSON_FALSE)
+ return 0;
+ return def;
+}
+
+void wx_place_note(const char *how, struct janas_buf *out)
+{
+ if (how && *how)
+ janas_buf_printf(out,
+ "\nNo place was named: this is where the user is, "
+ "%s. Tell the user which place it is and that it "
+ "may be off: they can name theirs.",
+ how);
+}
+
+int wx_result(struct janas_buf *out, struct janas_buf *b, int is_error)
+{
+ janas_mcps_text_result(b, out->p ? out->p : "", out->n, is_error);
+ janas_buf_free(out);
+ return 0;
+}
+
+int wx_arg_place(const struct janas_json *args, struct wx_place *p,
+ struct janas_buf *b)
+{
+ const char *q = wx_arg_str(args, "place");
+ double lat = wx_arg_num(args, "latitude", NAN);
+ double lon = wx_arg_num(args, "longitude", NAN);
+ char err[384];
+ if (q && wx_place_find(q, p, err, sizeof err) == 0)
+ return 0;
+ if (!q && !isnan(lat) && !isnan(lon)) {
+ wx_place_at(lat, lon, p);
+ return 0;
+ }
+ struct janas_where w;
+ if (!q && janas_where(&w, err, sizeof err) == 0) {
+ /* named as a point is, in the country's language: the source's
+ own names are English at times (Sicily), the warnings' not */
+ wx_place_at(w.lat, w.lon, p);
+ /* "3 km WNW of Palermo" says more than a guess knows: its town */
+ if (w.city[0] && strstr(p->name, " km "))
+ snprintf(p->name, sizeof p->name, "%s", w.city);
+ if (!p->tz[0])
+ snprintf(p->tz, sizeof p->tz, "%s", w.tz);
+ snprintf(p->how, sizeof p->how, "%s", w.how);
+ return 0;
+ }
+ struct janas_buf out = {0};
+ if (!q)
+ janas_buf_printf(&out, "No place given, and %s.", err);
+ else
+ janas_buf_printf(&out,
+ "%s. Ask the user which place, or try the "
+ "name in another language or with its "
+ "region (\"Name, Region\").",
+ err);
+ wx_result(&out, b, 1);
+ return -1;
+}
+
+void wx_local_time(time_t t, const char *tz, char *out, size_t cap)
+{
+ char *old = getenv("TZ") ? strdup(getenv("TZ")) : NULL;
+ if (tz && *tz)
+ setenv("TZ", tz, 1);
+ tzset();
+ struct tm lt, nt;
+ time_t now = time(NULL);
+ localtime_r(&t, &lt);
+ localtime_r(&now, &nt);
+ char hm[16], day[32] = "";
+ strftime(hm, sizeof hm, "%H:%M", &lt);
+ if (lt.tm_yday != nt.tm_yday || lt.tm_year != nt.tm_year)
+ strftime(day, sizeof day, " on %A %-d %B", &lt);
+ snprintf(out, cap, "%s%s %s", hm, day, lt.tm_zone ? lt.tm_zone : "");
+ if (tz && *tz) {
+ if (old)
+ setenv("TZ", old, 1);
+ else
+ unsetenv("TZ");
+ tzset();
+ }
+ free(old);
+}
+
+void wx_day_name(const char *date, char *out, size_t cap)
+{
+ struct tm tm = {0};
+ if (sscanf(date, "%d-%d-%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday) != 3) {
+ snprintf(out, cap, "%s", date);
+ return;
+ }
+ tm.tm_year -= 1900;
+ tm.tm_mon -= 1;
+ tm.tm_hour = 12;
+ time_t t = timegm(&tm);
+ struct tm g;
+ gmtime_r(&t, &g);
+ strftime(out, cap, "%A %-d %B", &g);
+}
+
+void wx_place_name(const struct wx_place *p, char *out, size_t cap)
+{
+ if (p->region[0] && p->country[0] && strcmp(p->region, p->name) != 0)
+ snprintf(out, cap, "%s (%s, %s)", p->name, p->region, p->country);
+ else if (p->country[0] && strcmp(p->country, p->name) != 0)
+ snprintf(out, cap, "%s (%s)", p->name, p->country);
+ else
+ snprintf(out, cap, "%s", p->name);
+ size_t n = strlen(out);
+ if (p->how[0] && n < cap) /* the model is to say it is a guess */
+ snprintf(out + n, cap - n, " - where the user is, %s", p->how);
+}
diff --git a/src/weather/warn.c b/src/weather/warn.c
new file mode 100644
index 0000000..98b8ea6
--- /dev/null
+++ b/src/weather/warn.c
@@ -0,0 +1,153 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * warn.c - weather_alerts (see weather.h): MeteoAlarm's warnings in force
+ * for the place's region, those of the rest of its country after them,
+ * and in Italy the Civil Protection's official levels for the place's
+ * zone of alert. No warning is news too, and is said.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "weather.h"
+
+#define OTHERS 8 /* warnings elsewhere in the country, listed at most */
+
+static void alert_line(const struct wx_alert *a, int full, const char *tz,
+ struct janas_buf *out)
+{
+ /* the feeds give their own zone (Norway's UTC): the place's instead */
+ char from[64], to[64];
+ time_t t0 = wx_iso_time(a->onset), t1 = wx_iso_time(a->expires);
+ if (t0)
+ wx_local_time(t0, tz, from, sizeof from);
+ else
+ snprintf(from, sizeof from, "%.16s", a->onset);
+ if (t1)
+ wx_local_time(t1, tz, to, sizeof to);
+ else
+ snprintf(to, sizeof to, "%.16s", a->expires);
+ janas_buf_printf(out, "- %s, %s level, %s: from %s to %s", a->event,
+ a->level, a->area, from, to);
+ if (full && a->text[0]) {
+ /* the first line of the description: the rest is a disclaimer */
+ const char *nl = strchr(a->text, '\n');
+ int n = nl ? (int)(nl - a->text) : (int)strlen(a->text);
+ janas_buf_printf(out, ". %.*s", n, a->text);
+ }
+ if (full && a->sender[0])
+ janas_buf_printf(out, " (%s)", a->sender);
+ janas_buf_puts(out, "\n");
+}
+
+static const char *dpc_words(const char *level)
+{
+ /* "Ordinaria criticità / ALLERTA GIALLA" -> the level, in English */
+ if (strstr(level, "ROSSA"))
+ return "red alert (high criticality)";
+ if (strstr(level, "ARANCIONE"))
+ return "orange alert (moderate criticality)";
+ if (strstr(level, "GIALLA"))
+ return "yellow alert (ordinary criticality)";
+ if (strstr(level, "NESSUNA"))
+ return "no alert (no significant phenomena expected)";
+ return level;
+}
+
+int wx_tool_alerts(const struct janas_json *args, struct janas_buf *b)
+{
+ struct wx_place p;
+ if (wx_arg_place(args, &p, b) != 0)
+ return 0;
+ const char *lang = wx_arg_str(args, "language");
+ struct janas_buf out = {0};
+ char name[256], err[512];
+ wx_place_name(&p, name, sizeof name);
+ janas_buf_printf(&out, "Weather warnings for %s:\n", name);
+
+ struct wx_alert *v = NULL;
+ size_t n = 0;
+ int r = wx_meteoalarm(&p, lang ? lang : "en", &v, &n, err, sizeof err);
+ if (r < 0) {
+ janas_buf_printf(&out, "MeteoAlarm could not be asked: %s.\n", err);
+ } else if (r > 0) {
+ janas_buf_printf(&out, "%s.\n", err);
+ } else {
+ size_t mine = 0;
+ while (mine < n && v[mine].mine)
+ mine++;
+ const char *region = p.region[0] ? p.region : p.country;
+ if (mine)
+ janas_buf_printf(&out, "MeteoAlarm, in force for %s:\n", region);
+ else
+ janas_buf_printf(&out,
+ "MeteoAlarm: no warning in force for "
+ "%s.\n",
+ region);
+ for (size_t i = 0; i < mine; i++)
+ alert_line(&v[i], 1, p.tz, &out);
+ if (n > mine) {
+ janas_buf_printf(&out, "Elsewhere in %s, %zu more:\n",
+ p.country[0] ? p.country : "the country",
+ n - mine);
+ for (size_t i = mine; i < n && i < mine + OTHERS; i++)
+ alert_line(&v[i], 0, p.tz, &out);
+ if (n - mine > OTHERS)
+ janas_buf_printf(&out, "- and %zu more\n", n - mine - OTHERS);
+ }
+ if (strcmp(p.cc, "IT") == 0)
+ janas_buf_puts(&out, "MeteoAlarm's Italian warnings are the Air "
+ "Force weather service's, about the "
+ "phenomena; the official alerts are the "
+ "Civil Protection's, below.\n");
+ }
+ free(v);
+
+ if (strcmp(p.cc, "IT") == 0) {
+ struct wx_dpc d;
+ int k = wx_dpc(&p, &d, err, sizeof err);
+ if (k < 0) {
+ janas_buf_printf(&out,
+ "The Civil Protection's bulletin could not "
+ "be read: %s.\n",
+ err);
+ } else if (k == 0) {
+ janas_buf_printf(&out,
+ "The Civil Protection's bulletin has no "
+ "municipality called %s.\n",
+ p.name);
+ } else {
+ janas_buf_printf(&out,
+ "The Civil Protection's national bulletin of "
+ "criticality (issued %.4s-%.2s-%.2s at "
+ "%.2s:%.2s), zone of alert %s:\n",
+ d.issued, d.issued + 4, d.issued + 6, d.issued + 9,
+ d.issued + 11, d.zones);
+ static const char *const what[3] = {"floods (hydraulic)",
+ "landslides (hydrogeological)",
+ "thunderstorms"};
+ for (int i = 0; i < 2 && d.day[i][0]; i++) {
+ char dn[48];
+ wx_day_name(d.day[i], dn, sizeof dn);
+ janas_buf_printf(&out, "- %s:", dn);
+ for (int j = 0; j < 3; j++)
+ janas_buf_printf(&out, "%s %s: %s", j ? ";" : "", what[j],
+ d.level[i][j][0] ? dpc_words(d.level[i][j])
+ : "not given");
+ janas_buf_puts(&out, "\n");
+ }
+ if (!d.day[1][0])
+ janas_buf_puts(&out, "Tomorrow's levels come with the next "
+ "bulletin, usually by 16:00.\n");
+ }
+ }
+ janas_buf_puts(&out, "Sources: MeteoAlarm (meteoalarm.org, EUMETNET)");
+ if (strcmp(p.cc, "IT") == 0)
+ janas_buf_puts(&out, "; Dipartimento della Protezione Civile "
+ "(CC BY 4.0)");
+ janas_buf_puts(&out, ".");
+ wx_place_note(p.how, &out);
+ return wx_result(&out, b, 0);
+}
diff --git a/src/weather/weather.h b/src/weather/weather.h
new file mode 100644
index 0000000..24d13b8
--- /dev/null
+++ b/src/weather/weather.h
@@ -0,0 +1,250 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * weather.h - janas-weather, the weather as an MCP service: what its parts
+ * share. fetch.c asks the sources (answers kept a while), place.c finds a
+ * place by its name, openmeteo.c reads Open-Meteo's forecasts and seas,
+ * metno.c MET Norway's (when Open-Meteo does not answer), metar.c the
+ * observations of the airports' stations, alerts.c MeteoAlarm's warnings
+ * and the Italian Civil Protection's bulletin, words.c puts it all into
+ * words, tools.c offers the tools.
+ */
+#ifndef JANAS_WEATHER_H
+#define JANAS_WEATHER_H
+
+#include <stddef.h>
+#include <time.h>
+
+#include "llm/json.h"
+
+/* ---- fetch.c ---- */
+
+/* GET of url, the body into out; answers of status 200 are kept keep_s
+ seconds and given again meanwhile. with_agent: the User-Agent MET Norway
+ asks for, naming the program and where it lives. The HTTP status, or -1
+ with the reason in err. */
+int wx_fetch(const char *url, int keep_s, int with_agent, struct janas_buf *out,
+ char *err, size_t err_len);
+void wx_fetch_free(void);
+
+/* The text of a JSON document read (NULL with the reason in err). */
+struct janas_json_doc *wx_parse(const struct janas_buf *b, const char *who,
+ char *err, size_t err_len);
+
+/* ---- place.c ---- */
+
+struct wx_place {
+ char name[96]; /* "Trapani" */
+ char region[64]; /* "Sicilia": the first-level division */
+ char area2[64]; /* "Trapani": the second, a province */
+ char country[64]; /* "Italia" */
+ char cc[3]; /* "IT" */
+ char tz[48]; /* "Europe/Rome" */
+ double lat, lon;
+ double elevation; /* metres; NAN when not known */
+ char how[96]; /* where the user is, when the place was not given:
+ how it was told (locate.h); "" otherwise */
+};
+
+/* A place by its name (in any language Open-Meteo's geocoding reads,
+ Italian and English among them), an airport's code, or "lat,lon". 0, or
+ -1 with the reason in err. */
+int wx_place_find(const char *query, struct wx_place *p, char *err,
+ size_t err_len);
+/* A point: its place in words and zone from the built-in tables. */
+void wx_place_at(double lat, double lon, struct wx_place *p);
+
+/* ---- openmeteo.c, metno.c: a forecast ---- */
+
+#define WX_DAYS 16
+#define WX_HOURS 48
+
+struct wx_now {
+ char time[20]; /* local, "2026-10-01T13:30" */
+ double temp, feels, humidity, precip, cloud, pressure;
+ double wind, wind_dir, gust; /* km/h, degrees from */
+ int code; /* WMO weather code; -1: none */
+ char symbol[48]; /* MET Norway's, when it is the source */
+ int is_day;
+};
+
+struct wx_day {
+ char date[11];
+ int code;
+ char symbol[48];
+ double tmin, tmax, rain, rain_prob, wind, gust, wind_dir, uv;
+ char sunrise[6], sunset[6]; /* "07:05"; "" when not given */
+};
+
+struct wx_hour {
+ char time[20];
+ double temp, rain, rain_prob, wind, wind_dir, gust;
+ int code;
+ char symbol[48];
+};
+
+struct wx_forecast {
+ const char *source; /* "Open-Meteo", "MET Norway" */
+ double grid_lat, grid_lon, grid_elev; /* where the model was read */
+ char tz[48], tz_abbr[16];
+ struct wx_now now;
+ int has_now;
+ struct wx_day day[WX_DAYS];
+ int n_day;
+ struct wx_hour hour[WX_HOURS];
+ int n_hour;
+};
+
+/* Open-Meteo: now, days days ahead and the hours of the next two days. */
+int wx_om_forecast(const struct wx_place *p, int days, struct wx_forecast *f,
+ char *err, size_t err_len);
+int wx_om_parse(const char *text, size_t n, struct wx_forecast *f, char *err,
+ size_t err_len);
+/* MET Norway's locationforecast, into the same, in the place's zone. */
+int wx_met_forecast(const struct wx_place *p, int days, struct wx_forecast *f,
+ char *err, size_t err_len);
+int wx_met_parse(const char *text, size_t n, const char *tz,
+ struct wx_forecast *f, char *err, size_t err_len);
+
+/* ---- openmeteo.c: the sea ---- */
+
+#define WX_SEA_POINTS 9
+
+struct wx_sea_day {
+ char date[11];
+ double wave_max, wave_dir, period_max;
+ double wind_max, gust_max, wind_dir; /* the forecast's, at the point */
+};
+
+struct wx_sea {
+ double lat, lon; /* the point asked */
+ double cell_lat, cell_lon; /* the cell of the sea model answering */
+ int ok; /* the model has sea there */
+ char time[20]; /* of the values now, in tz */
+ double wave, wave_dir, period, wind_wave, swell, swell_dir, sst;
+ double wind, wind_dir, gust; /* km/h, from the forecast */
+ struct wx_sea_day day[WX_DAYS];
+ int n_day;
+};
+
+/* The sea at n points, days days ahead, times in the zone tz: Open-Meteo's
+ waves and its wind (two calls for all the points). 0, or -1. */
+int wx_om_marine(struct wx_sea *s, int n, int days, const char *tz, char *err,
+ size_t err_len);
+/* The waves' answer, then the wind's, into s. */
+int wx_om_marine_parse(const char *text, size_t len, struct wx_sea *s, int n,
+ char *err, size_t err_len);
+int wx_om_wind_parse(const char *text, size_t len, struct wx_sea *s, int n,
+ char *err, size_t err_len);
+
+/* ---- metar.c: what a station measured ---- */
+
+struct wx_obs {
+ char icao[5], name[96];
+ double lat, lon, km; /* the station, its distance from the place */
+ time_t at; /* when it was measured */
+ double temp, dew, wind_dir, wind_kt, gust_kt, pressure;
+ int variable_wind; /* direction "VRB" */
+ char visib[8]; /* statute miles as given: "6+", "1 1/2" */
+ char wx[32]; /* present weather, as coded: "-RA", "TSRA" */
+ char clouds[96]; /* "few at 1500 ft, scattered at 1700 ft" */
+ char raw[160];
+};
+
+/* The observation of the station nearest the point within max_km. 1, 0
+ when none, -1 when it could not be asked. */
+int wx_metar_near(double lat, double lon, double max_km, struct wx_obs *o,
+ char *err, size_t err_len);
+int wx_metar_parse(const char *text, size_t n, double lat, double lon,
+ double max_km, struct wx_obs *o, char *err, size_t err_len);
+
+/* ---- alerts.c ---- */
+
+struct wx_alert {
+ char event[96]; /* "Allerta gialla per temporali" */
+ char level[16]; /* "yellow" */
+ int mine; /* for the place's region */
+ char area[96]; /* "Sicilia" */
+ char onset[26], expires[26];
+ char sender[96];
+ char text[512]; /* description, cut */
+};
+
+/* "2026-10-01T14:00:00+00:00" as a time; 0 when not one. */
+time_t wx_iso_time(const char *s);
+/* MeteoAlarm's warnings in force for the place's country, those of its
+ region first, in lang when given in it ("it", "en"). *v is malloc'd. */
+int wx_meteoalarm(const struct wx_place *p, const char *lang,
+ struct wx_alert **v, size_t *n, char *err, size_t err_len);
+int wx_meteoalarm_parse(const char *text, size_t len, const char *region,
+ const char *lang, time_t now, struct wx_alert **v,
+ size_t *n, char *err, size_t err_len);
+
+/* The Italian Civil Protection's bulletin for a municipality: the zones
+ of alert it is in and their levels, for the day the place lives and the
+ next when the bulletin has it. */
+struct wx_dpc {
+ char issued[16]; /* "20260930_1423" */
+ char zones[192]; /* "Nord-Occidentale e isole Egadi e Ustica" */
+ char day[2][11]; /* the dates the two sets are for; "" when none */
+ char level[2][3][96]; /* hydraulic, hydrogeological, thunderstorms */
+};
+
+/* 1 when the place is in the bulletin, 0 when not found, -1 on error. */
+int wx_dpc(const struct wx_place *p, struct wx_dpc *d, char *err,
+ size_t err_len);
+/* A bulletin's day read: the levels of the zones holding the municipality
+ (the highest, when it is in several), the zones' names; when no zone
+ names it, the zone the point is in (lat, lon NAN: none). 1, 0, -1. */
+int wx_dpc_parse(const char *text, size_t len, const char *comune, double lat,
+ double lon, char out[3][96], char *zones, size_t zones_len,
+ char *err, size_t err_len);
+
+/* ---- words.c ---- */
+
+/* The WMO weather code in words ("light rain"); NULL when unknown. */
+const char *wx_code_text(int code);
+/* MET Norway's symbol ("lightrainshowers_day") in words. */
+void wx_symbol_text(const char *symbol, char *out, size_t cap);
+/* The wind's force in words, on the Beaufort scale ("moderate breeze"). */
+const char *wx_wind_words(double kmh);
+/* The sea's state from the waves' height, on the Douglas scale. */
+const char *wx_sea_words(double m);
+/* "from the north-west (321°)" */
+void wx_from_dir(double deg, char *out, size_t cap);
+
+/* ---- tools.c: the tools, and what they share ---- */
+
+void wx_tools_list(void *ctx, struct janas_buf *b);
+int wx_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b);
+
+/* An argument: a string (NULL when absent), a number (def), a boolean. */
+const char *wx_arg_str(const struct janas_json *args, const char *name);
+double wx_arg_num(const struct janas_json *args, const char *name, double def);
+int wx_arg_bool(const struct janas_json *args, const char *name, int def);
+/* The place of the arguments ("place", or "latitude" and "longitude"):
+ 0, or -1 with the error already written as the tool's result. */
+int wx_arg_place(const struct janas_json *args, struct wx_place *p,
+ struct janas_buf *b);
+/* t as "13:55" in the zone tz (the machine's when NULL), and the day when
+ it is not today there. */
+void wx_local_time(time_t t, const char *tz, char *out, size_t cap);
+/* "2026-10-02" -> "Friday 2 October" */
+void wx_day_name(const char *date, char *out, size_t cap);
+/* "Trapani (Sicilia, Italia)" */
+void wx_place_name(const struct wx_place *p, char *out, size_t cap);
+/* When the user named no place (how, from struct wx_place, not ""): a
+ last line telling the model to say which place it was and how known. */
+void wx_place_note(const char *how, struct janas_buf *out);
+/* The text as the tool's result, and freed. */
+int wx_result(struct janas_buf *out, struct janas_buf *b, int is_error);
+
+/* ---- report.c, sea.c, warn.c: the tools ---- */
+
+int wx_tool_now(const struct janas_json *args, struct janas_buf *b);
+int wx_tool_forecast(const struct janas_json *args, struct janas_buf *b);
+int wx_tool_sea(const struct janas_json *args, struct janas_buf *b);
+int wx_tool_alerts(const struct janas_json *args, struct janas_buf *b);
+
+#endif
diff --git a/src/weather/words.c b/src/weather/words.c
new file mode 100644
index 0000000..3ab8beb
--- /dev/null
+++ b/src/weather/words.c
@@ -0,0 +1,192 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * words.c - the weather in words (see weather.h): the WMO codes Open-Meteo
+ * gives, MET Norway's symbols, the wind on the Beaufort scale, the sea on
+ * the Douglas scale, directions as the points of the compass. The model
+ * telling them then repeats words, not tables it would have to know.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "common/geo.h"
+#include "weather.h"
+
+const char *wx_code_text(int code)
+{
+ switch (code) {
+ case 0:
+ return "clear sky";
+ case 1:
+ return "mainly clear";
+ case 2:
+ return "partly cloudy";
+ case 3:
+ return "overcast";
+ case 45:
+ return "fog";
+ case 48:
+ return "fog depositing rime";
+ case 51:
+ return "light drizzle";
+ case 53:
+ return "drizzle";
+ case 55:
+ return "dense drizzle";
+ case 56:
+ return "light freezing drizzle";
+ case 57:
+ return "dense freezing drizzle";
+ case 61:
+ return "light rain";
+ case 63:
+ return "rain";
+ case 65:
+ return "heavy rain";
+ case 66:
+ return "light freezing rain";
+ case 67:
+ return "heavy freezing rain";
+ case 71:
+ return "light snow";
+ case 73:
+ return "snow";
+ case 75:
+ return "heavy snow";
+ case 77:
+ return "snow grains";
+ case 80:
+ return "light rain showers";
+ case 81:
+ return "rain showers";
+ case 82:
+ return "violent rain showers";
+ case 85:
+ return "light snow showers";
+ case 86:
+ return "heavy snow showers";
+ case 95:
+ return "thunderstorm";
+ case 96:
+ return "thunderstorm with light hail";
+ case 99:
+ return "thunderstorm with heavy hail";
+ default:
+ return NULL;
+ }
+}
+
+void wx_symbol_text(const char *symbol, char *out, size_t cap)
+{
+ /* "lightrainshowersandthunder_day": the words run together, the part
+ of the day after an underscore */
+ static const struct {
+ const char *from, *to;
+ } w[] = {
+ {"clearsky", "clear sky"},
+ {"partlycloudy", "partly cloudy"},
+ {"fair", "fair"},
+ {"cloudy", "cloudy"},
+ {"fog", "fog"},
+ {"light", "light "},
+ {"heavy", "heavy "},
+ {"rainshowers", "rain showers"},
+ {"sleetshowers", "sleet showers"},
+ {"snowshowers", "snow showers"},
+ {"rain", "rain"},
+ {"sleet", "sleet"},
+ {"snow", "snow"},
+ {"andthunder", " and thunder"},
+ };
+ size_t n = 0;
+ out[0] = 0;
+ const char *s = symbol ? symbol : "";
+ while (*s && *s != '_') {
+ size_t i;
+ for (i = 0; i < sizeof w / sizeof w[0]; i++) {
+ size_t k = strlen(w[i].from);
+ if (strncmp(s, w[i].from, k) == 0) {
+ n += (size_t)snprintf(out + n, n < cap ? cap - n : 0, "%s",
+ w[i].to);
+ s += k;
+ break;
+ }
+ }
+ if (i == sizeof w / sizeof w[0]) { /* a word not known: as it is */
+ if (n + 1 < cap) {
+ out[n++] = *s;
+ out[n] = 0;
+ }
+ s++;
+ }
+ if (n >= cap) {
+ out[cap - 1] = 0;
+ return;
+ }
+ }
+}
+
+const char *wx_wind_words(double kmh)
+{
+ static const struct {
+ double below;
+ const char *name;
+ } b[] = {
+ {1, "calm"}, {6, "light air"}, {12, "light breeze"},
+ {20, "gentle breeze"}, {29, "moderate breeze"}, {39, "fresh breeze"},
+ {50, "strong breeze"}, {62, "near gale"}, {75, "gale"},
+ {89, "strong gale"}, {103, "storm"}, {118, "violent storm"},
+ };
+ for (size_t i = 0; i < sizeof b / sizeof b[0]; i++)
+ if (kmh < b[i].below)
+ return b[i].name;
+ return "hurricane force";
+}
+
+const char *wx_sea_words(double m)
+{
+ if (m < 0.1)
+ return "calm";
+ if (m < 0.5)
+ return "smooth";
+ if (m < 1.25)
+ return "slight";
+ if (m < 2.5)
+ return "moderate";
+ if (m < 4)
+ return "rough";
+ if (m < 6)
+ return "very rough";
+ if (m < 9)
+ return "high";
+ if (m < 14)
+ return "very high";
+ return "phenomenal";
+}
+
+void wx_from_dir(double deg, char *out, size_t cap)
+{
+ static const struct {
+ const char *abbr, *name;
+ } w[] = {
+ {"N", "north"}, {"NNE", "north-north-east"},
+ {"NE", "north-east"}, {"ENE", "east-north-east"},
+ {"E", "east"}, {"ESE", "east-south-east"},
+ {"SE", "south-east"}, {"SSE", "south-south-east"},
+ {"S", "south"}, {"SSW", "south-south-west"},
+ {"SW", "south-west"}, {"WSW", "west-south-west"},
+ {"W", "west"}, {"WNW", "west-north-west"},
+ {"NW", "north-west"}, {"NNW", "north-north-west"},
+ };
+ if (isnan(deg)) {
+ snprintf(out, cap, "from a direction not given");
+ return;
+ }
+ const char *a = geo_compass(deg);
+ const char *name = a;
+ for (size_t i = 0; i < sizeof w / sizeof w[0]; i++)
+ if (strcmp(w[i].abbr, a) == 0)
+ name = w[i].name;
+ snprintf(out, cap, "from the %s (%.0f°)", name, deg);
+}
diff --git a/tests/test_flights_parse.c b/tests/test_flights_parse.c
index 4cf67e9..fc4f25f 100644
--- a/tests/test_flights_parse.c
+++ b/tests/test_flights_parse.c
@@ -6,7 +6,7 @@
* the evening before), a codeshare and an error, made by hand. The times
* come in the airport's local time marked +00:00: read in its zone.
* schedule.c belongs to the program, so it is compiled in here, with a
- * fl_get that never goes out and quotes the address in its error.
+ * janas_https_get that never goes out and quotes the address in its error.
*/
#include <stdio.h>
#include <string.h>
@@ -14,8 +14,9 @@
#include "flights/schedule.c"
-int fl_get(const char *url, const char *const *headers, size_t n_headers,
- struct janas_buf *out, char *err, size_t err_len)
+int janas_https_get(const char *url, const char *const *headers,
+ size_t n_headers, struct janas_buf *out, char *err,
+ size_t err_len)
{
(void)headers, (void)n_headers, (void)out;
/* as the URL parser does: its errors quote the address */
diff --git a/tests/test_geo.c b/tests/test_geo.c
index 828dd24..f04ce8c 100644
--- a/tests/test_geo.c
+++ b/tests/test_geo.c
@@ -10,7 +10,7 @@
#include <string.h>
#include <unistd.h>
-#include "flights/geo.c"
+#include "common/geo.c"
static int failures;
diff --git a/tests/test_locate.c b/tests/test_locate.c
new file mode 100644
index 0000000..d8d1a3f
--- /dev/null
+++ b/tests/test_locate.c
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_locate.c - where the user is (src/common/locate.c), without the
+ * network: the answers of GeoJS and ipwho.is as they come (numbers as
+ * strings in the first, a nested zone in the second), the broken ones, and
+ * JANAS_LOCATION as a city, a point, "off" and nonsense.
+ */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "common/locate.h"
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+static void test_parsers(void)
+{
+ struct janas_where w;
+ const char *geojs =
+ "{\"organization_name\":\"Example\",\"region\":\"Lazio\","
+ "\"accuracy\":20,\"country_code\":\"IT\",\"longitude\":\"12.4839\","
+ "\"city\":\"Rome\",\"timezone\":\"Europe/Rome\",\"country\":"
+ "\"Italy\",\"latitude\":\"41.8919\"}";
+ CHECK(janas_where_geojs(geojs, strlen(geojs), &w) == 0, "geojs");
+ CHECK(fabs(w.lat - 41.8919) < 1e-9 && fabs(w.lon - 12.4839) < 1e-9,
+ "geojs point %f %f", w.lat, w.lon);
+ CHECK(strcmp(w.city, "Rome") == 0 && strcmp(w.region, "Lazio") == 0 &&
+ strcmp(w.cc, "IT") == 0 && strcmp(w.tz, "Europe/Rome") == 0,
+ "geojs fields: %s %s %s %s", w.city, w.region, w.cc, w.tz);
+ const char *nopos = "{\"country\":\"Italy\",\"latitude\":\"nil\"}";
+ CHECK(janas_where_geojs(nopos, strlen(nopos), &w) != 0, "geojs no point");
+ CHECK(janas_where_geojs("<html>", 6, &w) != 0, "geojs not json");
+
+ const char *whois =
+ "{\"success\": true, \"country\": \"Italy\", \"country_code\": "
+ "\"IT\", \"region\": \"Sicilia\", \"city\": \"Palermo\", "
+ "\"latitude\": 38.1157, \"longitude\": 13.3615, \"timezone\": "
+ "{\"id\": \"Europe/Rome\", \"abbr\": \"CEST\"}}";
+ CHECK(janas_where_ipwhois(whois, strlen(whois), &w) == 0, "ipwhois");
+ CHECK(fabs(w.lat - 38.1157) < 1e-9 && strcmp(w.city, "Palermo") == 0 &&
+ strcmp(w.tz, "Europe/Rome") == 0,
+ "ipwhois fields: %f %s %s", w.lat, w.city, w.tz);
+ const char *fail = "{\"success\": false, \"message\": \"Reserved "
+ "range\", \"latitude\": 0, \"longitude\": 0}";
+ CHECK(janas_where_ipwhois(fail, strlen(fail), &w) != 0, "ipwhois failed");
+}
+
+static void test_setting(void)
+{
+ struct janas_where w;
+ char err[256];
+ setenv("JANAS_LOCATION", "off", 1);
+ CHECK(janas_where(&w, err, sizeof err) != 0 && strstr(err, "off"),
+ "off: %s", err);
+ setenv("JANAS_LOCATION", "Trapani", 1);
+ CHECK(janas_where(&w, err, sizeof err) == 0 && fabs(w.lat - 38.02) < 0.1 &&
+ fabs(w.lon - 12.51) < 0.1 && strcmp(w.tz, "Europe/Rome") == 0 &&
+ strstr(w.how, "JANAS_"),
+ "Trapani: %f %f %s %s", w.lat, w.lon, w.tz, w.how);
+ setenv("JANAS_LOCATION", "45.07, 7.69", 1);
+ CHECK(janas_where(&w, err, sizeof err) == 0 && fabs(w.lat - 45.07) < 1e-9 &&
+ strcmp(w.cc, "IT") == 0 && strcmp(w.tz, "Europe/Rome") == 0 &&
+ strstr(w.country, "Ital"),
+ "point: %f %s %s", w.lat, w.tz, w.country);
+ setenv("JANAS_LOCATION", "Xyzzyville", 1);
+ CHECK(janas_where(&w, err, sizeof err) != 0 && strstr(err, "Xyzzyville"),
+ "nonsense: %s", err);
+ unsetenv("JANAS_LOCATION");
+}
+
+int main(void)
+{
+ test_parsers();
+ test_setting();
+ if (failures) {
+ printf("test_locate: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_locate: ok\n");
+ return 0;
+}
diff --git a/tests/test_tools.c b/tests/test_tools.c
index d36ac11..5e487fa 100644
--- a/tests/test_tools.c
+++ b/tests/test_tools.c
@@ -204,6 +204,20 @@ static void test_grammar(void)
CHECK(!call_ok(JANAS_TOOLS_XML, "<function=get_weather>\n<parameter="
"days>\nx\n</parameter>\n</function>"),
"grammar xml: bad integer, required missing");
+ CHECK(call_ok(JANAS_TOOLS_XML,
+ "\n<function=get_weather>\n<parameter=days>\n2\n"
+ "</parameter>\n<parameter=city>\nRome\n</parameter>\n"
+ "</function>\n"),
+ "grammar xml: any order");
+ CHECK(!call_ok(JANAS_TOOLS_XML,
+ "\n<function=get_weather>\n<parameter=city>\nRome\n"
+ "</parameter>\n<parameter=city>\nOslo\n</parameter>\n"
+ "</function>\n"),
+ "grammar xml: a parameter twice");
+ CHECK(!call_ok(JANAS_TOOLS_XML,
+ "\n<function=get_weather>\n<parameter=days>\n2\n"
+ "</parameter>\n</function>\n"),
+ "grammar xml: required missing");
}
static uint64_t rng = 0x70015;
diff --git a/tests/test_weather_parse.c b/tests/test_weather_parse.c
new file mode 100644
index 0000000..b257132
--- /dev/null
+++ b/tests/test_weather_parse.c
@@ -0,0 +1,882 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_weather_parse.c - janas-weather's reading of its sources' answers,
+ * without the network: answers as they came on 1 October 2026 (Trapani's
+ * forecast from Open-Meteo, the sea at three points, Trapani-Birgi's
+ * METAR, MET Norway's series, cut to forty hours), MeteoAlarm's feed for
+ * Italy with a yellow and an orange warning made from its own (that day
+ * every warning was green) and two zones of the Civil Protection's
+ * bulletin made from one of its own; and the words.
+ * The sources belong to the program, so they are compiled in here.
+ */
+#define _GNU_SOURCE
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "weather/alerts.c"
+#include "weather/fetch.c"
+#include "weather/metar.c"
+#include "weather/metno.c"
+#include "weather/openmeteo.c"
+#include "weather/words.c"
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+static const char OM_FORECAST[] =
+ "{\"latitude\": 38.0, \"longitude\": 12.5625, \"generationtime_ms\": 0.36"
+ "41843795776367, \"utc_offset_seconds\": 7200, \"timezone\": \"Europe/Rom"
+ "e\", \"timezone_abbreviation\": \"GMT+2\", \"elevation\": 6.0, \"current"
+ "_units\": {\"time\": \"iso8601\", \"interval\": \"seconds\", \"temperatu"
+ "re_2m\": \"°C\", \"relative_humidity_2m\": \"%\", \"apparent_temperature"
+ "\": \"°C\", \"precipitation\": \"mm\", \"weather_code\": \"wmo code\", "
+ "\"cloud_cover\": \"%\", \"pressure_msl\": \"hPa\", \"wind_speed_10m\": \""
+ "km/h\", \"wind_direction_10m\": \"°\", \"wind_gusts_10m\": \"km/h\", \"i"
+ "s_day\": \"\"}, \"current\": {\"time\": \"2026-10-01T13:45\", \"interval"
+ "\": 900, \"temperature_2m\": 26.3, \"relative_humidity_2m\": 48, \"appar"
+ "ent_temperature\": 26.5, \"precipitation\": 0.0, \"weather_code\": 0, \""
+ "cloud_cover\": 14, \"pressure_msl\": 1022.8, \"wind_speed_10m\": 13.4, "
+ "\"wind_direction_10m\": 324, \"wind_gusts_10m\": 27.0, \"is_day\": 1}, \""
+ "hourly_units\": {\"time\": \"iso8601\", \"temperature_2m\": \"°C\", \"pr"
+ "ecipitation_probability\": \"%\", \"precipitation\": \"mm\", \"weather_c"
+ "ode\": \"wmo code\", \"wind_speed_10m\": \"km/h\", \"wind_direction_10m"
+ "\": \"°\", \"wind_gusts_10m\": \"km/h\"}, \"hourly\": {\"time\": [\"2026-"
+ "10-01T00:00\", \"2026-10-01T01:00\", \"2026-10-01T02:00\", \"2026-10-01T"
+ "03:00\", \"2026-10-01T04:00\", \"2026-10-01T05:00\", \"2026-10-01T06:00"
+ "\", \"2026-10-01T07:00\", \"2026-10-01T08:00\", \"2026-10-01T09:00\", \"2"
+ "026-10-01T10:00\", \"2026-10-01T11:00\", \"2026-10-01T12:00\", \"2026-10"
+ "-01T13:00\", \"2026-10-01T14:00\", \"2026-10-01T15:00\", \"2026-10-01T16"
+ ":00\", \"2026-10-01T17:00\", \"2026-10-01T18:00\", \"2026-10-01T19:00\","
+ " \"2026-10-01T20:00\", \"2026-10-01T21:00\", \"2026-10-01T22:00\", \"202"
+ "6-10-01T23:00\", \"2026-10-02T00:00\", \"2026-10-02T01:00\", \"2026-10-0"
+ "2T02:00\", \"2026-10-02T03:00\", \"2026-10-02T04:00\", \"2026-10-02T05:0"
+ "0\", \"2026-10-02T06:00\", \"2026-10-02T07:00\", \"2026-10-02T08:00\", "
+ "\"2026-10-02T09:00\", \"2026-10-02T10:00\", \"2026-10-02T11:00\", \"2026-"
+ "10-02T12:00\", \"2026-10-02T13:00\", \"2026-10-02T14:00\", \"2026-10-02T"
+ "15:00\", \"2026-10-02T16:00\", \"2026-10-02T17:00\", \"2026-10-02T18:00"
+ "\", \"2026-10-02T19:00\", \"2026-10-02T20:00\", \"2026-10-02T21:00\", \"2"
+ "026-10-02T22:00\", \"2026-10-02T23:00\", \"2026-10-03T00:00\", \"2026-10"
+ "-03T01:00\", \"2026-10-03T02:00\", \"2026-10-03T03:00\", \"2026-10-03T04"
+ ":00\", \"2026-10-03T05:00\", \"2026-10-03T06:00\", \"2026-10-03T07:00\","
+ " \"2026-10-03T08:00\", \"2026-10-03T09:00\", \"2026-10-03T10:00\", \"202"
+ "6-10-03T11:00\", \"2026-10-03T12:00\", \"2026-10-03T13:00\", \"2026-10-0"
+ "3T14:00\", \"2026-10-03T15:00\", \"2026-10-03T16:00\", \"2026-10-03T17:0"
+ "0\", \"2026-10-03T18:00\", \"2026-10-03T19:00\", \"2026-10-03T20:00\", "
+ "\"2026-10-03T21:00\", \"2026-10-03T22:00\", \"2026-10-03T23:00\"], \"temp"
+ "erature_2m\": [18.7, 18.2, 17.8, 17.5, 17.3, 17.0, 16.7, 16.5, 17.0, 20."
+ "0, 23.4, 25.1, 26.1, 26.4, 26.3, 26.6, 26.3, 26.3, 25.8, 24.4, 23.1, 22."
+ "1, 21.1, 19.7, 18.8, 18.4, 18.1, 17.7, 17.4, 17.2, 17.1, 16.9, 17.6, 20."
+ "5, 23.7, 25.4, 26.7, 27.1, 26.6, 26.4, 26.2, 25.9, 25.5, 24.5, 23.3, 22."
+ "2, 20.8, 19.6, 18.9, 18.5, 18.2, 17.9, 17.7, 17.6, 17.8, 17.8, 18.3, 20."
+ "9, 23.4, 24.8, 25.7, 26.4, 25.9, 25.8, 25.7, 25.5, 25.0, 24.1, 23.0, 22."
+ "0, 20.7, 19.7], \"precipitation_probability\": [0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"precipitation\": [0.0"
+ ", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "
+ "0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0."
+ "0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,"
+ " 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0"
+ ".0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], \""
+ "weather_code\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0"
+ ", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 2, 1, 1, 0, 1"
+ ", 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 1, 2, 2, 3, 2, 2, 2, 2"
+ ", 1, 1, 1, 1, 1], \"wind_speed_10m\": [5.6, 6.4, 6.3, 6.6, 6.5, 6.1, 6.1"
+ ", 6.6, 6.1, 4.0, 2.6, 0.7, 4.5, 11.7, 13.8, 14.8, 13.8, 16.3, 14.3, 9.7,"
+ " 6.5, 5.4, 4.2, 4.3, 5.1, 5.5, 6.2, 6.2, 6.1, 6.1, 6.5, 6.1, 5.8, 4.5, 3"
+ ".5, 2.5, 3.0, 10.7, 13.6, 13.5, 11.7, 11.3, 10.4, 8.7, 6.0, 5.1, 5.3, 5."
+ "1, 5.9, 5.9, 6.2, 5.8, 5.8, 5.8, 5.4, 5.8, 5.8, 4.8, 5.2, 2.5, 2.3, 7.4,"
+ " 11.7, 11.8, 11.4, 10.1, 9.7, 7.8, 6.4, 5.4, 5.0, 5.4], \"wind_direction"
+ "_10m\": [75, 74, 77, 81, 84, 90, 87, 81, 90, 100, 146, 180, 299, 313, 32"
+ "7, 331, 354, 25, 45, 39, 34, 42, 59, 85, 82, 79, 80, 83, 90, 90, 87, 90,"
+ " 90, 104, 156, 188, 284, 315, 310, 304, 326, 343, 358, 7, 17, 45, 62, 82"
+ ", 79, 79, 80, 83, 90, 94, 94, 94, 94, 103, 146, 180, 288, 313, 313, 322,"
+ " 349, 354, 2, 13, 27, 42, 60, 70], \"wind_gusts_10m\": [13.0, 15.1, 15.8"
+ ", 16.2, 16.2, 15.8, 15.5, 15.1, 14.4, 13.0, 10.1, 9.7, 11.5, 24.8, 27.4,"
+ " 28.1, 28.4, 36.4, 35.3, 29.9, 23.0, 19.8, 17.3, 14.8, 11.5, 11.5, 13.3,"
+ " 14.0, 14.0, 14.0, 13.0, 13.0, 12.2, 11.2, 10.1, 13.0, 7.6, 18.4, 28.1, "
+ "32.0, 27.0, 25.6, 23.4, 22.3, 19.4, 16.2, 13.7, 13.0, 13.0, 12.2, 13.0, "
+ "13.0, 13.3, 12.6, 10.8, 10.1, 11.2, 11.5, 13.3, 14.4, 7.9, 16.6, 25.2, 2"
+ "6.6, 25.6, 25.6, 21.6, 20.5, 19.1, 17.6, 15.1, 13.7]}, \"daily_units\": "
+ "{\"time\": \"iso8601\", \"weather_code\": \"wmo code\", \"temperature_2m"
+ "_max\": \"°C\", \"temperature_2m_min\": \"°C\", \"precipitation_sum\": "
+ "\"mm\", \"precipitation_probability_max\": \"%\", \"wind_speed_10m_max\":"
+ " \"km/h\", \"wind_gusts_10m_max\": \"km/h\", \"wind_direction_10m_domina"
+ "nt\": \"°\", \"sunrise\": \"iso8601\", \"sunset\": \"iso8601\", \"uv_ind"
+ "ex_max\": \"\"}, \"daily\": {\"time\": [\"2026-10-01\", \"2026-10-02\", "
+ "\"2026-10-03\"], \"weather_code\": [3, 3, 3], \"temperature_2m_max\": [2"
+ "6.6, 27.1, 26.4], \"temperature_2m_min\": [16.5, 16.9, 17.6], \"precipit"
+ "ation_sum\": [0.0, 0.0, 0.0], \"precipitation_probability_max\": [0, 0, "
+ "0], \"wind_speed_10m_max\": [16.3, 13.6, 11.8], \"wind_gusts_10m_max\": "
+ "[36.4, 32.0, 26.6], \"wind_direction_10m_dominant\": [36, 24, 36], \"sun"
+ "rise\": [\"2026-10-01T07:05\", \"2026-10-02T07:06\", \"2026-10-03T07:07"
+ "\"], \"sunset\": [\"2026-10-01T18:52\", \"2026-10-02T18:51\", \"2026-10-0"
+ "3T18:49\"], \"uv_index_max\": [5.9, 5.9, 5.8]}}";
+
+static const char OM_MARINE[] =
+ "[{\"latitude\": 39.541664, \"longitude\": 11.9583435, \"generationtime_m"
+ "s\": 0.23055076599121094, \"utc_offset_seconds\": 7200, \"timezone\": \""
+ "Europe/Rome\", \"timezone_abbreviation\": \"GMT+2\", \"elevation\": 0.0,"
+ " \"current_units\": {\"time\": \"iso8601\", \"interval\": \"seconds\", "
+ "\"wave_height\": \"m\", \"wave_direction\": \"°\", \"wave_period\": \"s\""
+ ", \"wind_wave_height\": \"m\", \"swell_wave_height\": \"m\", \"swell_wav"
+ "e_direction\": \"°\", \"sea_surface_temperature\": \"°C\"}, \"current\":"
+ " {\"time\": \"2026-10-01T13:45\", \"interval\": 900, \"wave_height\": 0."
+ "1, \"wave_direction\": 103, \"wave_period\": 2.95, \"wind_wave_height\":"
+ " 0.0, \"swell_wave_height\": 0.08, \"swell_wave_direction\": 69, \"sea_s"
+ "urface_temperature\": 26.7}, \"daily_units\": {\"time\": \"iso8601\", \""
+ "wave_height_max\": \"m\", \"wave_direction_dominant\": \"°\", \"wave_per"
+ "iod_max\": \"s\"}, \"daily\": {\"time\": [\"2026-10-01\", \"2026-10-02\""
+ "], \"wave_height_max\": [0.14, 0.06], \"wave_direction_dominant\": [115,"
+ " 151], \"wave_period_max\": [3.3, 2.95]}}, {\"latitude\": 40.541664, \"l"
+ "ongitude\": 10.9583435, \"generationtime_ms\": 0.10025501251220703, \"ut"
+ "c_offset_seconds\": 7200, \"timezone\": \"Europe/Rome\", \"timezone_abbr"
+ "eviation\": \"GMT+2\", \"elevation\": 0.0, \"location_id\": 1, \"current"
+ "_units\": {\"time\": \"iso8601\", \"interval\": \"seconds\", \"wave_heig"
+ "ht\": \"m\", \"wave_direction\": \"°\", \"wave_period\": \"s\", \"wind_w"
+ "ave_height\": \"m\", \"swell_wave_height\": \"m\", \"swell_wave_directio"
+ "n\": \"°\", \"sea_surface_temperature\": \"°C\"}, \"current\": {\"time\""
+ ": \"2026-10-01T13:45\", \"interval\": 900, \"wave_height\": 0.14, \"wave"
+ "_direction\": 149, \"wave_period\": 3.4, \"wind_wave_height\": 0.0, \"sw"
+ "ell_wave_height\": 0.12, \"swell_wave_direction\": 175, \"sea_surface_te"
+ "mperature\": 26.8}, \"daily_units\": {\"time\": \"iso8601\", \"wave_heig"
+ "ht_max\": \"m\", \"wave_direction_dominant\": \"°\", \"wave_period_max\""
+ ": \"s\"}, \"daily\": {\"time\": [\"2026-10-01\", \"2026-10-02\"], \"wave"
+ "_height_max\": [0.2, 0.12], \"wave_direction_dominant\": [159, 178], \"w"
+ "ave_period_max\": [3.85, 3.7]}}, {\"latitude\": 38.041664, \"longitude\""
+ ": 12.375015, \"generationtime_ms\": 0.09393692016601562, \"utc_offset_se"
+ "conds\": 7200, \"timezone\": \"Europe/Rome\", \"timezone_abbreviation\":"
+ " \"GMT+2\", \"elevation\": 10.0, \"location_id\": 2, \"current_units\": "
+ "{\"time\": \"iso8601\", \"interval\": \"seconds\", \"wave_height\": \"m"
+ "\", \"wave_direction\": \"°\", \"wave_period\": \"s\", \"wind_wave_height"
+ "\": \"m\", \"swell_wave_height\": \"m\", \"swell_wave_direction\": \"°\""
+ ", \"sea_surface_temperature\": \"°C\"}, \"current\": {\"time\": \"2026-1"
+ "0-01T13:45\", \"interval\": 900, \"wave_height\": 0.08, \"wave_direction"
+ "\": 70, \"wave_period\": 2.95, \"wind_wave_height\": 0.0, \"swell_wave_h"
+ "eight\": 0.04, \"swell_wave_direction\": 40, \"sea_surface_temperature\""
+ ": 24.9}, \"daily_units\": {\"time\": \"iso8601\", \"wave_height_max\": "
+ "\"m\", \"wave_direction_dominant\": \"°\", \"wave_period_max\": \"s\"}, "
+ "\"daily\": {\"time\": [\"2026-10-01\", \"2026-10-02\"], \"wave_height_max"
+ "\": [0.34, 0.24], \"wave_direction_dominant\": [65, 55], \"wave_period_m"
+ "ax\": [3.05, 2.85]}}]";
+
+static const char METAR_BBOX[] =
+ "[{\"icaoId\": \"LICT\", \"receiptTime\": \"2026-10-01T11:08:42.072Z\", "
+ "\"obsTime\": 1790852100, \"reportTime\": \"2026-10-01T11:00:00.000Z\", \""
+ "temp\": 26, \"dewp\": 19, \"wdir\": 340, \"wspd\": 8, \"visib\": \"6+\","
+ " \"altim\": 1022, \"qcField\": 0, \"metarType\": \"METAR\", \"rawOb\": "
+ "\"METAR LICT 011055Z 34008KT 9999 FEW015 SCT017 26/19 Q1022\", \"lat\": 3"
+ "7.911, \"lon\": 12.488, \"elev\": 4, \"name\": \"Trapani/Birgi Arpt, TP,"
+ " IT\", \"cover\": \"SCT\", \"clouds\": [{\"cover\": \"FEW\", \"base\": 1"
+ "500}, {\"cover\": \"SCT\", \"base\": 1700}], \"fltCat\": \"VFR\"}]";
+
+static const char MET_NORWAY[] =
+ "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":["
+ "12.51,38.02,2]},\"properties\":{\"meta\":{\"updated_at\":\"2026-10-01T11"
+ ":26:50Z\",\"units\":{\"air_pressure_at_sea_level\":\"hPa\",\"air_tempera"
+ "ture\":\"celsius\",\"cloud_area_fraction\":\"%\",\"precipitation_amount"
+ "\":\"mm\",\"relative_humidity\":\"%\",\"wind_from_direction\":\"degrees\""
+ ",\"wind_speed\":\"m/s\"}},\"timeseries\":[{\"time\":\"2026-10-01T11:00:0"
+ "0Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1"
+ "023.4,\"air_temperature\":26.1,\"cloud_area_fraction\":31.2,\"relative_h"
+ "umidity\":57.7,\"wind_from_direction\":307.4,\"wind_speed\":3.6}},\"next"
+ "_12_hours\":{\"summary\":{\"symbol_code\":\"lightrainshowers_day\"},\"de"
+ "tails\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"rainshowers"
+ "_day\"},\"details\":{\"precipitation_amount\":0.5}},\"next_6_hours\":{\""
+ "summary\":{\"symbol_code\":\"lightrainshowers_day\"},\"details\":{\"prec"
+ "ipitation_amount\":0.7}}}},{\"time\":\"2026-10-01T12:00:00Z\",\"data\":{"
+ "\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1023.1,\"air_tem"
+ "perature\":25.6,\"cloud_area_fraction\":40.6,\"relative_humidity\":65.0,"
+ "\"wind_from_direction\":327.2,\"wind_speed\":3.8}},\"next_12_hours\":{\""
+ "summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},\"next_1_ho"
+ "urs\":{\"summary\":{\"symbol_code\":\"lightrainshowers_day\"},\"details"
+ "\":{\"precipitation_amount\":0.1}},\"next_6_hours\":{\"summary\":{\"symbo"
+ "l_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.1}}}}"
+ ",{\"time\":\"2026-10-01T13:00:00Z\",\"data\":{\"instant\":{\"details\":{"
+ "\"air_pressure_at_sea_level\":1022.7,\"air_temperature\":24.7,\"cloud_ar"
+ "ea_fraction\":11.7,\"relative_humidity\":65.7,\"wind_from_direction\":33"
+ "6.0,\"wind_speed\":4.2}},\"next_12_hours\":{\"summary\":{\"symbol_code\""
+ ":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symb"
+ "ol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}},"
+ "\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"detai"
+ "ls\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-01T14:00:00Z"
+ "\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1022"
+ ".5,\"air_temperature\":24.3,\"cloud_area_fraction\":3.1,\"relative_humid"
+ "ity\":61.4,\"wind_from_direction\":324.0,\"wind_speed\":4.1}},\"next_12_"
+ "hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{}"
+ "},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"det"
+ "ails\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\""
+ "symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_amount\":"
+ "0.0}}}},{\"time\":\"2026-10-01T15:00:00Z\",\"data\":{\"instant\":{\"deta"
+ "ils\":{\"air_pressure_at_sea_level\":1022.4,\"air_temperature\":24.4,\"c"
+ "loud_area_fraction\":1.6,\"relative_humidity\":60.5,\"wind_from_directio"
+ "n\":336.5,\"wind_speed\":3.5}},\"next_12_hours\":{\"summary\":{\"symbol_"
+ "code\":\"clearsky_night\"},\"details\":{}},\"next_1_hours\":{\"summary\""
+ ":{\"symbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount"
+ "\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night"
+ "\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-01T"
+ "16:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_le"
+ "vel\":1022.5,\"air_temperature\":24.1,\"cloud_area_fraction\":0.0,\"rela"
+ "tive_humidity\":57.5,\"wind_from_direction\":7.2,\"wind_speed\":4.7}},\""
+ "next_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"deta"
+ "ils\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day"
+ "\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summa"
+ "ry\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_a"
+ "mount\":0.0}}}},{\"time\":\"2026-10-01T17:00:00Z\",\"data\":{\"instant\""
+ ":{\"details\":{\"air_pressure_at_sea_level\":1022.7,\"air_temperature\":"
+ "24.0,\"cloud_area_fraction\":0.0,\"relative_humidity\":57.7,\"wind_from_"
+ "direction\":30.6,\"wind_speed\":5.2}},\"next_12_hours\":{\"summary\":{\""
+ "symbol_code\":\"clearsky_night\"},\"details\":{}},\"next_1_hours\":{\"su"
+ "mmary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitatio"
+ "n_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clears"
+ "ky_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"20"
+ "26-10-01T18:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_"
+ "at_sea_level\":1023.2,\"air_temperature\":23.9,\"cloud_area_fraction\":0"
+ ".0,\"relative_humidity\":58.4,\"wind_from_direction\":46.5,\"wind_speed"
+ "\":5.1}},\"next_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night"
+ "\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"cle"
+ "arsky_night\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hour"
+ "s\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"pre"
+ "cipitation_amount\":0.0}}}},{\"time\":\"2026-10-01T19:00:00Z\",\"data\":"
+ "{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1023.7,\"air_te"
+ "mperature\":23.6,\"cloud_area_fraction\":0.0,\"relative_humidity\":59.6,"
+ "\"wind_from_direction\":56.9,\"wind_speed\":5.1}},\"next_12_hours\":{\"s"
+ "ummary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{}},\"next_1_h"
+ "ours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\""
+ "precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_cod"
+ "e\":\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{"
+ "\"time\":\"2026-10-01T20:00:00Z\",\"data\":{\"instant\":{\"details\":{\"a"
+ "ir_pressure_at_sea_level\":1024.1,\"air_temperature\":23.2,\"cloud_area_"
+ "fraction\":0.0,\"relative_humidity\":62.6,\"wind_from_direction\":65.3,"
+ "\"wind_speed\":4.8}},\"next_12_hours\":{\"summary\":{\"symbol_code\":\"cl"
+ "earsky_night\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbol_"
+ "code\":\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}},"
+ "\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"deta"
+ "ils\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-01T21:00:00Z"
+ "\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":102"
+ "4.3,\"air_temperature\":22.6,\"cloud_area_fraction\":0.0,\"relative_humi"
+ "dity\":65.8,\"wind_from_direction\":75.2,\"wind_speed\":4.6}},\"next_12_"
+ "hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},"
+ "\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"det"
+ "ails\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\""
+ "symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_amount\":"
+ "0.0}}}},{\"time\":\"2026-10-01T22:00:00Z\",\"data\":{\"instant\":{\"deta"
+ "ils\":{\"air_pressure_at_sea_level\":1024.4,\"air_temperature\":22.1,\"c"
+ "loud_area_fraction\":0.0,\"relative_humidity\":68.5,\"wind_from_directio"
+ "n\":80.6,\"wind_speed\":4.2}},\"next_12_hours\":{\"summary\":{\"symbol_c"
+ "ode\":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{"
+ "\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_amount\""
+ ":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\""
+ "},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-01T2"
+ "3:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_lev"
+ "el\":1024.3,\"air_temperature\":21.8,\"cloud_area_fraction\":0.0,\"relat"
+ "ive_humidity\":72.4,\"wind_from_direction\":82.0,\"wind_speed\":3.9}},\""
+ "next_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"detail"
+ "s\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night"
+ "\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summa"
+ "ry\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_a"
+ "mount\":0.0}}}},{\"time\":\"2026-10-02T00:00:00Z\",\"data\":{\"instant\""
+ ":{\"details\":{\"air_pressure_at_sea_level\":1024.3,\"air_temperature\":"
+ "21.5,\"cloud_area_fraction\":0.0,\"relative_humidity\":73.8,\"wind_from_"
+ "direction\":86.9,\"wind_speed\":4.0}},\"next_12_hours\":{\"summary\":{\""
+ "symbol_code\":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summ"
+ "ary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_"
+ "amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky"
+ "_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026"
+ "-10-02T01:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at"
+ "_sea_level\":1024.5,\"air_temperature\":21.1,\"cloud_area_fraction\":2.3"
+ ",\"relative_humidity\":74.6,\"wind_from_direction\":96.3,\"wind_speed\":"
+ "3.9}},\"next_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},"
+ "\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsk"
+ "y_night\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":"
+ "{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipi"
+ "tation_amount\":0.0}}}},{\"time\":\"2026-10-02T02:00:00Z\",\"data\":{\"i"
+ "nstant\":{\"details\":{\"air_pressure_at_sea_level\":1024.4,\"air_temper"
+ "ature\":20.8,\"cloud_area_fraction\":1.6,\"relative_humidity\":75.2,\"wi"
+ "nd_from_direction\":103.7,\"wind_speed\":3.6}},\"next_12_hours\":{\"summ"
+ "ary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},\"next_1_hours"
+ "\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"preci"
+ "pitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":"
+ "\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time"
+ "\":\"2026-10-02T03:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pr"
+ "essure_at_sea_level\":1024.5,\"air_temperature\":20.4,\"cloud_area_fract"
+ "ion\":3.1,\"relative_humidity\":77.3,\"wind_from_direction\":109.8,\"win"
+ "d_speed\":3.4}},\"next_12_hours\":{\"summary\":{\"symbol_code\":\"clears"
+ "ky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\""
+ ":\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}},\"next_"
+ "6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{"
+ "\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T04:00:00Z\",\"dat"
+ "a\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1024.6,\"ai"
+ "r_temperature\":20.1,\"cloud_area_fraction\":3.9,\"relative_humidity\":8"
+ "0.3,\"wind_from_direction\":116.8,\"wind_speed\":3.0}},\"next_12_hours\""
+ ":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},\"next_"
+ "1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":"
+ "{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_"
+ "code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}}}},{"
+ "\"time\":\"2026-10-02T05:00:00Z\",\"data\":{\"instant\":{\"details\":{\""
+ "air_pressure_at_sea_level\":1024.8,\"air_temperature\":19.8,\"cloud_area"
+ "_fraction\":5.5,\"relative_humidity\":82.7,\"wind_from_direction\":122.6"
+ ",\"wind_speed\":3.0}},\"next_12_hours\":{\"summary\":{\"symbol_code\":\""
+ "clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbol_"
+ "code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}},\"n"
+ "ext_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details"
+ "\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T06:00:00Z\","
+ "\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1025.3,"
+ "\"air_temperature\":20.3,\"cloud_area_fraction\":3.9,\"relative_humidity"
+ "\":79.6,\"wind_from_direction\":126.0,\"wind_speed\":2.9}},\"next_12_hou"
+ "rs\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},\"n"
+ "ext_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details"
+ "\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbo"
+ "l_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}}}}"
+ ",{\"time\":\"2026-10-02T07:00:00Z\",\"data\":{\"instant\":{\"details\":{"
+ "\"air_pressure_at_sea_level\":1025.9,\"air_temperature\":22.5,\"cloud_ar"
+ "ea_fraction\":6.2,\"relative_humidity\":63.4,\"wind_from_direction\":134"
+ ".1,\"wind_speed\":2.7}},\"next_12_hours\":{\"summary\":{\"symbol_code\":"
+ "\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"symbo"
+ "l_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}},"
+ "\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"detail"
+ "s\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T08:00:00Z\""
+ ",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1026."
+ "2,\"air_temperature\":24.1,\"cloud_area_fraction\":0.8,\"relative_humidi"
+ "ty\":56.1,\"wind_from_direction\":143.3,\"wind_speed\":2.1}},\"next_12_h"
+ "ours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}},"
+ "\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"detail"
+ "s\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"sym"
+ "bol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}}"
+ "}},{\"time\":\"2026-10-02T09:00:00Z\",\"data\":{\"instant\":{\"details\""
+ ":{\"air_pressure_at_sea_level\":1026.4,\"air_temperature\":25.2,\"cloud_"
+ "area_fraction\":4.7,\"relative_humidity\":52.5,\"wind_from_direction\":2"
+ "66.7,\"wind_speed\":1.9}},\"next_12_hours\":{\"summary\":{\"symbol_code"
+ "\":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"sym"
+ "bol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}}"
+ ",\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"deta"
+ "ils\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T10:00:00Z"
+ "\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":102"
+ "6.4,\"air_temperature\":25.9,\"cloud_area_fraction\":0.0,\"relative_humi"
+ "dity\":54.1,\"wind_from_direction\":300.2,\"wind_speed\":2.6}},\"next_12"
+ "_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":{}}"
+ ",\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"deta"
+ "ils\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"s"
+ "ymbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0"
+ "}}}},{\"time\":\"2026-10-02T11:00:00Z\",\"data\":{\"instant\":{\"details"
+ "\":{\"air_pressure_at_sea_level\":1026.4,\"air_temperature\":26.0,\"clou"
+ "d_area_fraction\":3.9,\"relative_humidity\":57.3,\"wind_from_direction\""
+ ":315.1,\"wind_speed\":3.5}},\"next_12_hours\":{\"summary\":{\"symbol_cod"
+ "e\":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"s"
+ "ymbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0"
+ "}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"de"
+ "tails\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T12:00:0"
+ "0Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1"
+ "026.1,\"air_temperature\":25.4,\"cloud_area_fraction\":17.2,\"relative_h"
+ "umidity\":59.0,\"wind_from_direction\":326.7,\"wind_speed\":3.7}},\"next"
+ "_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"details\":"
+ "{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"fair_day\"},\"detai"
+ "ls\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"sy"
+ "mbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0}"
+ "}}},{\"time\":\"2026-10-02T13:00:00Z\",\"data\":{\"instant\":{\"details"
+ "\":{\"air_pressure_at_sea_level\":1025.6,\"air_temperature\":25.2,\"cloud"
+ "_area_fraction\":10.9,\"relative_humidity\":57.9,\"wind_from_direction\""
+ ":324.1,\"wind_speed\":4.0}},\"next_12_hours\":{\"summary\":{\"symbol_cod"
+ "e\":\"clearsky_day\"},\"details\":{}},\"next_1_hours\":{\"summary\":{\"s"
+ "ymbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amount\":0.0"
+ "}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\"de"
+ "tails\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-02T14:00:0"
+ "0Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1"
+ "025.4,\"air_temperature\":25.1,\"cloud_area_fraction\":9.4,\"relative_hu"
+ "midity\":59.7,\"wind_from_direction\":324.8,\"wind_speed\":3.7}},\"next_"
+ "12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\""
+ ":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_day\"},\""
+ "details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"summary\":"
+ "{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitation_amount"
+ "\":0.0}}}},{\"time\":\"2026-10-02T15:00:00Z\",\"data\":{\"instant\":{\"d"
+ "etails\":{\"air_pressure_at_sea_level\":1025.1,\"air_temperature\":24.7,"
+ "\"cloud_area_fraction\":7.0,\"relative_humidity\":61.7,\"wind_from_direc"
+ "tion\":343.4,\"wind_speed\":3.8}},\"next_12_hours\":{\"summary\":{\"symb"
+ "ol_code\":\"clearsky_night\"},\"details\":{}},\"next_1_hours\":{\"summar"
+ "y\":{\"symbol_code\":\"clearsky_day\"},\"details\":{\"precipitation_amou"
+ "nt\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_nig"
+ "ht\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-"
+ "02T16:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea"
+ "_level\":1025.0,\"air_temperature\":24.3,\"cloud_area_fraction\":3.9,\"r"
+ "elative_humidity\":60.5,\"wind_from_direction\":9.3,\"wind_speed\":4.1}}"
+ ",\"next_12_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"d"
+ "etails\":{}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_d"
+ "ay\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{\"su"
+ "mmary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipitatio"
+ "n_amount\":0.0}}}},{\"time\":\"2026-10-03T13:00:00Z\",\"data\":{\"instan"
+ "t\":{\"details\":{\"air_pressure_at_sea_level\":1025.6,\"air_temperature"
+ "\":25.0,\"cloud_area_fraction\":27.3,\"relative_humidity\":68.4,\"wind_f"
+ "rom_direction\":267.0,\"wind_speed\":3.5}},\"next_1_hours\":{\"summary\""
+ ":{\"symbol_code\":\"lightrainshowers_day\"},\"details\":{\"precipitation"
+ "_amount\":0.2}},\"next_6_hours\":{\"summary\":{\"symbol_code\":\"fair_da"
+ "y\"},\"details\":{\"precipitation_amount\":0.4}}}},{\"time\":\"2026-10-0"
+ "3T14:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_"
+ "level\":1025.5,\"air_temperature\":24.8,\"cloud_area_fraction\":20.3,\"r"
+ "elative_humidity\":66.7,\"wind_from_direction\":276.5,\"wind_speed\":2.7"
+ "}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"lightrainshowers_day"
+ "\"},\"details\":{\"precipitation_amount\":0.1}},\"next_6_hours\":{\"summ"
+ "ary\":{\"symbol_code\":\"fair_night\"},\"details\":{\"precipitation_amou"
+ "nt\":0.2}}}},{\"time\":\"2026-10-03T15:00:00Z\",\"data\":{\"instant\":{"
+ "\"details\":{\"air_pressure_at_sea_level\":1025.3,\"air_temperature\":24."
+ "2,\"cloud_area_fraction\":27.3,\"relative_humidity\":67.4,\"wind_from_di"
+ "rection\":287.6,\"wind_speed\":2.4}},\"next_1_hours\":{\"summary\":{\"sy"
+ "mbol_code\":\"fair_day\"},\"details\":{\"precipitation_amount\":0.0}},\""
+ "next_6_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"detai"
+ "ls\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-03T16:00:00Z"
+ "\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":1025"
+ ".1,\"air_temperature\":23.6,\"cloud_area_fraction\":18.7,\"relative_humi"
+ "dity\":69.2,\"wind_from_direction\":305.9,\"wind_speed\":2.1}},\"next_1_"
+ "hours\":{\"summary\":{\"symbol_code\":\"fair_day\"},\"details\":{\"preci"
+ "pitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":"
+ "\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time"
+ "\":\"2026-10-03T17:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pr"
+ "essure_at_sea_level\":1025.1,\"air_temperature\":22.8,\"cloud_area_fract"
+ "ion\":11.7,\"relative_humidity\":70.4,\"wind_from_direction\":7.2,\"wind"
+ "_speed\":1.9}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky"
+ "_night\"},\"details\":{\"precipitation_amount\":0.0}},\"next_6_hours\":{"
+ "\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"precipit"
+ "ation_amount\":0.0}}}},{\"time\":\"2026-10-03T18:00:00Z\",\"data\":{\"in"
+ "stant\":{\"details\":{\"air_pressure_at_sea_level\":1025.4,\"air_tempera"
+ "ture\":22.7,\"cloud_area_fraction\":9.4,\"relative_humidity\":70.3,\"win"
+ "d_from_direction\":42.9,\"wind_speed\":1.5}},\"next_12_hours\":{\"summar"
+ "y\":{\"symbol_code\":\"clearsky_night\"},\"details\":{}},\"next_1_hours"
+ "\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{\"preci"
+ "pitation_amount\":0.0}},\"next_6_hours\":{\"summary\":{\"symbol_code\":"
+ "\"clearsky_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time"
+ "\":\"2026-10-03T19:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pr"
+ "essure_at_sea_level\":1025.7,\"air_temperature\":22.7,\"cloud_area_fract"
+ "ion\":9.4,\"relative_humidity\":68.5,\"wind_from_direction\":79.5,\"wind"
+ "_speed\":1.4}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky"
+ "_night\"},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026"
+ "-10-03T20:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at"
+ "_sea_level\":1025.9,\"air_temperature\":22.7,\"cloud_area_fraction\":4.7"
+ ",\"relative_humidity\":66.6,\"wind_from_direction\":143.6,\"wind_speed\""
+ ":1.3}},\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\""
+ "},\"details\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-03T2"
+ "1:00:00Z\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_lev"
+ "el\":1025.9,\"air_temperature\":22.5,\"cloud_area_fraction\":0.8,\"relat"
+ "ive_humidity\":66.7,\"wind_from_direction\":168.8,\"wind_speed\":1.2}},"
+ "\"next_1_hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"deta"
+ "ils\":{\"precipitation_amount\":0.0}}}},{\"time\":\"2026-10-03T22:00:00Z"
+ "\",\"data\":{\"instant\":{\"details\":{\"air_pressure_at_sea_level\":102"
+ "5.7,\"air_temperature\":22.2,\"cloud_area_fraction\":0.0,\"relative_humi"
+ "dity\":68.1,\"wind_from_direction\":171.0,\"wind_speed\":1.2}},\"next_1_"
+ "hours\":{\"summary\":{\"symbol_code\":\"clearsky_night\"},\"details\":{"
+ "\"precipitation_amount\":0.0}}}}]}}";
+
+static const char METEOALARM[] =
+ "{\"warnings\":[{\"alert\":{\"identifier\":\"2.49.0.0.380.3.IT.2609261008"
+ "57.001\",\"incidents\":\"Update\",\"info\":[{\"area\":[{\"areaDesc\":\"C"
+ "ampania\",\"geocode\":[{\"value\":\"IT016\",\"valueName\":\"EMMA_ID\"}]}"
+ "],\"audience\":\"Private\",\"category\":[\"Met\"],\"certainty\":\"Likely"
+ "\",\"description\":\"No Special Awareness Required\\n (DISCLAIMER: \\\"I"
+ "nformation provided on METEOALARM for Italy regard only the intensity an"
+ "d recurrence of the phenomena, further details can be found at www.meteo"
+ "am.it. METEOALARM information do not provide the assessment of impact on"
+ " the territory and they do not represent the Official Alerts messages th"
+ "at are issued by the National Civil Protection Service https://www.prote"
+ "zionecivile.gov.it\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\""
+ "event\":\"Green Wind Warning\",\"expires\":\"2026-09-28T23:59:00+02:00\""
+ ",\"headline\":\"Green Wind Warning for Italy - Campania\",\"instruction"
+ "\":\"The weather is not expected to cause significant impacts but there m"
+ "ay be some minor, localized issues\",\"language\":\"en-GB\",\"onset\":\""
+ "2026-09-26T10:08:00+02:00\",\"parameter\":[{\"value\":\"1; green; Minor"
+ "\",\"valueName\":\"awareness_level\"},{\"value\":\"1; Wind\",\"valueName"
+ "\":\"awareness_type\"}],\"responseType\":[\"None\"],\"senderName\":\"Ital"
+ "ian Air Force National Meteorological Service\",\"severity\":\"Minor\","
+ "\"urgency\":\"Future\",\"web\":\"https://meteoalarm.org/en/live/region/IT"
+ "?s=campania\"},{\"area\":[{\"areaDesc\":\"Campania\",\"geocode\":[{\"val"
+ "ue\":\"IT016\",\"valueName\":\"EMMA_ID\"}]}],\"audience\":\"Privato\",\""
+ "category\":[\"Met\"],\"certainty\":\"Likely\",\"description\":\"Nessun A"
+ "vviso\\n (DISCLAIMER: \\\"Le informazioni fornite su METEOALARM per l'It"
+ "alia riguardano esclusivamente l'intensità e la ricorrenza dei fenomeni,"
+ " maggiori dettagli sono disponibili su www.meteoam.it. Le informazioni M"
+ "ETEOALARM non forniscono la valutazione di impatto sul territorio e non "
+ "rappresentano i messaggi di Allerta Ufficiali che vengono emessi dal Ser"
+ "vizio Nazionale di Protezione Civile https://www.protezionecivile.gov.it"
+ "\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\"event\":\"Verde Ve"
+ "nto Allerta\",\"expires\":\"2026-09-28T23:59:00+02:00\",\"headline\":\"A"
+ "llerta Vento Verde per l'Italia - Campania\",\"instruction\":\"Non ci si"
+ " aspetta che il tempo possa causare impatti significativi, ma potrebbero"
+ " verificarsi alcuni locali, minori problemi.\",\"language\":\"it-IT\",\""
+ "onset\":\"2026-09-26T10:08:00+02:00\",\"parameter\":[{\"value\":\"1; gre"
+ "en; Minor\",\"valueName\":\"awareness_level\"},{\"value\":\"1; Wind\",\""
+ "valueName\":\"awareness_type\"}],\"responseType\":[\"None\"],\"senderNam"
+ "e\":\"Servizio Meteorologico dell'Aeronautica Militare\",\"severity\":\""
+ "Minor\",\"urgency\":\"Future\",\"web\":\"https://meteoalarm.org/it/live/"
+ "region/IT?s=campania\"}],\"msgType\":\"Update\",\"references\":\"aerocnm"
+ "[email protected],2.49.0.0.380.3.IT.260925102045.029,202"
+ "6-09-25T10:20:46+02:00\",\"scope\":\"Public\",\"sender\":\"aerocnmca.1sv"
+ "[email protected]\",\"sent\":\"2026-09-26T10:08:57+02:00\",\"s"
+ "tatus\":\"Actual\"},\"uuid\":\"e4d58b0f-9b7c-4864-8321-5cd50035dfc2\"},{"
+ "\"alert\":{\"identifier\":\"2.49.0.0.380.3.IT.260926100857.005\",\"incid"
+ "ents\":\"Update\",\"info\":[{\"area\":[{\"areaDesc\":\"Sicilia\",\"geoco"
+ "de\":[{\"value\":\"IT018\",\"valueName\":\"EMMA_ID\"}]}],\"audience\":\""
+ "Private\",\"category\":[\"Met\"],\"certainty\":\"Likely\",\"description"
+ "\":\"No Special Awareness Required\\n (DISCLAIMER: \\\"Information provid"
+ "ed on METEOALARM for Italy regard only the intensity and recurrence of t"
+ "he phenomena, further details can be found at www.meteoam.it. METEOALARM"
+ " information do not provide the assessment of impact on the territory an"
+ "d they do not represent the Official Alerts messages that are issued by "
+ "the National Civil Protection Service https://www.protezionecivile.gov.i"
+ "t\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\"event\":\"Green T"
+ "hunderstorm Warning\",\"expires\":\"2026-09-28T23:59:00+02:00\",\"headli"
+ "ne\":\"Green Thunderstorm Warning for Italy - Sicilia\",\"instruction\":"
+ "\"The weather is not expected to cause significant impacts but there may"
+ " be some minor, localized issues\",\"language\":\"en-GB\",\"onset\":\"20"
+ "26-09-26T10:08:00+02:00\",\"parameter\":[{\"value\":\"1; green; Minor\","
+ "\"valueName\":\"awareness_level\"},{\"value\":\"3; Thunderstorm\",\"valu"
+ "eName\":\"awareness_type\"}],\"responseType\":[\"None\"],\"senderName\":"
+ "\"Italian Air Force National Meteorological Service\",\"severity\":\"Min"
+ "or\",\"urgency\":\"Future\",\"web\":\"https://meteoalarm.org/en/live/reg"
+ "ion/IT?s=sicilia\"},{\"area\":[{\"areaDesc\":\"Sicilia\",\"geocode\":[{"
+ "\"value\":\"IT018\",\"valueName\":\"EMMA_ID\"}]}],\"audience\":\"Privato"
+ "\",\"category\":[\"Met\"],\"certainty\":\"Likely\",\"description\":\"Ness"
+ "un Avviso\\n (DISCLAIMER: \\\"Le informazioni fornite su METEOALARM per "
+ "l'Italia riguardano esclusivamente l'intensità e la ricorrenza dei fenom"
+ "eni, maggiori dettagli sono disponibili su www.meteoam.it. Le informazio"
+ "ni METEOALARM non forniscono la valutazione di impatto sul territorio e "
+ "non rappresentano i messaggi di Allerta Ufficiali che vengono emessi dal"
+ " Servizio Nazionale di Protezione Civile https://www.protezionecivile.go"
+ "v.it\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\"event\":\"Verd"
+ "e Temporali Allerta\",\"expires\":\"2026-09-28T23:59:00+02:00\",\"headli"
+ "ne\":\"Allerta Temporali Verde per l'Italia - Sicilia\",\"instruction\":"
+ "\"Non ci si aspetta che il tempo possa causare impatti significativi, ma"
+ " potrebbero verificarsi alcuni locali, minori problemi.\",\"language\":"
+ "\"it-IT\",\"onset\":\"2026-09-26T10:08:00+02:00\",\"parameter\":[{\"value"
+ "\":\"1; green; Minor\",\"valueName\":\"awareness_level\"},{\"value\":\"3"
+ "; Thunderstorm\",\"valueName\":\"awareness_type\"}],\"responseType\":[\""
+ "None\"],\"senderName\":\"Servizio Meteorologico dell'Aeronautica Militar"
+ "e\",\"severity\":\"Minor\",\"urgency\":\"Future\",\"web\":\"https://mete"
+ "oalarm.org/it/live/region/IT?s=sicilia\"}],\"msgType\":\"Update\",\"refe"
+ "rences\":\"[email protected],2.49.0.0.380.3.IT.26"
+ "0925102045.033,2026-09-25T10:20:46+02:00\",\"scope\":\"Public\",\"sender"
+ "\":\"[email protected]\",\"sent\":\"2026-09-26T10"
+ ":08:57+02:00\",\"status\":\"Actual\"},\"uuid\":\"4930e664-424b-4a89-bd27"
+ "-3caf7df9de11\"},{\"alert\":{\"identifier\":\"2.49.0.0.380.3.IT.26093010"
+ "4144.002\",\"incidents\":\"Update\",\"info\":[{\"area\":[{\"areaDesc\":"
+ "\"Piemonte\",\"geocode\":[{\"value\":\"IT005\",\"valueName\":\"EMMA_ID\"}"
+ "]}],\"audience\":\"Private\",\"category\":[\"Met\"],\"certainty\":\"Like"
+ "ly\",\"description\":\"No Special Awareness Required\\n (DISCLAIMER: \\"
+ "\"Information provided on METEOALARM for Italy regard only the intensity "
+ "and recurrence of the phenomena, further details can be found at www.met"
+ "eoam.it. METEOALARM information do not provide the assessment of impact "
+ "on the territory and they do not represent the Official Alerts messages "
+ "that are issued by the National Civil Protection Service https://www.pro"
+ "tezionecivile.gov.it\\\")\",\"effective\":\"2026-09-30T10:41:00+02:00\","
+ "\"event\":\"Green Thunderstorm Warning\",\"expires\":\"2026-10-02T23:59:"
+ "00+02:00\",\"headline\":\"Green Thunderstorm Warning for Italy - Piemont"
+ "e\",\"instruction\":\"The weather is not expected to cause significant i"
+ "mpacts but there may be some minor, localized issues\",\"language\":\"en"
+ "-GB\",\"onset\":\"2026-09-30T10:41:00+02:00\",\"parameter\":[{\"value\":"
+ "\"3; orange; Severe\",\"valueName\":\"awareness_level\"},{\"value\":\"3;"
+ " Thunderstorm\",\"valueName\":\"awareness_type\"}],\"responseType\":[\"N"
+ "one\"],\"senderName\":\"Italian Air Force National Meteorological Servic"
+ "e\",\"severity\":\"Minor\",\"urgency\":\"Future\",\"web\":\"https://mete"
+ "oalarm.org/en/live/region/IT?s=piemonte\"},{\"area\":[{\"areaDesc\":\"Pi"
+ "emonte\",\"geocode\":[{\"value\":\"IT005\",\"valueName\":\"EMMA_ID\"}]}]"
+ ",\"audience\":\"Privato\",\"category\":[\"Met\"],\"certainty\":\"Likely"
+ "\",\"description\":\"Nessun Avviso\\n (DISCLAIMER: \\\"Le informazioni fo"
+ "rnite su METEOALARM per l'Italia riguardano esclusivamente l'intensità e"
+ " la ricorrenza dei fenomeni, maggiori dettagli sono disponibili su www.m"
+ "eteoam.it. Le informazioni METEOALARM non forniscono la valutazione di i"
+ "mpatto sul territorio e non rappresentano i messaggi di Allerta Ufficial"
+ "i che vengono emessi dal Servizio Nazionale di Protezione Civile https:/"
+ "/www.protezionecivile.gov.it\\\")\",\"effective\":\"2026-09-30T10:41:00+"
+ "02:00\",\"event\":\"Verde Temporali Allerta\",\"expires\":\"2026-10-02T2"
+ "3:59:00+02:00\",\"headline\":\"Allerta Temporali Verde per l'Italia - Pi"
+ "emonte\",\"instruction\":\"Non ci si aspetta che il tempo possa causare "
+ "impatti significativi, ma potrebbero verificarsi alcuni locali, minori p"
+ "roblemi.\",\"language\":\"it-IT\",\"onset\":\"2026-09-30T10:41:00+02:00"
+ "\",\"parameter\":[{\"value\":\"3; orange; Severe\",\"valueName\":\"awaren"
+ "ess_level\"},{\"value\":\"3; Thunderstorm\",\"valueName\":\"awareness_ty"
+ "pe\"}],\"responseType\":[\"None\"],\"senderName\":\"Servizio Meteorologi"
+ "co dell'Aeronautica Militare\",\"severity\":\"Minor\",\"urgency\":\"Futu"
+ "re\",\"web\":\"https://meteoalarm.org/it/live/region/IT?s=piemonte\"}],"
+ "\"msgType\":\"Update\",\"references\":\"[email protected]"
+ "fesa.it,2.49.0.0.380.3.IT.260929102223.003,2026-09-29T10:22:23+02:00\","
+ "\"scope\":\"Public\",\"sender\":\"[email protected]"
+ "t\",\"sent\":\"2026-09-30T10:41:44+02:00\",\"status\":\"Actual\"},\"uuid"
+ "\":\"089288e8-1557-4372-ae0b-f714d76eca74\"},{\"alert\":{\"identifier\":"
+ "\"2.49.0.0.380.3.IT.260926100857.005\",\"incidents\":\"Update\",\"info\""
+ ":[{\"area\":[{\"areaDesc\":\"Sicilia\",\"geocode\":[{\"value\":\"IT018\""
+ ",\"valueName\":\"EMMA_ID\"}]}],\"audience\":\"Private\",\"category\":[\""
+ "Met\"],\"certainty\":\"Likely\",\"description\":\"No Special Awareness R"
+ "equired\\n (DISCLAIMER: \\\"Information provided on METEOALARM for Italy"
+ " regard only the intensity and recurrence of the phenomena, further deta"
+ "ils can be found at www.meteoam.it. METEOALARM information do not provid"
+ "e the assessment of impact on the territory and they do not represent th"
+ "e Official Alerts messages that are issued by the National Civil Protect"
+ "ion Service https://www.protezionecivile.gov.it\\\")\",\"effective\":\"2"
+ "026-09-26T10:08:00+02:00\",\"event\":\"Yellow Thunderstorm Warning\",\"e"
+ "xpires\":\"2026-10-02T23:59:00+02:00\",\"headline\":\"Green Thunderstorm"
+ " Warning for Italy - Sicilia\",\"instruction\":\"The weather is not expe"
+ "cted to cause significant impacts but there may be some minor, localized"
+ " issues\",\"language\":\"en-GB\",\"onset\":\"2026-09-26T10:08:00+02:00\""
+ ",\"parameter\":[{\"value\":\"2; yellow; Moderate\",\"valueName\":\"aware"
+ "ness_level\"},{\"value\":\"3; Thunderstorm\",\"valueName\":\"awareness_t"
+ "ype\"}],\"responseType\":[\"None\"],\"senderName\":\"Italian Air Force N"
+ "ational Meteorological Service\",\"severity\":\"Minor\",\"urgency\":\"Fu"
+ "ture\",\"web\":\"https://meteoalarm.org/en/live/region/IT?s=sicilia\"},{"
+ "\"area\":[{\"areaDesc\":\"Sicilia\",\"geocode\":[{\"value\":\"IT018\",\""
+ "valueName\":\"EMMA_ID\"}]}],\"audience\":\"Privato\",\"category\":[\"Met"
+ "\"],\"certainty\":\"Likely\",\"description\":\"Nessun Avviso\\n (DISCLAI"
+ "MER: \\\"Le informazioni fornite su METEOALARM per l'Italia riguardano e"
+ "sclusivamente l'intensità e la ricorrenza dei fenomeni, maggiori dettagl"
+ "i sono disponibili su www.meteoam.it. Le informazioni METEOALARM non for"
+ "niscono la valutazione di impatto sul territorio e non rappresentano i m"
+ "essaggi di Allerta Ufficiali che vengono emessi dal Servizio Nazionale d"
+ "i Protezione Civile https://www.protezionecivile.gov.it\\\")\",\"effecti"
+ "ve\":\"2026-09-26T10:08:00+02:00\",\"event\":\"Gialla Temporali Allerta"
+ "\",\"expires\":\"2026-10-02T23:59:00+02:00\",\"headline\":\"Allerta Tempo"
+ "rali Verde per l'Italia - Sicilia\",\"instruction\":\"Non ci si aspetta "
+ "che il tempo possa causare impatti significativi, ma potrebbero verifica"
+ "rsi alcuni locali, minori problemi.\",\"language\":\"it-IT\",\"onset\":"
+ "\"2026-09-26T10:08:00+02:00\",\"parameter\":[{\"value\":\"2; yellow; Mode"
+ "rate\",\"valueName\":\"awareness_level\"},{\"value\":\"3; Thunderstorm\""
+ ",\"valueName\":\"awareness_type\"}],\"responseType\":[\"None\"],\"sender"
+ "Name\":\"Servizio Meteorologico dell'Aeronautica Militare\",\"severity\""
+ ":\"Minor\",\"urgency\":\"Future\",\"web\":\"https://meteoalarm.org/it/li"
+ "ve/region/IT?s=sicilia\"}],\"msgType\":\"Update\",\"references\":\"aeroc"
+ "[email protected],2.49.0.0.380.3.IT.260925102045.033,2"
+ "026-09-25T10:20:46+02:00\",\"scope\":\"Public\",\"sender\":\"aerocnmca.1"
+ "[email protected]\",\"sent\":\"2026-09-26T10:08:57+02:00\","
+ "\"status\":\"Actual\"},\"uuid\":\"4930e664-424b-4a89-bd27-3caf7df9de11\"}"
+ ",{\"alert\":{\"identifier\":\"2.49.0.0.380.3.IT.260926100857.005\",\"inc"
+ "idents\":\"Update\",\"info\":[{\"area\":[{\"areaDesc\":\"Sicilia\",\"geo"
+ "code\":[{\"value\":\"IT018\",\"valueName\":\"EMMA_ID\"}]}],\"audience\":"
+ "\"Private\",\"category\":[\"Met\"],\"certainty\":\"Likely\",\"descriptio"
+ "n\":\"No Special Awareness Required\\n (DISCLAIMER: \\\"Information prov"
+ "ided on METEOALARM for Italy regard only the intensity and recurrence of"
+ " the phenomena, further details can be found at www.meteoam.it. METEOALA"
+ "RM information do not provide the assessment of impact on the territory "
+ "and they do not represent the Official Alerts messages that are issued b"
+ "y the National Civil Protection Service https://www.protezionecivile.gov"
+ ".it\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\"event\":\"Yello"
+ "w Thunderstorm Warning\",\"expires\":\"2026-10-02T23:59:00+02:00\",\"hea"
+ "dline\":\"Green Thunderstorm Warning for Italy - Sicilia\",\"instruction"
+ "\":\"The weather is not expected to cause significant impacts but there "
+ "may be some minor, localized issues\",\"language\":\"en-GB\",\"onset\":"
+ "\"2026-09-26T10:08:00+02:00\",\"parameter\":[{\"value\":\"2; yellow; Mode"
+ "rate\",\"valueName\":\"awareness_level\"},{\"value\":\"3; Thunderstorm\""
+ ",\"valueName\":\"awareness_type\"}],\"responseType\":[\"None\"],\"sender"
+ "Name\":\"Italian Air Force National Meteorological Service\",\"severity"
+ "\":\"Minor\",\"urgency\":\"Future\",\"web\":\"https://meteoalarm.org/en/l"
+ "ive/region/IT?s=sicilia\"},{\"area\":[{\"areaDesc\":\"Sicilia\",\"geocod"
+ "e\":[{\"value\":\"IT018\",\"valueName\":\"EMMA_ID\"}]}],\"audience\":\"P"
+ "rivato\",\"category\":[\"Met\"],\"certainty\":\"Likely\",\"description\""
+ ":\"Nessun Avviso\\n (DISCLAIMER: \\\"Le informazioni fornite su METEOALA"
+ "RM per l'Italia riguardano esclusivamente l'intensità e la ricorrenza de"
+ "i fenomeni, maggiori dettagli sono disponibili su www.meteoam.it. Le inf"
+ "ormazioni METEOALARM non forniscono la valutazione di impatto sul territ"
+ "orio e non rappresentano i messaggi di Allerta Ufficiali che vengono eme"
+ "ssi dal Servizio Nazionale di Protezione Civile https://www.protezioneci"
+ "vile.gov.it\\\")\",\"effective\":\"2026-09-26T10:08:00+02:00\",\"event\""
+ ":\"Gialla Temporali Allerta\",\"expires\":\"2026-10-02T23:59:00+02:00\","
+ "\"headline\":\"Allerta Temporali Verde per l'Italia - Sicilia\",\"instru"
+ "ction\":\"Non ci si aspetta che il tempo possa causare impatti significa"
+ "tivi, ma potrebbero verificarsi alcuni locali, minori problemi.\",\"lang"
+ "uage\":\"it-IT\",\"onset\":\"2026-09-26T10:08:00+02:00\",\"parameter\":["
+ "{\"value\":\"2; yellow; Moderate\",\"valueName\":\"awareness_level\"},{"
+ "\"value\":\"3; Thunderstorm\",\"valueName\":\"awareness_type\"}],\"respon"
+ "seType\":[\"None\"],\"senderName\":\"Servizio Meteorologico dell'Aeronau"
+ "tica Militare\",\"severity\":\"Minor\",\"urgency\":\"Future\",\"web\":\""
+ "https://meteoalarm.org/it/live/region/IT?s=sicilia\"}],\"msgType\":\"Upd"
+ "ate\",\"references\":\"[email protected],2.49.0.0"
+ ".380.3.IT.260925102045.033,2026-09-25T10:20:46+02:00\",\"scope\":\"Publi"
+ "c\",\"sender\":\"[email protected]\",\"sent\":\"2"
+ "026-09-26T10:08:57+02:00\",\"status\":\"Actual\"},\"uuid\":\"4930e664-42"
+ "4b-4a89-bd27-3caf7df9de11\"}]}";
+
+static const char DPC_DAY[] =
+ "{\"type\": \"FeatureCollection\", \"features\": [{\"type\": \"Feature\","
+ " \"properties\": {\"Rappresentata nella mappa\": \"Assenza di fenomeni s"
+ "ignificativi prevedibili / NESSUNA ALLERTA\", \"Per rischio idraulico\":"
+ " \"Assenza di fenomeni significativi prevedibili / NESSUNA ALLERTA\", \""
+ "Per rischio temporali\": \"Assenza di fenomeni significativi prevedibili"
+ " / NESSUNA ALLERTA\", \"Per rischio idrogeologico\": \"Assenza di fenome"
+ "ni significativi prevedibili / NESSUNA ALLERTA\", \"Nome zona\": \"Nord-"
+ "Occidentale e isole Egadi e Ustica\", \"Comuni\": [\"Erice\", \"Trapani"
+ "\", \"Marsala\"]}, \"geometry\": null}, {\"type\": \"Feature\", \"propert"
+ "ies\": {\"Rappresentata nella mappa\": \"Assenza di fenomeni significati"
+ "vi prevedibili / NESSUNA ALLERTA\", \"Per rischio idraulico\": \"Assenza"
+ " di fenomeni significativi prevedibili / NESSUNA ALLERTA\", \"Per rischi"
+ "o temporali\": \"Ordinaria criticità / ALLERTA GIALLA\", \"Per rischio i"
+ "drogeologico\": \"Assenza di fenomeni significativi prevedibili / NESSUN"
+ "A ALLERTA\", \"Nome zona\": \"Zona di prova\", \"Comuni\": [\"Trapani\","
+ " \"Paceco\"]}, \"geometry\": {\"type\": \"MultiPolygon\", \"coordinates"
+ "\": [[[[12.3, 37.8], [12.6, 37.8], [12.6, 38.0], [12.3, 38.0], [12.3, 3"
+ "7.8]]], [[[1, 1], [2, 1], [2, 2], [1, 1]]]]}}, {\"type\": \"Feature\", "
+ "\"properties"
+ "\": {\"Rappresentata nella mappa\": \"Assenza di fenomeni significativi "
+ "prevedibili / NESSUNA ALLERTA\", \"Per rischio idraulico\": \"Elevata cr"
+ "iticità / ALLERTA ROSSA\", \"Per rischio temporali\": \"Assenza di fenom"
+ "eni significativi prevedibili / NESSUNA ALLERTA\", \"Per rischio idrogeo"
+ "logico\": \"Assenza di fenomeni significativi prevedibili / NESSUNA ALLE"
+ "RTA\", \"Nome zona\": \"Altrove\", \"Comuni\": [\"Torino\"]}, \"geometry"
+ "\": {\"type\": \"Polygon\", \"coordinates\": [[[7.5, 44.9], [7.9, 44.9], "
+ "[7.9, 45.2], [7.5, 45.2]], [[7.6, 45.0], [7.62, 45.0], [7.62, 45.02], "
+ "[7.6, 45.02], [7.6, 45.0]]]}}]}";
+
+static void forecast(void)
+{
+ static struct wx_forecast f;
+ char err[256];
+ int r =
+ wx_om_parse(OM_FORECAST, sizeof OM_FORECAST - 1, &f, err, sizeof err);
+ CHECK(r == 0, "Open-Meteo: %s", err);
+ CHECK(f.grid_lat == 38.0 && f.grid_lon == 12.5625 && f.grid_elev == 6.0,
+ "the cell: %f %f %f", f.grid_lat, f.grid_lon, f.grid_elev);
+ CHECK(strcmp(f.tz, "Europe/Rome") == 0, "zone %s", f.tz);
+ CHECK(f.has_now && f.now.temp == 26.3 && f.now.code == 0 &&
+ f.now.wind == 13.4 && f.now.wind_dir == 324 &&
+ strcmp(f.now.time, "2026-10-01T13:45") == 0,
+ "now: %f %d %s", f.now.temp, f.now.code, f.now.time);
+ CHECK(f.n_day == 3 && f.day[0].tmax == 26.6 &&
+ strcmp(f.day[0].date, "2026-10-01") == 0 &&
+ strcmp(f.day[0].sunrise, "07:05") == 0,
+ "days: %d, %f, %s", f.n_day, f.day[0].tmax, f.day[0].sunrise);
+ CHECK(f.n_hour == WX_HOURS, "hours: %d", f.n_hour);
+
+ r = wx_met_parse(MET_NORWAY, sizeof MET_NORWAY - 1, "Europe/Rome", &f, err,
+ sizeof err);
+ CHECK(r == 0, "MET Norway: %s", err);
+ /* 11:00 UTC is 13:00 in Rome, summer time */
+ CHECK(strcmp(f.now.time, "2026-10-01T13:00") == 0 &&
+ strcmp(f.tz_abbr, "CEST") == 0,
+ "MET Norway now: %s %s", f.now.time, f.tz_abbr);
+ CHECK(f.n_day >= 2 && strcmp(f.day[0].date, "2026-10-01") == 0 &&
+ f.day[0].tmin <= f.day[0].tmax && f.day[0].symbol[0],
+ "MET Norway days: %d %s", f.n_day, f.day[0].date);
+ CHECK(f.n_hour > 20 && f.now.symbol[0], "MET Norway hours: %d", f.n_hour);
+ CHECK(f.now.wind > 12 && f.now.wind < 14, "m/s into km/h: %f", f.now.wind);
+}
+
+static void sea(void)
+{
+ struct wx_sea s[3] = {{.lat = 39.5, .lon = 12.0},
+ {.lat = 40.5, .lon = 11.0},
+ {.lat = 38.02, .lon = 12.53}};
+ char err[256];
+ int r = wx_om_marine_parse(OM_MARINE, sizeof OM_MARINE - 1, s, 3, err,
+ sizeof err);
+ CHECK(r == 0, "the sea: %s", err);
+ CHECK(s[0].ok && s[1].ok && s[2].ok && s[0].wave == 0.10 &&
+ s[1].wave == 0.14 && s[2].wave == 0.08 && s[0].sst == 26.7,
+ "the waves: %f %f %f", s[0].wave, s[1].wave, s[2].wave);
+ CHECK(s[0].n_day == 2 && s[0].day[0].wave_max > 0, "the sea's days: %d",
+ s[0].n_day);
+ CHECK(fabs(s[2].cell_lat - 38.041664) < 1e-6, "the coast's cell: %f",
+ s[2].cell_lat);
+}
+
+static void station(void)
+{
+ struct wx_obs o;
+ char err[256];
+ int r = wx_metar_parse(METAR_BBOX, sizeof METAR_BBOX - 1, 38.0176, 12.53617,
+ 40, &o, err, sizeof err);
+ CHECK(r == 1 && strcmp(o.icao, "LICT") == 0 && o.temp == 26 && o.km > 10 &&
+ o.km < 15 && strstr(o.clouds, "clouds at"),
+ "the station: %d %s %f %f '%s'", r, o.icao, o.temp, o.km, o.clouds);
+ r = wx_metar_parse(METAR_BBOX, sizeof METAR_BBOX - 1, 38.0176, 12.53617, 5,
+ &o, err, sizeof err);
+ CHECK(r == 0, "no station within 5 km: %d", r);
+}
+
+static void warnings(void)
+{
+ struct tm tm = {.tm_year = 126, .tm_mon = 9, .tm_mday = 1, .tm_hour = 12};
+ time_t now = timegm(&tm);
+ struct wx_alert *v;
+ size_t n;
+ char err[256];
+ int r = wx_meteoalarm_parse(METEOALARM, sizeof METEOALARM - 1, "Sicilia",
+ "it", now, &v, &n, err, sizeof err);
+ CHECK(r == 0, "MeteoAlarm: %s", err);
+ /* the expired and the green left out, the yellow given twice once */
+ CHECK(n == 2, "warnings: %zu", n);
+ if (n == 2) {
+ CHECK(v[0].mine && strcmp(v[0].level, "yellow") == 0 &&
+ strstr(v[0].area, "Sicilia"),
+ "Sicily's first: %d %s %s", v[0].mine, v[0].level, v[0].area);
+ CHECK(!v[1].mine && strcmp(v[1].level, "orange") == 0,
+ "then the rest: %s", v[1].level);
+ }
+ free(v);
+
+ char lv[3][96], zones[192];
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Trapani", NAN, NAN, lv,
+ zones, sizeof zones, err, sizeof err);
+ CHECK(r == 1 && strstr(zones, "Egadi") && strstr(zones, "Zona di prova"),
+ "Trapani's zones: %d %s", r, zones);
+ CHECK(strstr(lv[0], "NESSUNA") && strstr(lv[2], "GIALLA"),
+ "the highest of its zones: %s / %s", lv[0], lv[2]);
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Torino", NAN, NAN, lv, zones,
+ sizeof zones, err, sizeof err);
+ CHECK(r == 1 && strstr(lv[0], "ROSSA"), "Turin: %s", lv[0]);
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Roma", 41.9, 12.5, lv, zones,
+ sizeof zones, err, sizeof err);
+ CHECK(r == 0, "Rome not in it: %d", r);
+ /* a name the bulletin does not have: by the point, in a polygon (an
+ open ring, closed by the reader) and in a multipolygon */
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Turin", 45.07, 7.69, lv,
+ zones, sizeof zones, err, sizeof err);
+ CHECK(r == 1 && strstr(lv[0], "ROSSA") && strcmp(zones, "Altrove") == 0,
+ "Turin by the point: %d %s", r, zones);
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Turin", 45.01, 7.61, lv,
+ zones, sizeof zones, err, sizeof err);
+ CHECK(r == 0, "in the polygon's hole: %d %s", r, zones);
+ r = wx_dpc_parse(DPC_DAY, sizeof DPC_DAY - 1, "Trapani/Birgi Arpt", 37.91,
+ 12.49, lv, zones, sizeof zones, err, sizeof err);
+ CHECK(r == 1 && strstr(lv[2], "GIALLA") &&
+ strcmp(zones, "Zona di prova") == 0,
+ "Birgi by the point: %d %s", r, zones);
+}
+
+static void words(void)
+{
+ char s[96];
+ CHECK(strcmp(wx_code_text(63), "rain") == 0 && !wx_code_text(42),
+ "WMO codes");
+ wx_symbol_text("lightrainshowersandthunder_day", s, sizeof s);
+ CHECK(strcmp(s, "light rain showers and thunder") == 0, "symbol: '%s'", s);
+ wx_symbol_text("clearsky_night", s, sizeof s);
+ CHECK(strcmp(s, "clear sky") == 0, "symbol: '%s'", s);
+ CHECK(strcmp(wx_wind_words(13.4), "gentle breeze") == 0 &&
+ strcmp(wx_wind_words(130), "hurricane force") == 0,
+ "Beaufort");
+ CHECK(strcmp(wx_sea_words(0.08), "calm") == 0 &&
+ strcmp(wx_sea_words(1.5), "moderate") == 0,
+ "Douglas");
+ wx_from_dir(321, s, sizeof s);
+ CHECK(strcmp(s, "from the north-west (321°)") == 0, "direction: '%s'", s);
+}
+
+int main(void)
+{
+ alarm(60);
+ forecast();
+ sea();
+ station();
+ warnings();
+ words();
+ if (failures) {
+ printf("test_weather_parse: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_weather_parse: ok\n");
+ return 0;
+}
diff --git a/tools/gen_geo.c b/tools/gen_geo.c
index 97260fd..6e014d2 100644
--- a/tools/gen_geo.c
+++ b/tools/gen_geo.c
@@ -1,8 +1,8 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * gen_geo.c - generates src/flights/geo_data.h, the tables of janas-flights'
- * geography (src/flights/geo.h): countries, first-level regions, time
+ * gen_geo.c - generates src/common/geo_data.h, the tables of Janas's
+ * services' geography (src/common/geo.h): countries, first-level regions, time
* zones, cities of 30,000 people or more and every capital, the airports
* with an IATA code and scheduled flights, and the seas as polygons.
*
@@ -19,7 +19,7 @@
* An airport's time zone is that of the nearest city. The seas' outlines
* are simplified to about a kilometre (Douglas-Peucker, 0.01 degree).
*
- * Usage: gen_geo <data-directory> > src/flights/geo_data.h
+ * Usage: gen_geo <data-directory> > src/common/geo_data.h
*/
#include <math.h>
#include <stdint.h>
@@ -483,7 +483,7 @@ int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr,
- "usage: gen_geo <data-directory> > src/flights/geo_data.h\n");
+ "usage: gen_geo <data-directory> > src/common/geo_data.h\n");
return 2;
}
snprintf(dir, sizeof dir, "%s", argv[1]);