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.
C avx2ccpu-inferenceggufinference-enginelinuxllmlocal-llmmixture-of-expertsmoenvmequantizationqwen3simdspeculative-decodingvulkan
Release 2026-10-02: layouts - the services' data in the user's language, a brief to the model; a glossary of the scales' terms
camauri8eb26dcb83bf
diff --git a/ChangeLog.md b/ChangeLog.mdindex af3a1ce..d96c593 100644--- a/ChangeLog.md+++ b/ChangeLog.md@@ -2,6 +2,12 @@> Curated, user-facing summary of completed work, newest first.+## [2026-10-02] - Layouts: the services' data in the user's language, a brief to the model++- **The longest answers of the services come as data with a layout**: the aircraft over a sea and near a place, the weather now, the forecast and the sea. `janas-chat` fills the layout in the user's language and shows it, and the model reads only a brief of the figures. With Qwen3.6-35B-A3B, "how many aircraft over the Tyrrhenian now?" read 101 tokens and wrote 16, 3 s, against 3,011 and 334, 64 s; the weather in Trapani 162 tokens instead of about 400.+- **A layout is translated once, by the model, on the side** (`janas_llm_chat_aside`: the conversation saved and put back), checked, and kept in `~/.config/janas/layouts`. The model never sees the tags: asked to keep them, the 35B changed a key and a field in two layouts of the weather. It gets numbered markers and numbered words with what each word is (a Beaufort force, a Douglas sea state), and the tags and keys are put back. The scales' terms come from a glossary instead, for Italian, French, Spanish and German: the Beaufort forces and the Douglas sea states as the national weather services name them ("bava di vento", "poco mosso"; the model had written "brezza leggera", "liscio" and "burrasna"), never asked of the model, with the running text's terms of the sea ("mare lungo" for the swell) given to it in the request. The sea's states are now numbered as Douglas degrees, 1 to 9: they were one below.+- **In the libraries**: `src/common/template.c` (fields, words, lists, parts, a translation's shape checked); `janas_tpl_result` for the services; `janas_mcp_result_json`, a call's whole result; `janas_llm_chat_aside`. The MCP server merges a tool's `_meta` with its own, which two `_meta` keys had hidden.+## [2026-10-01] - janas-wiki, and the services together- **The services' tools are given when a question needs them.** The system message holds a catalog of Janas's services, a line each, and one tool, `janas__open_service`: the model opens a service, gets its instructions and tools as the call's answer, and calls them from then on; the next reply is held to be a call, since Qwen3.5-0.8B, told to call one, made the weather up instead. In the library, `janas_llm_chat_tools_add` (also in `llm.bi`): tools the model may call that are not written into the system message. With Qwen3.6-35B-A3B the system message went from 4,057 tokens to 616 (11 s the first time instead of 74), and opening the weather costs 1,048 tokens once in a conversation; one session asked the weather, a page of Wikipedia and the aircraft over the Tyrrhenian, opening each service when it came to it. `--all-tools` writes them all as before.diff --git a/build.sh b/build.shindex 8258bc2..b7d2d38 100755--- a/build.sh+++ b/build.sh@@ -336,9 +336,10 @@ if [ "$VARIANT" = release ]; thencase "$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) ;;+ # the services': the geography's tables, the GET over HTTPS,+ # where the user is and the layouts of their answers+ */common_geo.o | */common_https_get.o | */common_locate.o | \+ */common_template.o) ;;*/llm_json.o) mcp_objs+=("$o") llm_objs+=("$o") ;;*) llm_objs+=("$o") ;;esacdiff --git a/docs/services/README.md b/docs/services/README.mdindex e3d1409..9c6a4fb 100644--- a/docs/services/README.md+++ b/docs/services/README.md@@ -15,6 +15,7 @@ What every service does the same way:- **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.- **Only what was asked.** A service's tools are used for its subject when the user asks about it, and never because of another's answer: no weather or flights for the town a page names, unless the user asks for them.+- **Data and a layout.** The longest answers - the aircraft over a sea or near a place, the weather now, the forecast, the sea - come as data with a layout (MCP's `structuredContent`, the layout in `_meta`) besides their English text. `janas-chat` fills the layout in the user's language and shows it, and gives the model only a brief: the figures it needs to answer in a line or two. A list of forty aircraft cost the model 3,000 tokens to read and as many to write again; it now reads about a hundred. The layout in another language than English is asked of the model once, on the side of the conversation: it gets the text with the layout's tags as numbered markers and its words numbered one a line, never the tags themselves, which are put back and checked (a word it leaves out stays English; a marker left out, and the English layout is used). The terms of the scales - the Beaufort forces, the Douglas sea states - are not asked: in Italian, French, Spanish and German they come from a glossary in `janas-chat`, with the names the national weather services give them, and the request gives the model the terms of the sea for the rest of the text. It is kept in `~/.config/janas/layouts`, one file a layout and language, where it can be corrected by hand; a new version of a layout is translated anew. The language is the computer's (`LANG`).- **What is the user's goes to the user.** A page of Wikipedia is shown as it is, and the model reads only a note of it: MCP marks each part of an answer with its audience, and `janas-chat` shows the parts meant for the user alone instead of giving them to the model. A client that does not heed the audience gives the model both.- **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)).diff --git a/include/janas/llm.bi b/include/janas/llm.biindex 8e400ef..d370314 100644--- a/include/janas/llm.bi+++ b/include/janas/llm.bi@@ -330,6 +330,18 @@ declare function janas_llm_chat_tools(byval c as janas_llm_chat ptr, _declare function janas_llm_chat_tools_add(byval c as janas_llm_chat ptr, _byval json as const zstring ptr, _byval length as long) as long+'' A request on the side, between two replies: system (may be NULL) and+'' text answered greedily in at most max_tokens into buf; the conversation+'' is put back as it was.+declare function janas_llm_chat_aside(byval c as janas_llm_chat ptr, _+ byval system as const zstring ptr, _+ byval system_len as long, _+ byval text as const zstring ptr, _+ byval text_len as long, _+ byval max_tokens as long, _+ byval buf as zstring ptr, _+ byval cap as long, _+ byval length as long ptr) as longdeclare function janas_llm_chat_tool_choice(byval c as janas_llm_chat ptr, _byval choice as long, _byval name_ as const zstring ptr, _diff --git a/include/janas/llm.h b/include/janas/llm.hindex 2d4ac7a..e905c75 100644--- a/include/janas/llm.h+++ b/include/janas/llm.h@@ -481,6 +481,20 @@ JANAS_LLM_API int32_t janas_llm_chat_tools(janas_llm_chat *c, const char *json,JANAS_LLM_API int32_t janas_llm_chat_tools_add(janas_llm_chat *c,const char *json, int32_t len);+/*+ * A request on the side, between two replies: a system message (NULL:+ * none) and a user message, answered greedily, with no reasoning, in at+ * most max_tokens, into buf (as the other texts: *len its length, and+ * JANAS_LLM_ESMALL when cap cannot hold it). The conversation is saved+ * first and put back after as it was: the next message continues it.+ * janas-chat asks this way for a service's layout in the user's language,+ * once. It costs the reading of the request and of the answer, and memory+ * for a copy of the conversation.+ */+JANAS_LLM_API int32_t janas_llm_chat_aside(+ janas_llm_chat *c, const char *system, int32_t system_len, const char *text,+ int32_t text_len, int32_t max_tokens, char *buf, int32_t cap, int32_t *len);+/* Whether the model calls a tool, from the next reply on: as it judges(AUTO, default), never (NONE), at least one (REQUIRED), or the functionnamed (FUNCTION, name of len bytes). parallel 0 allows one call at mostdiff --git a/include/janas/mcp.bi b/include/janas/mcp.biindex 3ad0292..d9839a7 100644--- a/include/janas/mcp.bi+++ b/include/janas/mcp.bi@@ -118,6 +118,12 @@ declare function janas_mcp_result_user(byval m as const janas_mcp ptr, _byval buf as zstring ptr, _byval cap as long, _byval length as long ptr) as long+'' The whole result of the last call as JSON (content, structuredContent,+'' _meta...).+declare function janas_mcp_result_json(byval m as const janas_mcp ptr, _+ byval buf as zstring ptr, _+ byval cap as long, _+ byval length as long ptr) as longdeclare sub janas_mcp_cancel(byval m as janas_mcp ptr)end externdiff --git a/include/janas/mcp.h b/include/janas/mcp.hindex a184815..b0eccff 100644--- a/include/janas/mcp.h+++ b/include/janas/mcp.h@@ -183,6 +183,10 @@ JANAS_MCP_API int32_t janas_mcp_result_error(const janas_mcp *m);*/JANAS_MCP_API int32_t janas_mcp_result_user(const janas_mcp *m, char *buf,int32_t cap, int32_t *len);+/* The whole result of the last call as JSON (content, structuredContent,+ _meta...), for a client that does more with it than read its text. */+JANAS_MCP_API int32_t janas_mcp_result_json(const janas_mcp *m, char *buf,+ int32_t cap, int32_t *len);/* Stops the call in progress on m, which then returns an error; the serveris told (notifications/cancelled). */diff --git a/src/chat/glossary.c b/src/chat/glossary.cnew file mode 100644index 0000000..6f608cb--- /dev/null+++ b/src/chat/glossary.c@@ -0,0 +1,114 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * glossary.c - the terms of art of the layouts (see glossary.h). The+ * scales' names are those of the national services' tables: Aeronautica+ * Militare, Météo-France, AEMET, Deutscher Wetterdienst. The sea's state+ * is the Douglas degree (weather/words.c), 1 to 9; 0, the glassy sea, is+ * there for the table to be whole.+ */+#include "glossary.h"++#include <string.h>++static const struct {+ const char *lang;+ const char *bft[13]; /* Beaufort 0-12 */+ const char *sea[10]; /* Douglas 0-9 */+ const char *terms;+} G[] = {+ {"it",+ {"calma", "bava di vento", "brezza leggera", "brezza tesa",+ "vento moderato", "vento teso", "vento fresco", "vento forte", "burrasca",+ "burrasca forte", "tempesta", "tempesta violenta", "uragano"},+ {"calmo", "quasi calmo", "poco mosso", "mosso", "molto mosso", "agitato",+ "molto agitato", "grosso", "molto grosso", "tempestoso"},+ "swell = mare lungo; wind waves = mare di vento; significant height = "+ "altezza significativa; gusts = raffiche"},+ {"fr",+ {"calme", "très légère brise", "légère brise", "petite brise",+ "jolie brise", "bonne brise", "vent frais", "grand frais", "coup de vent",+ "fort coup de vent", "tempête", "violente tempête", "ouragan"},+ {"calme", "calme, ridée", "belle", "peu agitée", "agitée", "forte",+ "très forte", "grosse", "très grosse", "énorme"},+ "swell = houle; wind waves = mer du vent; significant height = "+ "hauteur significative; gusts = rafales"},+ {"es",+ {"calma", "ventolina", "flojito", "flojo", "bonancible", "fresquito",+ "fresco", "frescachón", "temporal", "temporal fuerte", "temporal duro",+ "temporal muy duro", "temporal huracanado"},+ {"calma", "rizada", "marejadilla", "marejada", "fuerte marejada", "gruesa",+ "muy gruesa", "arbolada", "montañosa", "enorme"},+ "swell = mar de fondo; wind waves = mar de viento; significant height "+ "= altura significativa; gusts = rachas"},+ {"de",+ {"Windstille", "leiser Zug", "leichte Brise", "schwache Brise",+ "mäßige Brise", "frische Brise", "starker Wind", "steifer Wind",+ "stürmischer Wind", "Sturm", "schwerer Sturm", "orkanartiger Sturm",+ "Orkan"},+ {"spiegelglatte See", "ruhige, gekräuselte See", "schwach bewegte See",+ "leicht bewegte See", "mäßig bewegte See", "grobe See", "sehr grobe See",+ "hohe See", "sehr hohe See", "außergewöhnlich schwere See"},+ "swell = Dünung; wind waves = Windsee; significant height = "+ "signifikante Wellenhöhe; gusts = Böen"},+};++static int find(const char *lang)+{+ for (size_t i = 0; lang && i < sizeof G / sizeof *G; i++)+ if (strcmp(G[i].lang, lang) == 0)+ return (int)i;+ return -1;+}++/* The degree after prefix in key, or -1. */+static int degree(const char *key, size_t n, const char *prefix, int top)+{+ size_t pn = strlen(prefix);+ if (n <= pn || n > pn + 2 || strncmp(key, prefix, pn) != 0)+ return -1;+ int d = 0;+ for (size_t i = pn; i < n; i++) {+ if (key[i] < '0' || key[i] > '9')+ return -1;+ d = d * 10 + (key[i] - '0');+ }+ return d <= top ? d : -1;+}++const char *glossary_word(const char *lang, const char *key, size_t n)+{+ int g = find(lang), d;+ if (g < 0)+ return NULL;+ if ((d = degree(key, n, "bft.", 12)) >= 0)+ return G[g].bft[d];+ if ((d = degree(key, n, "sea.", 9)) >= 0)+ return G[g].sea[d];+ return NULL;+}++const char *glossary_terms(const char *lang)+{+ int g = find(lang);+ return g < 0 ? NULL : G[g].terms;+}++static uint64_t fnv(uint64_t h, const char *s)+{+ for (; *s; s++)+ h = (h ^ (unsigned char)*s) * 1099511628211ull;+ return (h ^ '\n') * 1099511628211ull;+}++uint64_t glossary_mark(const char *lang, uint64_t h)+{+ int g = find(lang);+ if (g < 0)+ return h;+ for (int i = 0; i < 13; i++)+ h = fnv(h, G[g].bft[i]);+ for (int i = 0; i < 10; i++)+ h = fnv(h, G[g].sea[i]);+ return fnv(h, G[g].terms);+}diff --git a/src/chat/glossary.h b/src/chat/glossary.hnew file mode 100644index 0000000..15aace5--- /dev/null+++ b/src/chat/glossary.h@@ -0,0 +1,28 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * glossary.h - the terms of art of the layouts (layout.h) in the languages+ * Janas knows: the degrees of the Beaufort and Douglas scales as the+ * national weather services name them, which a model asked to translate+ * gets wrong ("liscio" for the Douglas sea "quasi calmo"). Everything else+ * is translated by the model.+ */+#ifndef JANAS_CHAT_GLOSSARY_H+#define JANAS_CHAT_GLOSSARY_H++#include <stddef.h>+#include <stdint.h>++/* The term of the word key (n bytes: "bft.4", "sea.3") in lang; NULL when+ the glossary has none. */+const char *glossary_word(const char *lang, const char *key, size_t n);++/* The terms of the running text in lang, for the request to the model+ ("swell = mare lungo; ..."); NULL when there are none. */+const char *glossary_terms(const char *lang);++/* h carried on (FNV-1a) over the glossary of lang: a layout kept on disk+ is translated again when the glossary changes. */+uint64_t glossary_mark(const char *lang, uint64_t h);++#endifdiff --git a/src/chat/layout.c b/src/chat/layout.cnew file mode 100644index 0000000..b630803--- /dev/null+++ b/src/chat/layout.c@@ -0,0 +1,456 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * layout.c - the layouts of the services' answers in janas-chat (see+ * layout.h).+ */+#define _GNU_SOURCE /* memmem, strndup */+#include "layout.h"++#include <errno.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>++#include "common/template.h"+#include "glossary.h"++#define META "dev.prabanta.janas/layout"++static char lang[16] = "en";+static int (*translator)(const char *, const char *, const char *, char **);++void layout_set_lang(const char *l)+{+ snprintf(lang, sizeof lang, "%s", l && *l ? l : "en");+}++const char *layout_lang(void)+{+ return lang;+}++void layout_set_translator(int (*fn)(const char *, const char *, const char *,+ char **))+{+ translator = fn;+}++/* The language's name, for the request. */+static const char *lang_name(const char *code)+{+ static const char *const names[][2] = {+ {"it", "Italian"}, {"fr", "French"}, {"de", "German"},+ {"es", "Spanish"}, {"pt", "Portuguese"}, {"nl", "Dutch"},+ {"ca", "Catalan"}, {"sc", "Sardinian"}, {"pl", "Polish"},+ {"ro", "Romanian"}, {"el", "Greek"}, {"sv", "Swedish"},+ };+ for (size_t i = 0; i < sizeof names / sizeof *names; i++)+ if (strcmp(names[i][0], code) == 0)+ return names[i][1];+ return code;+}++/* FNV-1a: the English layout's mark in the file's name, so that a layout+ changed by a new version of the service is translated again */+static uint64_t mark(const char *s)+{+ uint64_t h = 1469598103934665603ull;+ for (; *s; s++)+ h = (h ^ (unsigned char)*s) * 1099511628211ull;+ return h;+}++static int dir_of(char *buf, size_t cap)+{+ const char *xdg = getenv("XDG_CONFIG_HOME"), *home = getenv("HOME");+ int n = xdg && *xdg ? snprintf(buf, cap, "%s/janas", xdg)+ : home ? snprintf(buf, cap, "%s/.config/janas", home)+ : -1;+ if (n < 0 || (size_t)n >= cap)+ return -1;+ if (mkdir(buf, 0700) != 0 && errno != EEXIST)+ return -1;+ if ((size_t)n + 9 >= cap)+ return -1;+ strcat(buf, "/layouts");+ if (mkdir(buf, 0700) != 0 && errno != EEXIST)+ return -1;+ return 0;+}++static char *read_file(const char *path)+{+ FILE *f = fopen(path, "rb");+ if (!f)+ return NULL;+ struct janas_buf b = {0};+ char tmp[4096];+ size_t n;+ while ((n = fread(tmp, 1, sizeof tmp, f)) > 0)+ janas_buf_put(&b, tmp, n);+ fclose(f);+ janas_buf_put(&b, "", 1);+ if (b.oom) {+ janas_buf_free(&b);+ return NULL;+ }+ return b.p;+}++/* The model's answer as a layout: without the fence of a code block, and+ without blank lines around it. */+static void unwrap(char *s)+{+ char *p = s;+ while (*p == '\n' || *p == ' ')+ p++;+ if (strncmp(p, "```", 3) == 0) {+ char *nl = strchr(p, '\n');+ p = nl ? nl + 1 : p + 3;+ char *end = strstr(p, "\n```");+ if (end)+ *end = 0;+ }+ memmove(s, p, strlen(p) + 1);+ size_t n = strlen(s);+ while (n && (s[n - 1] == '\n' || s[n - 1] == ' '))+ s[--n] = 0;+}++/* The languages that write a decimal comma. */+static int comma_lang(const char *l)+{+ static const char *const c[] = {+ "it", "fr", "de", "es", "pt", "nl", "ca", "sc", "pl", "ro",+ "el", "sv", "da", "fi", "no", "nb", "cs", "sk", "hu", "ru",+ "uk", "tr", "hr", "sl", "sr", "bg", "lt", "lv", "et", "id"};+ for (size_t i = 0; i < sizeof c / sizeof *c; i++)+ if (strcmp(c[i], l) == 0)+ return 1;+ return 0;+}++/*+ * The model never sees a tag or a key: asked to keep them, Qwen3.6-35B-A3B+ * still wrote dir.NNN for dir.NNW and {{sst}} for {{sea}} in two layouts+ * of the weather. It gets the text with each tag as a numbered marker+ * ({7}, as in the message files programs are translated with) and the+ * words' texts numbered one a line; the tags and the keys are put back+ * here.+ */+static const char SYSTEM[] =+ "You translate the texts of a program. The text holds markers such as "+ "{7}: keep every marker exactly as it is, once each, where the sense "+ "puts it; never translate, change, add or drop one. After the line "+ "\"=== words\" come words and short phrases, one a line, each after "+ "its number and a colon (\"12: north-east\"): translate what follows "+ "the colon, keeping the numbers and the lines; what is in square "+ "brackets says what the word is (a term of a scale: give the "+ "language's own term) and is not to be written. Compass points as the "+ "language abbreviates them (in Italian W is O and SW is SO). Answer "+ "with the translated text, the line \"=== words\" and the words, "+ "nothing before or after.";++struct coded {+ struct janas_buf text; /* for the model */+ char **tags; /* {N}: tags[N - 1] */+ size_t n_tags;+ char **keys; /* word N: keys[N - 1], and its English text */+ char **english;+ size_t n_keys, n_english;+};++static void coded_free(struct coded *c)+{+ janas_buf_free(&c->text);+ for (size_t i = 0; i < c->n_tags; i++)+ free(c->tags[i]);+ for (size_t i = 0; i < c->n_keys; i++)+ free(c->keys[i]);+ for (size_t i = 0; i < c->n_english; i++)+ free(c->english[i]);+ free(c->english);+ free(c->tags);+ free(c->keys);+}++static int push(char ***v, size_t *n, const char *s, size_t len)+{+ char **g = realloc(*v, (*n + 1) * sizeof **v);+ if (!g)+ return -1;+ *v = g;+ if (!(g[*n] = malloc(len + 1)))+ return -1;+ memcpy(g[*n], s, len);+ g[*n][len] = 0;+ (*n)++;+ return 0;+}++/* What a word is, for the model to find the language's own term: the+ names of the scales are terms of art (Beaufort 1 is "bava di vento" in+ Italian, not a word for "light air"). Left out of the answer. */+static const char *hint(const char *key, size_t n)+{+ static char h[96];+ static const struct {+ const char *prefix, *what;+ } k[] = {{"bft.", "Beaufort wind force"},+ {"sea.", "Douglas sea state"},+ {"wmo.", "WMO weather code"},+ {"cover.", "METAR cloud cover"},+ {"wx.", "METAR present weather"},+ {"dir.", "compass point, abbreviated"},+ {"from.", "wind direction"},+ {"wd.", "day of the week"},+ {"mon.", "month"}};+ for (size_t i = 0; i < sizeof k / sizeof *k; i++) {+ size_t pn = strlen(k[i].prefix);+ if (n > pn && strncmp(key, k[i].prefix, pn) == 0) {+ snprintf(h, sizeof h, " [%s %.*s]", k[i].what, (int)(n - pn),+ key + pn);+ return h;+ }+ }+ return "";+}++/* The layout without its tags and keys, for the model. */+static int encode(const char *en, struct coded *c)+{+ memset(c, 0, sizeof *c);+ const char *sep = strstr(en, "\n---\n");+ size_t ln = sep ? (size_t)(sep - en) : strlen(en);+ for (size_t i = 0; i < ln;) {+ const char *open = memmem(en + i, ln - i, "{{", 2);+ size_t upto = open ? (size_t)(open - en) : ln;+ janas_buf_put(&c->text, en + i, upto - i);+ if (!open)+ break;+ const char *close = memmem(open, ln - upto, "}}", 2);+ if (!close)+ return -1;+ size_t end = (size_t)(close - en) + 2;+ if (push(&c->tags, &c->n_tags, open, end - upto) != 0)+ return -1;+ janas_buf_printf(&c->text, "{%zu}", c->n_tags);+ i = end;+ }+ janas_buf_puts(&c->text, "\n=== words\n");+ for (const char *p = sep ? sep + 5 : en + ln; *p;) {+ const char *nl = strchr(p, '\n');+ size_t len = nl ? (size_t)(nl - p) : strlen(p);+ const char *eq = memchr(p, '=', len);+ if (eq && *p != '#') {+ const char *a = p, *b = eq;+ while (b > a && b[-1] == ' ')+ b--;+ const char *v = eq + 1;+ while (*v == ' ')+ v++;+ if (push(&c->keys, &c->n_keys, a, (size_t)(b - a)) != 0 ||+ push(&c->english, &c->n_english, v, (size_t)(p + len - v)) != 0)+ return -1;+ /* a term of the glossary is not asked: decode puts it */+ if (!glossary_word(lang, a, (size_t)(b - a)))+ janas_buf_printf(&c->text, "%zu: %.*s%s\n", c->n_keys,+ (int)(p + len - v), v,+ hint(a, (size_t)(b - a)));+ }+ p = nl ? nl + 1 : p + len;+ }+ return c->text.oom ? -1 : 0;+}++/* The model's answer with the tags and keys put back; NULL with the+ reason in why when a marker or a word is missing, doubled or made up. */+static char *decode(const struct coded *c, const char *ans, char *why,+ size_t why_len)+{+ const char *w = strstr(ans, "=== words");+ if (!w) {+ snprintf(why, why_len, "no words");+ return NULL;+ }+ size_t tn = (size_t)(w - ans);+ while (tn && (ans[tn - 1] == '\n' || ans[tn - 1] == ' '))+ tn--;+ int *seen = calloc(c->n_tags + 1, sizeof *seen);+ char **val = calloc(c->n_keys + 1, sizeof *val);+ struct janas_buf out = {0};+ int bad = !seen || !val;+ for (size_t i = 0; !bad && i < tn;) {+ if (ans[i] == '{') {+ char *end;+ unsigned long k = strtoul(ans + i + 1, &end, 10);+ if (end > ans + i + 1 && *end == '}') {+ if (k < 1 || k > c->n_tags || seen[k]++) {+ snprintf(why, why_len, "marker {%lu} made up or doubled",+ k);+ bad = 1;+ break;+ }+ janas_buf_puts(&out, c->tags[k - 1]);+ i = (size_t)(end - ans) + 1;+ continue;+ }+ }+ janas_buf_put(&out, ans + i, 1);+ i++;+ }+ for (size_t k = 1; !bad && k <= c->n_tags; k++)+ if (!seen[k]) {+ snprintf(why, why_len, "marker {%zu} dropped", k);+ bad = 1;+ }+ for (size_t k = 1; !bad && k <= c->n_keys; k++) {+ const char *g =+ glossary_word(lang, c->keys[k - 1], strlen(c->keys[k - 1]));+ if (g)+ val[k] = strdup(g);+ }+ for (const char *p = w; !bad && *p;) {+ const char *nl = strchr(p, '\n');+ size_t len = nl ? (size_t)(nl - p) : strlen(p);+ char *end;+ unsigned long k = strtoul(p, &end, 10);+ if (end > p && *end == ':' && k >= 1 && k <= c->n_keys && !val[k]) {+ const char *v = end + 1;+ while (*v == ' ')+ v++;+ size_t vn = (size_t)(p + len - v);+ const char *br = memchr(v, '[', vn); /* the hint, if repeated */+ if (br)+ vn = (size_t)(br - v);+ while (vn && (v[vn - 1] == ' ' || v[vn - 1] == '\r'))+ vn--;+ val[k] = strndup(v, vn);+ }+ p = nl ? nl + 1 : p + len;+ }+ /* a word left out stays English: the layout still holds (a marker+ left out would not) - Qwen3.6-35B-A3B skipped one line in a hundred */+ for (size_t k = 1; !bad && k <= c->n_keys; k++)+ if (!val[k])+ val[k] = strdup(c->english[k - 1]);+ if (!bad) {+ janas_buf_puts(&out, "\n---\n");+ for (size_t k = 1; k <= c->n_keys; k++)+ janas_buf_printf(&out, "%s = %s\n", c->keys[k - 1], val[k]);+ if (comma_lang(lang))+ janas_buf_puts(&out, "decimal = ,\n");+ janas_buf_put(&out, "", 1);+ }+ for (size_t k = 0; val && k <= c->n_keys; k++)+ free(val[k]);+ free(val);+ free(seen);+ if (bad || out.oom) {+ janas_buf_free(&out);+ return NULL;+ }+ return out.p;+}++/* The layout of name in the user's language: from the file, or asked of+ the model and kept; NULL when there is none (English is used). */+static char *translated(const char *name, const char *en)+{+ char dir[1024], path[1200];+ if (dir_of(dir, sizeof dir) != 0)+ return NULL;+ snprintf(path, sizeof path, "%s/%s.%s.%016llx.txt", dir, name, lang,+ (unsigned long long)glossary_mark(lang, mark(en)));+ char *have = read_file(path);+ char why[200];+ if (have && janas_tpl_same_shape(en, strlen(en), have, strlen(have), why,+ sizeof why))+ return have;+ free(have);+ struct coded c;+ if (!translator || encode(en, &c) != 0)+ return NULL;+ struct janas_buf ask = {0};+ const char *terms = glossary_terms(lang);+ janas_buf_printf(&ask, "Translate into %s%s%s:\n\n%.*s", lang_name(lang),+ terms ? ", with these terms: " : "", terms ? terms : "",+ (int)c.text.n, c.text.p);+ char *ans = NULL;+ int r = ask.oom ? -1 : translator(name, SYSTEM, ask.p, &ans);+ janas_buf_free(&ask);+ char *out = NULL;+ if (r == 0 && ans) {+ unwrap(ans);+ out = decode(&c, ans, why, sizeof why);+ } else {+ snprintf(why, sizeof why, "no answer");+ }+ free(ans);+ coded_free(&c);+ if (out && !janas_tpl_same_shape(en, strlen(en), out, strlen(out), why,+ sizeof why)) {+ free(out);+ out = NULL;+ }+ if (!out) {+ fprintf(stderr,+ "janas-chat: the layout %s in %s is not usable (%s): "+ "English is used\n",+ name, lang, why);+ return NULL;+ }+ FILE *f = fopen(path, "wb");+ if (f) {+ fputs(out, f);+ fclose(f);+ }+ return out;+}++static char *fill(const char *tpl, const struct janas_json *data)+{+ struct janas_buf b = {0};+ char err[200];+ if (janas_tpl_render(tpl, strlen(tpl), data, &b, err, sizeof err) != 0) {+ fprintf(stderr, "janas-chat: a layout could not be filled: %s\n", err);+ janas_buf_free(&b);+ return NULL;+ }+ janas_buf_put(&b, "", 1);+ return b.oom ? NULL : b.p;+}++int layout_take(const char *result, size_t n, char **user, char **model)+{+ *user = *model = NULL;+ struct janas_json_doc *d = janas_json_parse(result, n, NULL, 0);+ const struct janas_json *r = d ? janas_json_root(d) : NULL;+ const struct janas_json *meta =+ janas_json_get(janas_json_get(r, "_meta"), META);+ const struct janas_json *data = janas_json_get(r, "structuredContent");+ const char *name = janas_json_str(janas_json_get(meta, "name"));+ const char *en = janas_json_str(janas_json_get(meta, "text"));+ const char *brief = janas_json_str(janas_json_get(meta, "brief"));+ int ok = 0;+ if (name && en && brief && data && data->type == JANAS_JSON_OBJECT &&+ !strchr(name, '/') && name[0] != '.') {+ char *mine = strcmp(lang, "en") != 0 ? translated(name, en) : NULL;+ *user = fill(mine ? mine : en, data);+ if (!*user && mine) /* a translation that does not fill: English */+ *user = fill(en, data);+ free(mine);+ *model = fill(brief, data);+ ok = *user && *model;+ if (!ok) {+ free(*user);+ free(*model);+ *user = *model = NULL;+ }+ }+ janas_json_free(d);+ return ok;+}diff --git a/src/chat/layout.h b/src/chat/layout.hnew file mode 100644index 0000000..33c5949--- /dev/null+++ b/src/chat/layout.h@@ -0,0 +1,33 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * layout.h - the layouts of the services' answers in janas-chat+ * (common/template.h): an answer that brings its data and an English+ * layout is shown to the user filled in the user's language, and the model+ * reads only its brief. The layout in another language is asked of the+ * model once, checked against the English one and kept in+ * ~/.config/janas/layouts; the scales' terms come from the glossary+ * (glossary.h), not from the model.+ */+#ifndef JANAS_CHAT_LAYOUT_H+#define JANAS_CHAT_LAYOUT_H++#include <stddef.h>++/* The user's language ("it"; "en" or NULL: English, no translation). */+void layout_set_lang(const char *lang);+const char *layout_lang(void);++/* How a layout is translated: system and user messages to the model, its+ answer into *out (malloc'd). 0, or -1. Called once a layout and+ language; what it says on the terminal is its own. */+void layout_set_translator(int (*fn)(const char *name, const char *system,+ const char *text, char **out));++/* A tools/call result (JSON) with a layout: 1 with the text for the user+ in *user and the brief for the model in *model (both malloc'd); 0 when+ it has none, or it could not be filled (then the answer is used as it+ came). */+int layout_take(const char *result, size_t n, char **user, char **model);++#endifdiff --git a/src/chat/main.c b/src/chat/main.cindex dccfb23..43e5cd5 100644--- a/src/chat/main.c+++ b/src/chat/main.c@@ -30,6 +30,7 @@#include "common/sysinfo.h"#include "edit.h"+#include "layout.h"#include "janas/llm.h"#include "markdown.h"#include "mcp_chat.h"@@ -645,6 +646,58 @@ static void prep_wait(const janas_llm *llm, int stop)prep.on = 0;}+/*+ * A service's layout in the user's language, asked of the model on the+ * side (the conversation saved and put back): once a layout and language,+ * then kept. Said on the terminal, as it takes a while.+ */+static janas_llm_chat *aside_chat;++static int translate(const char *name, const char *system, const char *text,+ char **out)+{+ if (!aside_chat)+ return -1;+ term_gap(&term);+ prep_say(T_USER(&term),+ "Writing the layout of %s's answers in your language (%s), "+ "once: it is kept in ~/.config/janas/layouts.",+ name, layout_lang());+ footer(idle_llm, aside_chat, "writing a layout");+ size_t cap = 32768;+ char *buf = malloc(cap);+ int32_t len = 0;+ if (!buf || janas_llm_chat_aside(aside_chat, system, -1, text, -1, 4096,+ buf, (int32_t)cap, &len) != JANAS_LLM_OK) {+ prep_say(T_WARN(&term), "the layout could not be written: %s",+ buf ? janas_llm_last_error() : "out of memory");+ free(buf);+ return -1;+ }+ *out = buf;+ return 0;+}++/* The user's language, from the computer's (LANG=it_IT.UTF-8: it). */+static void user_lang(void)+{+ static const char *const vars[] = {"LC_ALL", "LC_MESSAGES", "LANG"};+ for (size_t i = 0; i < sizeof vars / sizeof *vars; i++) {+ const char *v = getenv(vars[i]);+ if (!v || !*v)+ continue;+ char l[16];+ size_t n = strcspn(v, "_.@");+ snprintf(l, sizeof l, "%.*s", (int)(n < 15 ? n : 15), v);+ int ok = n >= 2 && n <= 3;+ for (size_t k = 0; ok && k < n; k++)+ ok = l[k] >= 'a' && l[k] <= 'z';+ layout_set_lang(ok ? l : "en");+ return;+ }+ layout_set_lang("en");+}+static void restart(janas_llm_chat *c, const char *system){janas_llm_chat_reset(c);@@ -1425,6 +1478,9 @@ int main(int argc, char **argv)fprintf(stderr, "janas-chat: %s\n", janas_llm_last_error());/* the tools of the MCP servers configured and of Janas's own servicesbeside the program, given to the model */+ aside_chat = c;+ user_lang();+ layout_set_translator(translate);if (mcp) {mcpc_defer(!all_tools);mcpc_start(mcp_config);diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.cindex 9b11c71..a009fa1 100644--- a/src/chat/mcp_chat.c+++ b/src/chat/mcp_chat.c@@ -13,6 +13,7 @@#include <sys/stat.h>#include <unistd.h>+#include "layout.h"#include "llm/json.h"/* An answer longer than this is cut: the context is the model's memory of@@ -578,6 +579,21 @@ int mcpc_call(const char *name, const char *args, char **text, char **shown)(size_t)len - keep);}*text = t;+ /* data with a layout: the user's text from it, the model's brief */+ int32_t rl = 0;+ janas_mcp_result_json(s->m, NULL, 0, &rl);+ char *raw = rl > 0 ? malloc((size_t)rl + 1) : NULL;+ char *user = NULL, *brief = NULL;+ if (raw && janas_mcp_result_json(s->m, raw, rl + 1, &rl) == JANAS_MCP_OK &&+ !janas_mcp_result_error(s->m) &&+ layout_take(raw, (size_t)rl, &user, &brief)) {+ free(*text);+ *text = brief;+ *shown = user;+ free(raw);+ return 0;+ }+ free(raw);int32_t ul = 0;janas_mcp_result_user(s->m, NULL, 0, &ul);if (ul > 0 && (*shown = malloc((size_t)ul + 1)) != NULL &&diff --git a/src/common/geo.c b/src/common/geo.cindex 539fdd2..f4cb43f 100644--- a/src/common/geo.c+++ b/src/common/geo.c@@ -371,17 +371,25 @@ const struct geo_city *geo_city_near(double lat, double lon, double *km)return near;}-void geo_describe(double lat, double lon, struct janas_buf *b)+/* Where a point is: the sea it is over (NULL: land), the nearest city+ and the nearest of another region that lies the other way (NULL: none+ worth naming), and how far and which way from the nearest. */+struct where {+ const char *sea;+ const struct geo_city *near, *other;+ double km;+ const char *dir;+};++static int where_parts(double lat, double lon, struct where *w){/* the nearest city, and the nearest of another region that lies theother 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;- }+ if (!near)+ return -1;double b_near = geo_bearing(lat, lon, DEG(near->lat), DEG(near->lon));for (size_t i = 0; i < N_OF(geo_cities); i++) {const struct geo_city *c = &geo_cities[i];@@ -398,26 +406,77 @@ void geo_describe(double lat, double lon, struct janas_buf *b)other = c;}}- const char *sea = geo_sea_at(lat, lon);- if (sea) {- janas_buf_printf(b, "over the %s", sea);- if (other && d_other < 3 * d_near + 100 && d_other < 400) {+ *w = (struct where){.sea = geo_sea_at(lat, lon),+ .near = near,+ .km = d_near,+ .dir = geo_compass(geo_bearing(+ DEG(near->lat), DEG(near->lon), lat, lon))};+ if (w->sea && other && d_other < 3 * d_near + 100 && d_other < 400)+ w->other = other;+ return 0;+}++void geo_describe(double lat, double lon, struct janas_buf *b)+{+ struct where w;+ if (where_parts(lat, lon, &w) != 0) {+ janas_buf_printf(b, "at %.2f, %.2f", lat, lon);+ return;+ }+ if (w.sea) {+ janas_buf_printf(b, "over the %s", w.sea);+ if (w.other) {janas_buf_puts(b, ", between ");- where_of(near, b);+ where_of(w.near, b);janas_buf_puts(b, " and ");- where_of(other, b);+ where_of(w.other, b);}janas_buf_puts(b, "; ");} else {janas_buf_puts(b, "over ");- where_of(near, b);+ where_of(w.near, b);janas_buf_puts(b, "; ");}- if (d_near < 3)- janas_buf_printf(b, "over %s", near->name);+ if (w.km < 3)+ janas_buf_printf(b, "over %s", w.near->name);else- janas_buf_printf(- b, "%.0f km %s of %s", d_near,- geo_compass(geo_bearing(DEG(near->lat), DEG(near->lon), lat, lon)),- near->name);+ janas_buf_printf(b, "%.0f km %s of %s", w.km, w.dir, w.near->name);+}++static void json_str(struct janas_buf *b, const char *key, const char *v)+{+ janas_buf_printf(b, "\"%s\": ", key);+ janas_json_write_str(b, v, strlen(v));+}++void geo_describe_json(double lat, double lon, struct janas_buf *b)+{+ struct where w;+ if (where_parts(lat, lon, &w) != 0) {+ janas_buf_printf(b, "{\"lat\": %.2f, \"lon\": %.2f}", lat, lon);+ return;+ }+ struct janas_buf r = {0};+ where_of(w.near, &r);+ janas_buf_puts(b, "{");+ if (w.sea) {+ json_str(b, "sea", w.sea);+ janas_buf_puts(b, ", ");+ }+ janas_buf_puts(b, "\"region\": ");+ janas_json_write_str(b, r.p ? r.p : "", r.n);+ if (w.other) {+ r.n = 0;+ where_of(w.other, &r);+ janas_buf_puts(b, ", \"and\": ");+ janas_json_write_str(b, r.p ? r.p : "", r.n);+ }+ janas_buf_puts(b, ", ");+ json_str(b, "city", w.near->name);+ if (w.km >= 3) {+ janas_buf_printf(b, ", \"km\": %.0f, ", w.km);+ json_str(b, "dir", w.dir);+ }+ janas_buf_puts(b, "}");+ janas_buf_free(&r);}diff --git a/src/common/geo.h b/src/common/geo.hindex ce08a76..04b8a5b 100644--- a/src/common/geo.h+++ b/src/common/geo.h@@ -99,5 +99,10 @@ int geo_area_has(const struct geo_area *a, double lat, double lon);/* The position in words, appended to b. */void geo_describe(double lat, double lon, struct janas_buf *b);+/* The same as a JSON object, for a layout (common/template.h): "sea" when+ over one, "region" ("Sicily, Italy": the region over, or the first of+ the two a sea lies between), "and" (the second), "city", and "km" and+ "dir" from it when 3 km or more away. */+void geo_describe_json(double lat, double lon, struct janas_buf *b);#endifdiff --git a/src/common/mcp_client.c b/src/common/mcp_client.cindex dc65bf7..d6f05c7 100644--- a/src/common/mcp_client.c+++ b/src/common/mcp_client.c@@ -470,6 +470,7 @@ void janas_mcp_close(janas_mcp *m)free(m->instructions);janas_buf_free(&m->result);janas_buf_free(&m->shown);+ janas_buf_free(&m->raw);free(m);}@@ -747,6 +748,7 @@ int32_t janas_mcp_call(janas_mcp *m, const char *name, int32_t name_len,__atomic_store_n(&m->cancel, 0, __ATOMIC_RELAXED);m->result.n = 0;m->shown.n = 0;+ m->raw.n = 0;m->result_error = 0;size_t nn = name_len < 0 ? strlen(name) : (size_t)name_len;size_t an = !args ? 0 : args_len < 0 ? strlen(args) : (size_t)args_len;@@ -827,7 +829,7 @@ int32_t janas_mcp_call(janas_mcp *m, const char *name, int32_t name_len,elsejanas_mcp_take_result(m, a.result);janas_rpc_free(&a);- if (rc == JANAS_MCP_OK && (m->result.oom || m->shown.oom))+ if (rc == JANAS_MCP_OK && (m->result.oom || m->shown.oom || m->raw.oom))rc = janas_mcp_fail(JANAS_MCP_ENOMEM, "out of memory");return rc;}@@ -848,6 +850,14 @@ int32_t janas_mcp_result_user(const janas_mcp *m, char *buf, int32_t cap,return copy_out(m->shown.p ? m->shown.p : "", m->shown.n, buf, cap, len);}+int32_t janas_mcp_result_json(const janas_mcp *m, char *buf, int32_t cap,+ int32_t *len)+{+ if (!m)+ return janas_mcp_fail(JANAS_MCP_EINVAL, "invalid argument");+ return copy_out(m->raw.p ? m->raw.p : "", m->raw.n, buf, cap, len);+}+int32_t janas_mcp_result_error(const janas_mcp *m){return m ? m->result_error : 0;diff --git a/src/common/mcp_client.h b/src/common/mcp_client.hindex 81d5a27..8c749db 100644--- a/src/common/mcp_client.h+++ b/src/common/mcp_client.h@@ -56,6 +56,7 @@ struct janas_mcp {size_t n_tools;struct janas_buf result; /* the last call's answer, as text */struct janas_buf shown; /* its parts for the user alone (audience) */+ struct janas_buf raw; /* the whole result, as JSON */int result_error;volatile sig_atomic_t cancel;int http_status; /* the last HTTP answer's */diff --git a/src/common/mcp_content.c b/src/common/mcp_content.cindex b7bee56..a614e41 100644--- a/src/common/mcp_content.c+++ b/src/common/mcp_content.c@@ -170,6 +170,12 @@ void janas_mcp_take_result(struct janas_mcp *m, const struct janas_json *res)m->result.oom = 0;m->shown.n = 0;m->shown.oom = 0;+ m->raw.n = 0;+ m->raw.oom = 0;+ janas_json_write(&m->raw, res);+ janas_buf_put(&m->raw, "", 1); /* NUL-terminated, not counted */+ if (m->raw.n)+ m->raw.n--;m->result_error = janas_json_get(res, "isError") &&janas_json_get(res, "isError")->type == JANAS_JSON_TRUE;const struct janas_json *content = janas_json_get(res, "content");diff --git a/src/common/mcp_server.c b/src/common/mcp_server.cindex 5d816e1..a19906e 100644--- a/src/common/mcp_server.c+++ b/src/common/mcp_server.c@@ -33,15 +33,51 @@ static void result(struct janas_mcps *s, const struct janas_json *id,janas_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");janas_json_write(&b, id);janas_buf_puts(&b, ",\"result\":{");+ /* the server's own _meta, and the tool's when it gave one (a layout,+ common/template.h): one object, a key may not come twice */+ struct janas_buf all = {0};+ janas_buf_puts(&all, "{");+ janas_buf_put(&all, members, n);+ janas_buf_puts(&all, "}");+ struct janas_json_doc *d = modern && n && !all.oom+ ? janas_json_parse(all.p, all.n, NULL, 0)+ : NULL;+ const struct janas_json *meta =+ d ? janas_json_get(janas_json_root(d), "_meta") : NULL;+ janas_buf_free(&all);if (modern) {janas_buf_puts(&b, "\"resultType\":\"complete\",\"_meta\":{\"io.""modelcontextprotocol/serverInfo\":{\"name\":");janas_json_write_str(&b, s->name, strlen(s->name));janas_buf_puts(&b, ",\"version\":");janas_json_write_str(&b, s->version, strlen(s->version));- janas_buf_puts(&b, n ? "}}," : "}}");+ janas_buf_puts(&b, "}");+ for (const struct janas_json *m =+ meta && meta->type == JANAS_JSON_OBJECT ? meta->child : NULL;+ m; m = m->next) {+ janas_buf_puts(&b, ",");+ janas_json_write_str(&b, m->key, m->key_n);+ janas_buf_puts(&b, ":");+ janas_json_write(&b, m);+ }+ janas_buf_puts(&b, n ? "}," : "}");+ }+ if (meta) { /* the members but the _meta written above */+ int first = 1;+ for (const struct janas_json *m = janas_json_root(d)->child; m;+ m = m->next) {+ if (m == meta)+ continue;+ janas_buf_puts(&b, first ? "" : ",");+ janas_json_write_str(&b, m->key, m->key_n);+ janas_buf_puts(&b, ":");+ janas_json_write(&b, m);+ first = 0;+ }+ } else {+ janas_buf_put(&b, members, n);}- janas_buf_put(&b, members, n);+ janas_json_free(d);janas_buf_puts(&b, "}}\n");send_buf(s, &b);}diff --git a/src/common/template.c b/src/common/template.cnew file mode 100644index 0000000..f83ddbc--- /dev/null+++ b/src/common/template.c@@ -0,0 +1,520 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * template.c - a layout filled with data (see template.h).+ */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/template.h"++#define DEPTH 32++struct frame {+ const struct janas_json *v;+ int index; /* in its list, from 1; 0: not an item */+};++struct ctx {+ const char *t; /* the layout */+ size_t n;+ const char *w; /* the words */+ size_t wn;+ struct frame st[DEPTH];+ int depth;+ struct janas_buf *out;+ char *err;+ size_t err_len;+};++struct tag {+ size_t at, end; /* "{{" and past "}}" */+ char kind; /* 0 a value, '#', '^', '/', '@' */+ const char *name, *filt;+ size_t name_n, filt_n;+};++/* The layout and its words: what follows a line "---". */+static void split(const char *t, size_t n, size_t *layout_n, const char **w,+ size_t *wn)+{+ *layout_n = n;+ *w = t + n;+ *wn = 0;+ for (size_t i = 0; i + 3 <= n; i++) {+ if ((i == 0 || t[i - 1] == '\n') && memcmp(t + i, "---", 3) == 0 &&+ (i + 3 == n || t[i + 3] == '\n')) {+ *layout_n = i > 0 ? i - 1 : 0; /* without its newline */+ size_t from = i + 3 < n ? i + 4 : n;+ *w = t + from;+ *wn = n - from;+ return;+ }+ }+}++static int is_space(char c)+{+ return c == ' ' || c == '\t';+}++/* The tag that begins at i ("{{"): 0, or -1 when it is not ended. */+static int read_tag(const char *t, size_t n, size_t i, struct tag *g)+{+ size_t k = i + 2;+ while (k + 1 < n && !(t[k] == '}' && t[k + 1] == '}'))+ k++;+ if (k + 1 >= n)+ return -1;+ size_t a = i + 2, b = k;+ while (a < b && is_space(t[a]))+ a++;+ while (b > a && is_space(t[b - 1]))+ b--;+ *g = (struct tag){.at = i, .end = k + 2};+ if (a < b && strchr("#^/@", t[a])) {+ g->kind = t[a++];+ while (a < b && is_space(t[a]))+ a++;+ }+ const char *bar = memchr(t + a, '|', b - a);+ g->name = t + a;+ g->name_n = bar ? (size_t)(bar - (t + a)) : b - a;+ while (g->name_n && is_space(g->name[g->name_n - 1]))+ g->name_n--;+ if (bar) {+ g->filt = bar + 1;+ g->filt_n = (size_t)(t + b - g->filt);+ while (g->filt_n && is_space(*g->filt)) {+ g->filt++;+ g->filt_n--;+ }+ }+ return 0;+}++/* The next tag in [i, to): 1, 0 when none, -1 when one is not ended. */+static int next_tag(const char *t, size_t to, size_t i, struct tag *g)+{+ for (; i + 1 < to; i++)+ if (t[i] == '{' && t[i + 1] == '{')+ return read_tag(t, to, i, g) == 0 ? 1 : -1;+ return 0;+}++/* A part's tag alone on its line: where the line begins, and past its end;+ 0 when other text shares the line. */+static int alone(const struct ctx *c, const struct tag *g, size_t *line,+ size_t *past)+{+ if (g->kind != '#' && g->kind != '^' && g->kind != '/')+ return 0;+ size_t a = g->at;+ while (a > 0 && c->t[a - 1] != '\n')+ a--;+ for (size_t k = a; k < g->at; k++)+ if (!is_space(c->t[k]))+ return 0;+ size_t e = g->end;+ while (e < c->n && is_space(c->t[e]))+ e++;+ if (e < c->n && c->t[e] != '\n')+ return 0;+ *line = a;+ *past = e < c->n ? e + 1 : e;+ return 1;+}++static int fail(struct ctx *c, const char *what, const struct tag *g)+{+ snprintf(c->err, c->err_len, "%s: {{%c%.*s}} at byte %zu", what,+ g->kind ? g->kind : ' ', (int)g->name_n, g->name, g->at);+ return -1;+}++/* The tag closing the part opened by g, from i. */+static int find_close(struct ctx *c, const struct tag *g, size_t i, size_t to,+ struct tag *close)+{+ int depth = 0;+ struct tag h;+ int r;+ while ((r = next_tag(c->t, to, i, &h)) == 1) {+ i = h.end;+ if (h.kind == '#' || h.kind == '^')+ depth++;+ else if (h.kind == '/' && depth > 0)+ depth--;+ else if (h.kind == '/') {+ if (h.name_n != g->name_n || memcmp(h.name, g->name, h.name_n))+ return fail(c, "closed by another name", g);+ *close = h;+ return 0;+ }+ }+ return fail(c, r < 0 ? "a tag not ended" : "a part not closed", g);+}++static const struct janas_json *member(const struct janas_json *o,+ const char *k, size_t kn)+{+ char key[128];+ if (!o || o->type != JANAS_JSON_OBJECT || kn >= sizeof key)+ return NULL;+ memcpy(key, k, kn);+ key[kn] = 0;+ return janas_json_get(o, key);+}++/* name in the innermost frame that has its first part, then the rest. */+static const struct janas_json *lookup(const struct ctx *c, const char *name,+ size_t n)+{+ if (n == 1 && name[0] == '.')+ return c->depth ? c->st[c->depth - 1].v : NULL;+ const char *dot = memchr(name, '.', n);+ size_t first = dot ? (size_t)(dot - name) : n;+ const struct janas_json *v = NULL;+ for (int f = c->depth - 1; f >= 0 && !v; f--)+ v = member(c->st[f].v, name, first);+ while (v && dot) {+ const char *s = dot + 1;+ size_t left = n - (size_t)(s - name);+ dot = memchr(s, '.', left);+ v = member(v, s, dot ? (size_t)(dot - s) : left);+ }+ return v;+}++static int truthy(const struct janas_json *v)+{+ if (!v)+ return 0;+ switch (v->type) {+ case JANAS_JSON_NULL:+ case JANAS_JSON_FALSE:+ return 0;+ case JANAS_JSON_NUMBER:+ return janas_json_num(v, 0) != 0;+ case JANAS_JSON_STRING:+ return v->n > 0;+ case JANAS_JSON_ARRAY:+ return v->child != NULL;+ default:+ return 1;+ }+}++/* The word key, from the words: 1 with it in *s, *n. */+static int word(const struct ctx *c, const char *key, size_t kn, const char **s,+ size_t *n)+{+ const char *p = c->w, *end = c->w + c->wn;+ while (p < end) {+ const char *nl = memchr(p, '\n', (size_t)(end - p));+ const char *e = nl ? nl : end;+ const char *eq = memchr(p, '=', (size_t)(e - p));+ if (eq && *p != '#') {+ const char *a = p, *b = eq;+ while (a < b && is_space(*a))+ a++;+ while (b > a && is_space(b[-1]))+ b--;+ if ((size_t)(b - a) == kn && memcmp(a, key, kn) == 0) {+ const char *v = eq + 1, *ve = e;+ while (v < ve && is_space(*v))+ v++;+ while (ve > v && (is_space(ve[-1]) || ve[-1] == '\r'))+ ve--;+ *s = v;+ *n = (size_t)(ve - v);+ return 1;+ }+ }+ p = nl ? nl + 1 : end;+ }+ return 0;+}++/* A word as written: "\n" in it is a new line. */+static void put_word(struct janas_buf *b, const char *s, size_t n)+{+ for (size_t i = 0; i < n; i++) {+ if (s[i] == '\\' && i + 1 < n && s[i + 1] == 'n') {+ janas_buf_put(b, "\n", 1);+ i++;+ } else {+ janas_buf_put(b, s + i, 1);+ }+ }+}++static void put_value(struct ctx *c, const struct tag *g,+ const struct janas_json *v)+{+ if (!v || (v->type != JANAS_JSON_STRING && v->type != JANAS_JSON_NUMBER))+ return;+ if (g->filt_n) {+ char key[192];+ int kn = snprintf(key, sizeof key, "%.*s.%.*s", (int)g->filt_n, g->filt,+ (int)v->n, v->s);+ const char *s;+ size_t n;+ if (kn > 0 && (size_t)kn < sizeof key &&+ word(c, key, (size_t)kn, &s, &n)) {+ put_word(c->out, s, n);+ return;+ }+ }+ if (v->type == JANAS_JSON_NUMBER) {+ const char *d;+ size_t dn = 0;+ int point = word(c, "decimal", 7, &d, &dn) && dn > 0;+ for (size_t i = 0; i < v->n; i++)+ if (point && v->s[i] == '.')+ janas_buf_put(c->out, d, dn);+ else+ janas_buf_put(c->out, v->s + i, 1);+ return;+ }+ janas_buf_put(c->out, v->s, v->n);+}++static int render(struct ctx *c, size_t from, size_t to)+{+ size_t i = from;+ struct tag g;+ int r;+ while ((r = next_tag(c->t, to, i, &g)) == 1) {+ size_t line, past;+ int solo = alone(c, &g, &line, &past) && line >= i;+ janas_buf_put(c->out, c->t + i, (solo ? line : g.at) - i);+ i = solo ? past : g.end;+ if (g.kind == '/')+ return fail(c, "a part closed but not opened", &g);+ if (g.kind == '@') {+ for (int f = c->depth - 1; f >= 0; f--)+ if (c->st[f].index) {+ janas_buf_printf(c->out, "%d", c->st[f].index);+ break;+ }+ continue;+ }+ if (!g.kind) {+ put_value(c, &g, lookup(c, g.name, g.name_n));+ continue;+ }+ struct tag close;+ if (find_close(c, &g, g.end, to, &close) != 0)+ return -1;+ size_t cl, cp;+ int csolo = alone(c, &close, &cl, &cp);+ size_t body = i, body_end = csolo ? cl : close.at;+ if (body_end < body)+ body_end = body;+ i = csolo ? cp : close.end;+ const struct janas_json *v = lookup(c, g.name, g.name_n);+ if (g.kind == '^') {+ if (!truthy(v) && render(c, body, body_end) != 0)+ return -1;+ continue;+ }+ if (!truthy(v))+ continue;+ if (c->depth >= DEPTH)+ return fail(c, "parts too deep", &g);+ if (v->type == JANAS_JSON_ARRAY) {+ int k = 0;+ for (const struct janas_json *it = v->child; it; it = it->next) {+ c->st[c->depth++] = (struct frame){.v = it, .index = ++k};+ int e = render(c, body, body_end);+ c->depth--;+ if (e != 0)+ return -1;+ }+ } else {+ c->st[c->depth++] = (struct frame){.v = v};+ int e = render(c, body, body_end);+ c->depth--;+ if (e != 0)+ return -1;+ }+ }+ if (r < 0) {+ snprintf(c->err, c->err_len, "a tag not ended at byte %zu", i);+ return -1;+ }+ janas_buf_put(c->out, c->t + i, to - i);+ return 0;+}++int janas_tpl_render(const char *tpl, size_t n, const struct janas_json *data,+ struct janas_buf *out, char *err, size_t err_len)+{+ struct ctx c = {.t = tpl, .out = out, .err = err, .err_len = err_len};+ split(tpl, n, &c.n, &c.w, &c.wn);+ c.st[c.depth++] = (struct frame){.v = data};+ if (render(&c, 0, c.n) != 0)+ return -1;+ if (out->oom) {+ snprintf(err, err_len, "out of memory");+ return -1;+ }+ return 0;+}++int janas_tpl_result(struct janas_buf *b, const char *name, const char *data,+ size_t data_n, const char *layout, const char *brief,+ char *err, size_t err_len)+{+ char why[160];+ struct janas_json_doc *d = janas_json_parse(data, data_n, why, sizeof why);+ if (!d) {+ snprintf(err, err_len, "the data: %s", why);+ return -1;+ }+ struct janas_buf text = {0};+ int r = janas_tpl_render(layout, strlen(layout), janas_json_root(d), &text,+ err, err_len);+ janas_json_free(d);+ if (r != 0) {+ janas_buf_free(&text);+ return -1;+ }+ janas_buf_puts(b, "\"content\": [{\"type\": \"text\", \"text\": ");+ janas_json_write_str(b, text.p ? text.p : "", text.n);+ janas_buf_puts(b, "}], \"structuredContent\": ");+ janas_buf_put(b, data, data_n);+ janas_buf_puts(b, ", \"_meta\": {\"dev.prabanta.janas/layout\": "+ "{\"name\": ");+ janas_json_write_str(b, name, strlen(name));+ janas_buf_puts(b, ", \"text\": ");+ janas_json_write_str(b, layout, strlen(layout));+ janas_buf_puts(b, ", \"brief\": ");+ janas_json_write_str(b, brief, strlen(brief));+ janas_buf_puts(b, "}}, \"isError\": false");+ janas_buf_free(&text);+ return 0;+}++/* ---- the shape of a layout ---- */++struct list {+ char **s;+ size_t n, cap;+};++static int list_add(struct list *l, const char *s, size_t n)+{+ if (l->n == l->cap) {+ size_t cap = l->cap ? 2 * l->cap : 32;+ char **g = realloc(l->s, cap * sizeof *g);+ if (!g)+ return -1;+ l->s = g;+ l->cap = cap;+ }+ char *d = malloc(n + 1);+ if (!d)+ return -1;+ memcpy(d, s, n);+ d[n] = 0;+ l->s[l->n++] = d;+ return 0;+}++static void list_free(struct list *l)+{+ for (size_t i = 0; i < l->n; i++)+ free(l->s[i]);+ free(l->s);+}++static int by_text(const void *a, const void *b)+{+ return strcmp(*(char *const *)a, *(char *const *)b);+}++/* Its parts in order, its fields and its words' keys sorted. */+static int shape(const char *t, size_t n, struct list *parts,+ struct list *fields, struct list *keys)+{+ size_t ln, wn;+ const char *w;+ split(t, n, &ln, &w, &wn);+ struct tag g;+ int r;+ size_t i = 0;+ char buf[256];+ while ((r = next_tag(t, ln, i, &g)) == 1) {+ i = g.end;+ int k = snprintf(buf, sizeof buf, "%c%.*s|%.*s", g.kind ? g.kind : '=',+ (int)g.name_n, g.name, (int)g.filt_n,+ g.filt ? g.filt : "");+ if (k < 0 || (size_t)k >= sizeof buf)+ k = sizeof buf - 1;+ if (list_add(g.kind == '#' || g.kind == '^' || g.kind == '/' ? parts+ : fields,+ buf, (size_t)k) != 0)+ return -1;+ }+ if (r < 0)+ return -1;+ const char *p = w, *end = w + wn;+ while (p < end) {+ const char *nl = memchr(p, '\n', (size_t)(end - p));+ const char *e = nl ? nl : end;+ const char *eq = memchr(p, '=', (size_t)(e - p));+ if (eq && *p != '#') {+ const char *a = p, *b = eq;+ while (a < b && is_space(*a))+ a++;+ while (b > a && is_space(b[-1]))+ b--;+ /* the decimal point is the language's: a translation may add+ it */+ if (!((size_t)(b - a) == 7 && memcmp(a, "decimal", 7) == 0) &&+ list_add(keys, a, (size_t)(b - a)) != 0)+ return -1;+ }+ p = nl ? nl + 1 : end;+ }+ qsort(fields->s, fields->n, sizeof *fields->s, by_text);+ qsort(keys->s, keys->n, sizeof *keys->s, by_text);+ return 0;+}++static int same(const struct list *a, const struct list *b, const char *what,+ char *why, size_t why_len)+{+ for (size_t i = 0; i < a->n || i < b->n; i++) {+ const char *x = i < a->n ? a->s[i] : "(none)";+ const char *y = i < b->n ? b->s[i] : "(none)";+ if (strcmp(x, y) != 0) {+ snprintf(why, why_len, "%s differ: %s against %s", what, x, y);+ return 0;+ }+ }+ return 1;+}++int janas_tpl_same_shape(const char *a, size_t an, const char *b, size_t bn,+ char *why, size_t why_len)+{+ struct list pa = {0}, fa = {0}, ka = {0}, pb = {0}, fb = {0}, kb = {0};+ int ok = 0;+ if (shape(a, an, &pa, &fa, &ka) != 0 || shape(b, bn, &pb, &fb, &kb) != 0)+ snprintf(why, why_len, "a layout could not be read");+ else+ ok = same(&pa, &pb, "parts", why, why_len) &&+ same(&fa, &fb, "fields", why, why_len) &&+ same(&ka, &kb, "words", why, why_len);+ list_free(&pa);+ list_free(&fa);+ list_free(&ka);+ list_free(&pb);+ list_free(&fb);+ list_free(&kb);+ return ok;+}diff --git a/src/common/template.h b/src/common/template.hnew file mode 100644index 0000000..b5e45b4--- /dev/null+++ b/src/common/template.h@@ -0,0 +1,57 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * template.h - a layout filled with data (template.c), for the services'+ * answers: the service gives the data and an English layout; a client+ * shows the user the layout filled, in the user's language, and spares+ * the model reading and writing it.+ *+ * A layout is text with fields, and after a line "---" its words, one a+ * line, "key = text":+ *+ * {{name}} the value of name in the data ("a.b": b in a)+ * {{name|w}} the word "w.<value>" when the words have it, else+ * the value (a compass point, a weather code...)+ * {{#name}}...{{/name}} the part for each item of a list, or once when+ * the value is there (not null, false, 0 or empty)+ * {{^name}}...{{/name}} the part when it is not+ * {{@n}} the item's number in its list, from 1+ * {{.}} the item itself (a list of texts)+ *+ * A line holding only a part's tag is left out whole. Numbers are written+ * as the data has them, with the word "decimal" as their point when the+ * words give one ("decimal = ,"). A translation changes the text and the+ * words, never the fields: janas_tpl_same_shape checks it (a "decimal" may+ * be added).+ */+#ifndef JANAS_COMMON_TEMPLATE_H+#define JANAS_COMMON_TEMPLATE_H++#include <stddef.h>++#include "llm/json.h"++/* The layout tpl (n bytes) filled with data (an object) into out. 0, or -1+ with the reason in err: a part not closed, a tag not ended. */+int janas_tpl_render(const char *tpl, size_t n, const struct janas_json *data,+ struct janas_buf *out, char *err, size_t err_len);++/* 1 when b has the fields, parts and words of a (a translation of it), 0+ with the first difference in why. */+int janas_tpl_same_shape(const char *a, size_t an, const char *b, size_t bn,+ char *why, size_t why_len);++/*+ * A tools/call result made of data and a layout, the members into b: the+ * layout filled in English as its text, for the clients that read text;+ * the data as structuredContent; and in _meta, under+ * "dev.prabanta.janas/layout", its name, the layout and the brief - a+ * layout for the model, filled by a client that shows the user the layout+ * in the user's language (janas-chat) and gives the model only the brief.+ * 0, or -1 with the reason in err when the layout could not be filled.+ */+int janas_tpl_result(struct janas_buf *b, const char *name, const char *data,+ size_t data_n, const char *layout, const char *brief,+ char *err, size_t err_len);++#endifdiff --git a/src/flights/flights.h b/src/flights/flights.hindex 4a6a9f4..86aeb07 100644--- a/src/flights/flights.h+++ b/src/flights/flights.h@@ -98,6 +98,13 @@ int fl_sched_parse(const char *text, size_t len, struct fl_sched **v, size_t *n,void fl_sched_free(void);+/* ---- layouts.c ---- */++/* flights_over's layout and brief (common/template.h). */+extern const char FL_OVER_LAYOUT[], FL_OVER_BRIEF[];+/* flights_nearby's */+extern const char FL_NEAR_LAYOUT[], FL_NEAR_BRIEF[];+/* ---- tools.c ---- */void fl_tools_list(void *ctx, struct janas_buf *b);diff --git a/src/flights/layouts.c b/src/flights/layouts.cnew file mode 100644index 0000000..538c6b6--- /dev/null+++ b/src/flights/layouts.c@@ -0,0 +1,128 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * layouts.c - the layouts of janas-flights' answers (see flights.h and+ * common/template.h): the text the user reads, filled with the data in+ * English here and in the user's language by a client that translates the+ * layout once (janas-chat), and the brief, all the model reads of it.+ */+#include "flights.h"++/* The words every layout of aircraft shares: the compass, the codes of an+ emergency. */+#define WORDS \+ "dir.N = N\n" \+ "dir.NNE = NNE\n" \+ "dir.NE = NE\n" \+ "dir.ENE = ENE\n" \+ "dir.E = E\n" \+ "dir.ESE = ESE\n" \+ "dir.SE = SE\n" \+ "dir.SSE = SSE\n" \+ "dir.S = S\n" \+ "dir.SSW = SSW\n" \+ "dir.SW = SW\n" \+ "dir.WSW = WSW\n" \+ "dir.W = W\n" \+ "dir.WNW = WNW\n" \+ "dir.NW = NW\n" \+ "dir.NNW = NNW\n" \+ "squawk.7500 = 7500, unlawful interference (hijacking)\n" \+ "squawk.7600 = 7600, radio failure\n" \+ "squawk.7700 = 7700, general emergency\n" \+ "ground.stationary = stationary\n" \+ "ground.taxiing = taxiing\n" \+ "ground.runway = on the runway (taking off or just landed)\n"++/* One aircraft, as an item of "aircraft". */+#define AIRCRAFT "{{@n}}. " AIRCRAFT_BODY+#define AIRCRAFT_BODY \+ "{{#callsign}}{{callsign}}{{/callsign}}{{^callsign}}no callsign " \+ "(transponder {{hex}}){{/callsign}}{{#reg}} ({{reg}}{{#type}}, " \+ "{{type}}{{/type}}){{/reg}}{{^reg}}{{#type}} ({{type}}){{/type}}" \+ "{{/reg}}: {{#ground}}on the ground{{#airport}} at {{airport}}" \+ "{{/airport}}{{#on_ground}}, {{on_ground|ground}}{{/on_ground}}" \+ "{{/ground}}{{^ground}}{{#fl}}FL{{fl}}" \+ "{{/fl}}{{#ft}}{{ft}} ft{{/ft}}{{^fl}}{{^ft}}altitude not reported" \+ "{{/ft}}{{/fl}}{{#climbing}} climbing{{/climbing}}{{#descending}} " \+ "descending{{/descending}}{{/ground}}{{#kts}}, {{kts}} kts{{/kts}}" \+ "{{#heading}}, towards {{heading|dir}}{{/heading}}; " \+ "{{#where.sea}}over the {{where.sea}}{{#where.and}}, between " \+ "{{where.region}} and {{where.and}}{{/where.and}}{{/where.sea}}" \+ "{{^where.sea}}over {{where.region}}{{/where.sea}}; {{#where.km}}" \+ "{{where.km}} km {{where.dir|dir}} of {{where.city}}{{/where.km}}" \+ "{{^where.km}}over {{where.city}}{{/where.km}}{{#emergency}}; " \+ "EMERGENCY: transponder code {{emergency|squawk}}{{/emergency}}" \+ "{{#route}}; route on record: {{route.from}} ({{route.from_code}}) to " \+ "{{route.to}} ({{route.to_code}}){{#route.airline}}, {{route.airline}}" \+ "{{/route.airline}}{{/route}}"++/* The sources, at the foot. */+#define SOURCES \+ "Sources: live positions from {{net}} ({{#odbl}}data under the ODbL, " \+ "{{/odbl}}{{net_url}}){{#routes}}; routes from adsbdb.com{{/routes}}"++const char FL_OVER_LAYOUT[] =+ "As of {{time}} UTC: {{count}} aircraft over the {{sea}} ({{airborne}} "+ "in the air){{#failed}}; {{failed}} of the {{parts}} parts of the sea "+ "could not be asked, so there may be more{{/failed}}{{#listed}}; "+ "{{listed}} of them listed{{/listed}}{{#count}}, from west to "+ "east:{{/count}}{{^count}}.{{/count}}\n"+ "{{#aircraft}}\n" AIRCRAFT "\n"+ "{{/aircraft}}\n"+ "{{#routes}}\n"+ "\nRoutes on record come from the community (adsbdb), not from "+ "schedules: usually right, sometimes not; those that do not fit the "+ "position are left out.\n"+ "{{/routes}}\n"+ "Only aircraft with a transponder heard by the community's receivers "+ "are counted: nearly all airliners, not every small or military "+ "aircraft.\n\n" SOURCES "; sea boundaries from Natural Earth.\n"+ "---\n" WORDS;++const char FL_OVER_BRIEF[] =+ "{{count}} aircraft over the {{sea}} at {{time}} UTC ({{airborne}} in "+ "the air){{#failed}}; {{failed}} of {{parts}} parts of the sea not "+ "asked, so there may be more{{/failed}}.{{#emergencies}} "+ "{{emergencies}} of them squawk an emergency: say so.{{/emergencies}} "+ "The list, aircraft by aircraft, is shown to the user as it is: do not "+ "repeat it; answer in a line or two from these figures, in the user's "+ "language.";++/* Where the user is, as the locator says how it knows. */+#define HOW_WORDS \+ "how.as set on the computer (JANAS_LOCATION) = as set on the computer " \+ "(JANAS_LOCATION)\n" \+ "how.estimated from the internet connection (GeoJS) = estimated from " \+ "the internet connection (GeoJS)\n" \+ "how.estimated from the internet connection (ipwho.is) = estimated from " \+ "the internet connection (ipwho.is)\n" \+ "how.a rough guess, the city of the computer's time zone = a rough " \+ "guess, the city of the computer's time zone\n"++const char FL_NEAR_LAYOUT[] =+ "As of {{time}} UTC.\n"+ "{{#point}}\n"+ "The point is {{#point.sea}}over the {{point.sea}}{{#point.and}}, "+ "between {{point.region}} and {{point.and}}{{/point.and}}{{/point.sea}}"+ "{{^point.sea}}over {{point.region}}{{/point.sea}}; {{#point.km}}"+ "{{point.km}} km {{point.dir|dir}} of {{point.city}}{{/point.km}}"+ "{{^point.km}}over {{point.city}}{{/point.km}}.\n"+ "{{/point}}\n"+ "{{count}} aircraft within {{radius}} km of {{place}}{{#how}} (where "+ "the user is, {{how|how}}){{/how}}{{#listed}}; the nearest {{listed}}"+ "{{/listed}}{{#count}}:{{/count}}{{^count}}.{{/count}}\n"+ "{{#aircraft}}\n"+ "{{@n}}. {{dist_km}} km {{dist_dir|dir}}: " AIRCRAFT_BODY "\n"+ "{{/aircraft}}\n"+ "\n" SOURCES ".{{#no_schedules}} No schedules (the server has no "+ "AviationStack key): scheduled and official estimated times are not "+ "known to this tool.{{/no_schedules}}\n"+ "---\n" WORDS HOW_WORDS;++const char FL_NEAR_BRIEF[] =+ "{{count}} aircraft within {{radius}} km of {{place}} at {{time}} UTC"+ "{{#how}}; the place is where the user is, {{how}}: say which place, "+ "and that it may be off{{/how}}. The list, aircraft by aircraft, is "+ "shown to the user as it is: do not repeat it; answer in a line or two "+ "from these figures, in the user's language.";diff --git a/src/flights/tools.c b/src/flights/tools.cindex d5d0740..d4dd116 100644--- a/src/flights/tools.c+++ b/src/flights/tools.c@@ -25,6 +25,7 @@#include "common/mcp_server.h"#include "flights.h"#include "common/geo.h"+#include "common/template.h"#define DEG(x) ((x) * 1e-5)#define KM_PER_NM 1.852@@ -883,49 +884,83 @@ static int flights_between(const struct janas_json *args, struct janas_buf *b)/* ---- flights_over ---- */-/* One aircraft on one line: callsign, aircraft, altitude, speed, heading,- where, and its route on record when it fits. */-static void ac_line(const struct fl_ac *a, const struct fl_route *r,+/* "key": "value", as JSON */+static void jstr(struct janas_buf *b, const char *key, const char *v)+{+ janas_buf_printf(b, "\"%s\": ", key);+ janas_json_write_str(b, v, strlen(v));+}++/* One aircraft as an item of a layout's "aircraft" (layouts.c): what+ ac_line says, as data. */+static void ac_json(const struct fl_ac *a, const struct fl_route *r,int have_route, struct janas_buf *b){- if (a->flight[0])- janas_buf_puts(b, a->flight);- else- janas_buf_printf(b, "no callsign (transponder %s)", a->hex);- if (a->reg[0] || a->type[0])- janas_buf_printf(b, " (%s%s%s)", a->reg,- a->reg[0] && a->type[0] ? ", " : "", a->type);- janas_buf_puts(b, ": ");- if (a->ground)- janas_buf_puts(b, "on the ground");- else if (a->has_alt && a->alt >= 10000)- janas_buf_printf(b, "FL%03ld", lround(a->alt / 100));- else if (a->has_alt) {- thousands(b, a->alt);- janas_buf_puts(b, " ft");- } else- janas_buf_puts(b, "altitude not reported");+ janas_buf_puts(b, "{");+ jstr(b, "hex", a->hex);+ if (a->flight[0]) {+ janas_buf_puts(b, ", ");+ jstr(b, "callsign", a->flight);+ }+ if (a->reg[0]) {+ janas_buf_puts(b, ", ");+ jstr(b, "reg", a->reg);+ }+ if (a->type[0]) {+ janas_buf_puts(b, ", ");+ jstr(b, "type", a->type);+ }+ if (a->ground) {+ janas_buf_puts(b, ", \"ground\": true");+ double km = 1e30;+ const struct geo_airport *ap =+ a->has_pos ? geo_airport_near(a->lat, a->lon, &km) : NULL;+ if (ap && km < 6) {+ char at[160];+ snprintf(at, sizeof at, "%s (%s)", ap->name, ap->iata);+ janas_buf_puts(b, ", ");+ jstr(b, "airport", at);+ }+ if (a->gs >= 0)+ janas_buf_printf(b, ", \"on_ground\": \"%s\"",+ a->gs < 3 ? "stationary"+ : a->gs < 40 ? "taxiing"+ : "runway");+ } else if (a->has_alt && a->alt >= 10000)+ janas_buf_printf(b, ", \"fl\": \"%03ld\"", lround(a->alt / 100));+ else if (a->has_alt)+ janas_buf_printf(b, ", \"ft\": %ld", lround(a->alt));if (!a->ground && a->has_alt && fabs(a->rate) > 400)- janas_buf_puts(b, a->rate > 0 ? " climbing" : " descending");+ janas_buf_puts(b, a->rate > 0 ? ", \"climbing\": true"+ : ", \"descending\": true");if (a->gs >= 0)- janas_buf_printf(b, ", %.0f kts", a->gs);- if (a->track >= 0)- janas_buf_printf(b, ", heading %s", geo_compass(a->track));- janas_buf_puts(b, "; ");- geo_describe(a->lat, a->lon, b);- const char *sq = squawk_meaning(a->squawk);- if (sq)- janas_buf_printf(b, "; EMERGENCY: transponder code %s", sq);+ janas_buf_printf(b, ", \"kts\": %.0f", a->gs);+ if (a->track >= 0) {+ janas_buf_puts(b, ", ");+ jstr(b, "heading", geo_compass(a->track));+ }+ janas_buf_puts(b, ", \"where\": ");+ geo_describe_json(a->lat, a->lon, b);+ if (squawk_meaning(a->squawk)) {+ janas_buf_puts(b, ", ");+ jstr(b, "emergency", a->squawk);+ }if (have_route && route_fits(a, r)) {- janas_buf_puts(b, "; route on record: ");- janas_buf_printf(b, "%s (%s) to %s (%s)",- r->from.city[0] ? r->from.city : r->from.name,- r->from.iata[0] ? r->from.iata : r->from.icao,- r->to.city[0] ? r->to.city : r->to.name,- r->to.iata[0] ? r->to.iata : r->to.icao);- if (r->airline[0])- janas_buf_printf(b, ", %s", r->airline);+ janas_buf_puts(b, ", \"route\": {");+ jstr(b, "from", r->from.city[0] ? r->from.city : r->from.name);+ janas_buf_puts(b, ", ");+ jstr(b, "from_code", r->from.iata[0] ? r->from.iata : r->from.icao);+ janas_buf_puts(b, ", ");+ jstr(b, "to", r->to.city[0] ? r->to.city : r->to.name);+ janas_buf_puts(b, ", ");+ jstr(b, "to_code", r->to.iata[0] ? r->to.iata : r->to.icao);+ if (r->airline[0]) {+ janas_buf_puts(b, ", ");+ jstr(b, "airline", r->airline);+ }+ janas_buf_puts(b, "}");}+ janas_buf_puts(b, "}");}static int by_lon(const void *x, const void *y)@@ -1029,52 +1064,57 @@ static int flights_over(const struct janas_json *args, struct janas_buf *b)}if (n_all)qsort(all, n_all, sizeof(*all), by_lon);- struct janas_buf out = {0};- now_text(&out);+ /* the data, for the layout (layouts.c) */+ struct janas_buf d = {0};+ char utc[16];+ hhmm(time(NULL), "UTC", utc, sizeof utc);size_t airborne = 0;- for (size_t i = 0; i < n_all; i++)+ int emergencies = 0;+ for (size_t i = 0; i < n_all; i++) {airborne += !all[i].ground;- janas_buf_printf(&out, "%zu aircraft over the %s now (%zu in the air)",- n_all, area.name, airborne);+ emergencies += squawk_meaning(all[i].squawk) != NULL;+ }+ janas_buf_printf(&d, "{\"time\": \"%s\", ", utc);+ jstr(&d, "sea", area.name);+ janas_buf_printf(&d, ", \"count\": %zu, \"airborne\": %zu", n_all,+ airborne);if (failed)- janas_buf_printf(&out,- "; %d of the %d parts of the sea could not be asked, "- "so there may be more",- failed, nx * ny);+ janas_buf_printf(&d, ", \"failed\": %d, \"parts\": %d", failed,+ nx * ny);if (n_all > (size_t)limit)- janas_buf_printf(&out, "; %d of them listed", limit);- janas_buf_puts(&out, n_all ? ", from west to east:\n" : ".");+ janas_buf_printf(&d, ", \"listed\": %d", limit);+ if (emergencies)+ janas_buf_printf(&d, ", \"emergencies\": %d", emergencies);+ janas_buf_puts(&d, ", \"aircraft\": [");int routes = 0;for (size_t i = 0; i < n_all && i < (size_t)limit; i++) {struct fl_route r = {0};int have = 0;if (all[i].flight[0] && i < ROUTES_OVER) {have = fl_route(all[i].flight, &r) == 1;- routes |= have;+ routes |= have && route_fits(&all[i], &r);}- janas_buf_printf(&out, "\n%zu. ", i + 1);- ac_line(&all[i], &r, have, &out);+ janas_buf_puts(&d, i ? ", " : "");+ ac_json(&all[i], &r, have, &d);}- if (routes)- janas_buf_puts(&out, "\n\nRoutes on record come from the community "- "(adsbdb), not from schedules: usually right, "- "sometimes not; those that do not fit the "- "position are left out.");- janas_buf_puts(&out, "\nOnly aircraft with a transponder heard by the "- "community's receivers are counted: nearly all "- "airliners, not every small or military aircraft.");+ janas_buf_puts(&d, "], ");/* open data only: no schedule is asked for a list */- janas_buf_printf(&out,- "\n\nSources: live positions from %s (%s)%s; sea "- "boundaries from Natural Earth.",- net,- strcmp(net, "adsb.lol") == 0- ? "data under the ODbL, https://adsb.lol"- : "https://adsb.fi",- routes ? "; routes from adsbdb.com" : "");+ jstr(&d, "net", net);+ janas_buf_puts(&d, ", ");+ jstr(&d, "net_url",+ strcmp(net, "adsb.lol") == 0 ? "https://adsb.lol" : "https://adsb.fi");+ janas_buf_printf(&d, "%s%s}",+ strcmp(net, "adsb.lol") == 0 ? ", \"odbl\": true" : "",+ routes ? ", \"routes\": true" : "");free(all);- janas_mcps_text_result(b, out.p ? out.p : "", out.n, 0);- janas_buf_free(&out);+ if (d.oom || janas_tpl_result(b, "flights_over", d.p, d.n, FL_OVER_LAYOUT,+ FL_OVER_BRIEF, err, sizeof err) != 0) {+ char m[480];+ snprintf(m, sizeof m, "The answer could not be written: %s",+ d.oom ? "out of memory" : err);+ janas_mcps_text_result(b, m, strlen(m), 1);+ }+ janas_buf_free(&d);return 0;}@@ -1106,7 +1146,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[256] = "";+ char where[256] = "", here[128] = "", how[128] = "";if (place && *place) {const struct geo_airport *ap = geo_airport_find(place);const struct geo_city *c = ap ? NULL : geo_city_find(place);@@ -1142,6 +1182,9 @@ static int flights_nearby(const struct janas_json *args, struct janas_buf *b)lon = w.lon;snprintf(where, sizeof where, "%s (where the user is, %s)",w.city[0] ? w.city : "the user's position", w.how);+ snprintf(here, sizeof here, "%s",+ w.city[0] ? w.city : "the user's position");+ snprintf(how, sizeof how, "%s", w.how);place = where; /* named: no point to put into words */} else {snprintf(where, sizeof where, "%.3f, %.3f", lat, lon);@@ -1166,38 +1209,61 @@ static int flights_nearby(const struct janas_json *args, struct janas_buf *b)}if (m)qsort(v, m, sizeof(*v), by_km);- struct janas_buf out = {0};- now_text(&out);- if (!(place && *place)) { /* a point: where it is, in words */- janas_buf_printf(&out, "The point %s is ", where);- geo_describe(lat, lon, &out);- janas_buf_puts(&out, ".\n");+ /* the data, for the layout (layouts.c) */+ struct janas_buf d = {0};+ char utc[16];+ hhmm(time(NULL), "UTC", utc, sizeof utc);+ janas_buf_printf(&d, "{\"time\": \"%s\", ", utc);+ jstr(&d, "place", here[0] ? here : where);+ if (how[0]) {+ janas_buf_puts(&d, ", ");+ jstr(&d, "how", how);+ }+ if (!(place && *place)) { /* a point: where it is */+ janas_buf_puts(&d, ", \"point\": ");+ geo_describe_json(lat, lon, &d);}- janas_buf_printf(&out, "%zu aircraft within %.0f km of %s", m, radius,- where);+ janas_buf_printf(&d, ", \"radius\": %.0f, \"count\": %zu", radius, m);if (m > (size_t)limit)- janas_buf_printf(&out, "; the nearest %d", limit);- janas_buf_puts(&out, m ? ":\n" : ".");+ janas_buf_printf(&d, ", \"listed\": %d", limit);+ janas_buf_puts(&d, ", \"aircraft\": [");int routes = 0;for (size_t i = 0; i < m && i < (size_t)limit; i++) {const struct fl_ac *a = v[i].a;- janas_buf_printf(&out, "\n%zu. %.0f km %s of %s\n", i + 1, v[i].km,- geo_compass(geo_bearing(lat, lon, a->lat, a->lon)),- where);struct fl_route r = {0};int have = 0;if (a->flight[0] && i < ROUTES_ASKED) {have = fl_route(a->flight, &r) == 1;- routes |= have;+ routes |= have && route_fits(a, &r);}- ac_text(a, &r, have, &out);- janas_buf_puts(&out, "\n");+ janas_buf_puts(&d, i ? ", " : "");+ ac_json(a, &r, have, &d);+ /* how far and which way from the place, into the item */+ d.n--; /* its "}" */+ janas_buf_printf(&d, ", \"dist_km\": %.0f, ", v[i].km);+ jstr(&d, "dist_dir",+ geo_compass(geo_bearing(lat, lon, a->lat, a->lon)));+ janas_buf_puts(&d, "}");}- sources(&out, net, routes, 0);+ janas_buf_puts(&d, "], ");+ jstr(&d, "net", net);+ janas_buf_puts(&d, ", ");+ jstr(&d, "net_url",+ strcmp(net, "adsb.lol") == 0 ? "https://adsb.lol" : "https://adsb.fi");+ janas_buf_printf(&d, "%s%s%s}",+ strcmp(net, "adsb.lol") == 0 ? ", \"odbl\": true" : "",+ routes ? ", \"routes\": true" : "",+ fl_sched_have() ? "" : ", \"no_schedules\": true");free(v);free(ac);- janas_mcps_text_result(b, out.p ? out.p : "", out.n, 0);- janas_buf_free(&out);+ if (d.oom || janas_tpl_result(b, "flights_nearby", d.p, d.n, FL_NEAR_LAYOUT,+ FL_NEAR_BRIEF, err, sizeof err) != 0) {+ char msg[480];+ snprintf(msg, sizeof msg, "The answer could not be written: %s",+ d.oom ? "out of memory" : err);+ janas_mcps_text_result(b, msg, strlen(msg), 1);+ }+ janas_buf_free(&d);return 0;}diff --git a/src/llm/api_aside.c b/src/llm/api_aside.cnew file mode 100644index 0000000..5fe0575--- /dev/null+++ b/src/llm/api_aside.c@@ -0,0 +1,113 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * api_aside.c - a request on the side (janas_llm_chat_aside in+ * include/janas/llm.h): the conversation saved, a system message and a+ * user message answered greedily, the conversation put back as it was.+ * janas-chat asks the model this way to translate a service's layout once,+ * in the middle of a conversation it must not disturb.+ */+#include <stdlib.h>+#include <string.h>++#include "llm/chat.h"++/* A token the reply is not made of: the markers of the format. */+static int marker(const janas_llm *llm, int32_t t)+{+ return t == llm->im_start || t == llm->im_end || t == llm->think_open ||+ t == llm->think_close || t == llm->bos;+}++static int is_stop(const janas_llm *llm, int32_t t)+{+ if (t == llm->im_end || t == llm->eos_id)+ return 1;+ for (int i = 0; i < llm->n_stop; i++)+ if (t == llm->stop[i])+ return 1;+ return 0;+}++int32_t janas_llm_chat_aside(janas_llm_chat *c, const char *system,+ int32_t system_len, const char *text,+ int32_t text_len, int32_t max_tokens, char *buf,+ int32_t cap, int32_t *len)+{+ if (len)+ *len = 0;+ if (!c || !text || max_tokens <= 0 || (cap > 0 && !buf))+ return janas_api_fail(JANAS_LLM_EINVAL, "invalid argument");+ if (c->replying && !c->ended)+ return janas_api_fail(JANAS_LLM_EBUSY,+ "a reply is being read: ask aside after it");+ const janas_llm *llm = c->llm;+ struct janas_llm_saved *sv = janas_llm_session_save(c->s);+ if (!sv)+ return janas_api_fail(JANAS_LLM_ENOMEM, "out of memory");+ /* what building a message changes, kept to be put back */+ int thinking = c->p.thinking, in_think = c->in_think, in_turn = c->in_turn,+ chan = c->chan_label;+ c->p.thinking = 0; /* no reasoning: an answer, at once */+ c->in_turn = 0;+ c->n_ids = c->n_text = 0;+ int err = janas_api_begin_sequence(c);+ if (system)+ err |= janas_api_add_message(c, "system", system,+ janas_api_text_len(system, system_len));+ err |= janas_api_add_message(c, "user", text,+ janas_api_text_len(text, text_len));+ err |= janas_api_start_reply(c);+ struct janas_gen_options o;+ int32_t rc = JANAS_LLM_OK;+ struct janas_buf out = {0};+ if (err) {+ rc = janas_api_fail(JANAS_LLM_ENOMEM, "out of memory");+ } else if (janas_api_options(c, &o) != JANAS_LLM_OK) {+ rc = JANAS_LLM_EINVAL;+ } else {+ o.temperature = 0; /* greedy: the same answer every time */+ o.presence_penalty = o.frequency_penalty = 0;+ o.logprobs = o.top_logprobs = 0;+ janas_llm_session_filter(c->s, NULL);+ janas_llm_session_reset(c->s);+ if (janas_llm_session_set_options(c->s, &o) != 0 ||+ janas_llm_session_append(c->s, c->ids, (uint32_t)c->n_ids) != 0)+ rc = janas_api_fail(JANAS_LLM_EFULL,+ "the request does not fit in the context");+ for (int32_t k = 0; rc == JANAS_LLM_OK && k < max_tokens; k++) {+ int32_t t;+ int r = janas_llm_session_next(c->s, &t);+ if (r != 0) {+ if (r < 0)+ rc = janas_api_fail(JANAS_LLM_EFAIL, "the pass failed");+ break;+ }+ if (is_stop(llm, t))+ break;+ if (marker(llm, t))+ continue;+ char piece[256];+ size_t n = janas_tokenizer_decode(llm->tok, t, piece, sizeof piece);+ janas_buf_put(&out, piece, n < sizeof piece ? n : sizeof piece);+ }+ }+ /* the conversation back, as it was */+ if (janas_llm_session_restore(c->s, sv) != 0 && rc == JANAS_LLM_OK)+ rc = janas_api_fail(JANAS_LLM_ENOMEM,+ "the conversation could not be put back");+ janas_llm_saved_free(sv);+ c->p.thinking = thinking;+ c->in_think = in_think;+ c->in_turn = in_turn;+ c->chan_label = chan;+ c->n_ids = c->n_text = 0;+ if (janas_api_options(c, &o) == JANAS_LLM_OK)+ janas_llm_session_set_options(c->s, &o);+ if (rc == JANAS_LLM_OK && out.oom)+ rc = janas_api_fail(JANAS_LLM_ENOMEM, "out of memory");+ if (rc == JANAS_LLM_OK)+ rc = janas_api_copy_out(out.p ? out.p : "", out.n, buf, cap, len);+ janas_buf_free(&out);+ return rc;+}diff --git a/src/llm/api_chat.c b/src/llm/api_chat.cindex 91b05c2..0148f03 100644--- a/src/llm/api_chat.c+++ b/src/llm/api_chat.c@@ -71,6 +71,11 @@ static int32_t gen_options(const janas_llm_chat *c, struct janas_gen_options *o)return JANAS_LLM_OK;}+int32_t janas_api_options(const janas_llm_chat *c, struct janas_gen_options *o)+{+ return gen_options(c, o);+}+static int32_t take_params(janas_llm_chat *c,const struct janas_llm_chat_params *pp){diff --git a/src/llm/chat.h b/src/llm/chat.hindex c967e5e..56dffd6 100644--- a/src/llm/chat.h+++ b/src/llm/chat.h@@ -249,6 +249,8 @@ int janas_api_begin_reply(janas_llm_chat *c, uint32_t reply_at, uint32_t total,uint32_t cached);/* Building a prompt begins (its time is prepare_seconds). */void janas_api_prep_start(janas_llm_chat *c);+/* The session's options from the chat's parameters. */+int32_t janas_api_options(const janas_llm_chat *c, struct janas_gen_options *o);/* What janas_llm_chat_prepare read, dropped: the system message or thetools change. */void janas_api_unprepare(janas_llm_chat *c);diff --git a/src/weather/layouts.c b/src/weather/layouts.cnew file mode 100644index 0000000..4dc414c--- /dev/null+++ b/src/weather/layouts.c@@ -0,0 +1,344 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * layouts.c - the layouts of janas-weather's answers (see weather.h and+ * common/template.h): the report the user reads, filled in English here+ * and in the user's language by a client that translates the layout once+ * (janas-chat), and the brief, the figures the model reads to answer.+ */+#include "weather.h"++/* The sky, as the WMO codes Open-Meteo gives (words.c). */+#define WMO_WORDS \+ "wmo.0 = clear sky\n" \+ "wmo.1 = mainly clear\n" \+ "wmo.2 = partly cloudy\n" \+ "wmo.3 = overcast\n" \+ "wmo.45 = fog\n" \+ "wmo.48 = fog depositing rime\n" \+ "wmo.51 = light drizzle\n" \+ "wmo.53 = drizzle\n" \+ "wmo.55 = dense drizzle\n" \+ "wmo.56 = light freezing drizzle\n" \+ "wmo.57 = dense freezing drizzle\n" \+ "wmo.61 = light rain\n" \+ "wmo.63 = rain\n" \+ "wmo.65 = heavy rain\n" \+ "wmo.66 = light freezing rain\n" \+ "wmo.67 = heavy freezing rain\n" \+ "wmo.71 = light snow\n" \+ "wmo.73 = snow\n" \+ "wmo.75 = heavy snow\n" \+ "wmo.77 = snow grains\n" \+ "wmo.80 = light rain showers\n" \+ "wmo.81 = rain showers\n" \+ "wmo.82 = violent rain showers\n" \+ "wmo.85 = light snow showers\n" \+ "wmo.86 = heavy snow showers\n" \+ "wmo.95 = thunderstorm\n" \+ "wmo.96 = thunderstorm with light hail\n" \+ "wmo.99 = thunderstorm with heavy hail\n"++/* The wind's force, and where it blows from. */+#define WIND_WORDS \+ "bft.0 = calm\n" \+ "bft.1 = light air\n" \+ "bft.2 = light breeze\n" \+ "bft.3 = gentle breeze\n" \+ "bft.4 = moderate breeze\n" \+ "bft.5 = fresh breeze\n" \+ "bft.6 = strong breeze\n" \+ "bft.7 = near gale\n" \+ "bft.8 = gale\n" \+ "bft.9 = strong gale\n" \+ "bft.10 = storm\n" \+ "bft.11 = violent storm\n" \+ "bft.12 = hurricane force\n" \+ "from.N = from the north\n" \+ "from.NNE = from the north-north-east\n" \+ "from.NE = from the north-east\n" \+ "from.ENE = from the east-north-east\n" \+ "from.E = from the east\n" \+ "from.ESE = from the east-south-east\n" \+ "from.SE = from the south-east\n" \+ "from.SSE = from the south-south-east\n" \+ "from.S = from the south\n" \+ "from.SSW = from the south-south-west\n" \+ "from.SW = from the south-west\n" \+ "from.WSW = from the west-south-west\n" \+ "from.W = from the west\n" \+ "from.WNW = from the west-north-west\n" \+ "from.NW = from the north-west\n" \+ "from.NNW = from the north-north-west\n"++/* The compass, for where a station is. */+#define DIR_WORDS \+ "dir.N = N\n" \+ "dir.NNE = NNE\n" \+ "dir.NE = NE\n" \+ "dir.ENE = ENE\n" \+ "dir.E = E\n" \+ "dir.ESE = ESE\n" \+ "dir.SE = SE\n" \+ "dir.SSE = SSE\n" \+ "dir.S = S\n" \+ "dir.SSW = SSW\n" \+ "dir.SW = SW\n" \+ "dir.WSW = WSW\n" \+ "dir.W = W\n" \+ "dir.WNW = WNW\n" \+ "dir.NW = NW\n" \+ "dir.NNW = NNW\n"++/* A station's report: the weather as coded, the clouds. */+#define STATION_WORDS \+ "wx.- = light\n" \+ "wx.+ = heavy\n" \+ "wx.TS = thunderstorm\n" \+ "wx.SH = showers of\n" \+ "wx.FZ = freezing\n" \+ "wx.RA = rain\n" \+ "wx.DZ = drizzle\n" \+ "wx.SN = snow\n" \+ "wx.GR = hail\n" \+ "wx.GS = small hail\n" \+ "wx.FG = fog\n" \+ "wx.BR = mist\n" \+ "wx.HZ = haze\n" \+ "wx.VC = nearby\n" \+ "cover.FEW = few clouds\n" \+ "cover.SCT = scattered clouds\n" \+ "cover.BKN = broken clouds\n" \+ "cover.OVC = overcast\n" \+ "cover.VV = sky obscured\n" \+ "cover.CLR = clear\n" \+ "cover.SKC = clear\n" \+ "cover.NSC = no significant cloud\n" \+ "cover.NCD = no cloud detected\n" \+ "cover.CAVOK = no significant cloud\n"++/* The days of the week (0 Sunday) and the months. */+#define DATE_WORDS \+ "wd.0 = Sunday\n" \+ "wd.1 = Monday\n" \+ "wd.2 = Tuesday\n" \+ "wd.3 = Wednesday\n" \+ "wd.4 = Thursday\n" \+ "wd.5 = Friday\n" \+ "wd.6 = Saturday\n" \+ "mon.1 = January\n" \+ "mon.2 = February\n" \+ "mon.3 = March\n" \+ "mon.4 = April\n" \+ "mon.5 = May\n" \+ "mon.6 = June\n" \+ "mon.7 = July\n" \+ "mon.8 = August\n" \+ "mon.9 = September\n" \+ "mon.10 = October\n" \+ "mon.11 = November\n" \+ "mon.12 = December\n"++/* Where the user is, as the locator says how it knows it. */+#define HOW_WORDS \+ "how.as set on the computer (JANAS_LOCATION) = as set on the computer " \+ "(JANAS_LOCATION)\n" \+ "how.estimated from the internet connection (GeoJS) = estimated from " \+ "the internet connection (GeoJS)\n" \+ "how.estimated from the internet connection (ipwho.is) = estimated from " \+ "the internet connection (ipwho.is)\n" \+ "how.a rough guess, the city of the computer's time zone = a rough " \+ "guess, the city of the computer's time zone\n"++#define PLACE "{{place}}{{#how}} - where the user is, {{how|how}}{{/how}}"++/* The model's cell, and the source. */+#define MODEL \+ "Forecast: {{model.source}}'s model, at the point {{model.lat}}, " \+ "{{model.lon}}{{#model.elev}} ({{model.elev}} m){{/model.elev}}, " \+ "{{model.km}} km from the place: a model's value, not a measure.\n"++const char WX_NOW_LAYOUT[] =+ "The weather now in " PLACE ", at {{time}} {{tz}} (local time):\n"+ "- sky: {{sky|wmo}}{{sky_text}}{{#cloud}} (cloud cover {{cloud}}%)"+ "{{/cloud}}\n"+ "- temperature {{temp}} °C{{#feels}}, feels like {{feels}} °C{{/feels}}"+ "{{#humidity}}; humidity {{humidity}}%{{/humidity}}\n"+ "- wind {{#wind_from}}{{wind_from|from}} ({{wind_deg}}°) {{/wind_from}}"+ "at {{wind}} km/h ({{bft|bft}}){{#gust}}, gusts up to {{gust}} km/h"+ "{{/gust}}\n"+ "{{#has_precip}}\n"+ "- rain in the last quarter of an hour: {{precip}} mm\n"+ "{{/has_precip}}\n"+ "{{#pressure}}\n"+ "- pressure at sea level {{pressure}} hPa\n"+ "{{/pressure}}\n"+ "{{#today}}\n"+ "- today: lowest {{today.tmin}} °C, highest {{today.tmax}} °C"+ "{{#today.has_prob}}, chance of rain {{today.rain_prob}}%"+ "{{/today.has_prob}}{{#today.sunrise}}; sunrise {{today.sunrise}}, "+ "sunset {{today.sunset}}{{/today.sunrise}}\n"+ "{{/today}}\n" MODEL "{{#station}}\n"+ "Measured by the station of {{station.name}} ({{station.icao}}), "+ "{{station.km}} km {{station.dir|dir}} of the place, at "+ "{{station.time}} ({{station.ago}} minutes ago): {{station.temp}} °C, "+ "dew point {{station.dew}} °C{{#station.calm}}, calm{{/station.calm}}"+ "{{#station.variable}}, wind of variable direction at {{station.kt}} kt "+ "({{station.kmh}} km/h){{/station.variable}}{{#station.from}}, wind "+ "{{station.from|from}} at {{station.kt}} kt ({{station.kmh}} km/h, "+ "{{station.bft|bft}}){{/station.from}}{{#station.gust_kt}}, gusts "+ "{{station.gust_kt}} kt ({{station.gust_kmh}} km/h){{/station.gust_kt}}"+ "{{#station.vis_km}}, visibility {{station.vis_km}} km"+ "{{#station.vis_more}} or more{{/station.vis_more}}{{/station.vis_km}}"+ "{{#station.wx}}, {{#station.wx_parts}}{{.|wx}} {{/station.wx_parts}}"+ "({{station.wx}}){{/station.wx}}{{^station.wx}}, no rain or other "+ "weather{{/station.wx}}{{#station.clouds}}, {{cover|cover}}{{#ft}} at "+ "{{ft}} ft ({{m}} m){{/ft}}{{/station.clouds}}{{#station.pressure}}, "+ "pressure {{station.pressure}} hPa{{/station.pressure}}. As reported: "+ "{{station.raw}}\n"+ "{{/station}}\n"+ "{{#temp_diff}}\n"+ "The model's temperature and the station's differ by {{temp_diff}} °C: "+ "the station's is the measure (the station is {{station.km}} km away).\n"+ "{{/temp_diff}}\n"+ "{{#rain_disagree}}\n"+ "The model and the station disagree on rain: the station "+ "{{#station_rain}}reports it{{/station_rain}}{{^station_rain}}reports "+ "none{{/station_rain}}, the model {{#model_rain}}has it{{/model_rain}}"+ "{{^model_rain}}has none{{/model_rain}}.\n"+ "{{/rain_disagree}}\n"+ "{{#no_station}}\n"+ "No weather station reported within {{no_station}} km.\n"+ "{{/no_station}}\n"+ "{{#station_error}}\n"+ "The stations could not be asked ({{station_error}}).\n"+ "{{/station_error}}\n"+ "Sources: {{model.source}} ({{model.url}}, CC BY 4.0){{#station}}; the "+ "station's METAR from aviationweather.gov (NOAA){{/station}}.\n"+ "---\n" WMO_WORDS WIND_WORDS DIR_WORDS STATION_WORDS HOW_WORDS;++const char WX_NOW_BRIEF[] =+ "The weather now in {{place}} at {{time}} {{tz}}{{#how}} (where the "+ "user is, {{how}}: say which place, and that it may be off){{/how}}: "+ "{{sky|wmo}}{{sky_text}}, {{temp}} °C{{#feels}} (feels {{feels}})"+ "{{/feels}}, wind {{wind}} km/h{{#wind_from}} {{wind_from|from}}"+ "{{/wind_from}}{{#gust}}, gusts {{gust}}{{/gust}}{{#today}}; today "+ "{{today.tmin}} to {{today.tmax}} °C{{#today.has_prob}}, chance of "+ "rain {{today.rain_prob}}%{{/today.has_prob}}{{/today}}{{#station}}; "+ "the station of {{station.name}}, {{station.km}} km away, measured "+ "{{station.temp}} °C{{/station}}.{{#temp_diff}} The model and the "+ "station differ by {{temp_diff}} °C: the station's is the "+ "measure.{{/temp_diff}}{{#rain_disagree}} They disagree on "+ "rain.{{/rain_disagree}} The full report is shown to the user as it "+ "is: do not repeat it; answer in a line or two from these figures, in "+ "the user's language.\n"+ "---\n" WMO_WORDS WIND_WORDS;++#define DATE "{{wd|wd}} {{day}} {{mon|mon}}"++const char WX_FORECAST_LAYOUT[] =+ "Forecast for " PLACE ", by the day (times in local time, {{tz}}):\n"+ "{{#days}}\n"+ "- " DATE ": {{sky|wmo}}{{sky_text}}; {{tmin}} to {{tmax}} °C"+ "{{#no_rain}}; no rain{{/no_rain}}{{#rain}}; rain {{rain}} mm{{/rain}}"+ "{{#has_prob}} (chance {{rain_prob}}%){{/has_prob}}{{#wind}}; wind up "+ "to {{wind}} km/h ({{bft|bft}}){{#wind_from}} {{wind_from|from}}"+ "{{/wind_from}}{{/wind}}{{#gust}}, gusts up to {{gust}} km/h{{/gust}}"+ "{{#uv}}; UV index {{uv}}{{/uv}}{{#sunrise}}; sunrise {{sunrise}}, "+ "sunset {{sunset}}{{/sunrise}}\n"+ "{{/days}}\n"+ "{{#fewer}}\n"+ "({{model.source}} gives {{fewer}} days.)\n"+ "{{/fewer}}\n"+ "{{#hours}}\n"+ "{{#newday}}\n"+ "{{newday.wd|wd}} {{newday.day}} {{newday.mon|mon}}\n"+ "{{/newday}}\n"+ "- {{time}}: {{sky|wmo}}{{sky_text}}, {{temp}} °C{{#rain}}, rain "+ "{{rain}} mm{{/rain}}{{#has_prob}} (chance {{rain_prob}}%){{/has_prob}}"+ ", wind {{wind}} km/h{{#wind_from}} {{wind_from|from}}{{/wind_from}}"+ "{{#gust}}, gusts {{gust}}{{/gust}}\n"+ "{{/hours}}\n" MODEL "Source: {{model.source}} ({{model.url}}, CC BY "+ "4.0).\n"+ "---\n" WMO_WORDS WIND_WORDS DATE_WORDS HOW_WORDS;++const char WX_FORECAST_BRIEF[] =+ "The forecast for {{place}}{{#how}} (where the user is, {{how}}: say "+ "which place, and that it may be off){{/how}}, by the day: "+ "{{#days}}" DATE ": {{sky|wmo}}{{sky_text}}, {{tmin}} to {{tmax}} °C"+ "{{#has_prob}}, rain {{rain_prob}}%{{/has_prob}}{{#rain}} ({{rain}} "+ "mm){{/rain}}{{#wind}}, wind {{wind}} km/h{{/wind}}; {{/days}}The full "+ "forecast, hour by hour too, is shown to the user as it is: do not "+ "repeat it; answer in a line or two from these figures, in the user's "+ "language.\n"+ "---\n" WMO_WORDS DATE_WORDS;++/* The sea's state, on the Douglas scale (words.c). */+#define SEA_WORDS \+ "sea.1 = calm\n" \+ "sea.2 = smooth\n" \+ "sea.3 = slight\n" \+ "sea.4 = moderate\n" \+ "sea.5 = rough\n" \+ "sea.6 = very rough\n" \+ "sea.7 = high\n" \+ "sea.8 = very high\n" \+ "sea.9 = phenomenal\n"++#define WHERE \+ "{{#where.sea}}over the {{where.sea}}{{#where.and}}, between " \+ "{{where.region}} and {{where.and}}{{/where.and}}{{/where.sea}}" \+ "{{^where.sea}}over {{where.region}}{{/where.sea}}; {{#where.km}}" \+ "{{where.km}} km {{where.dir|dir}} of {{where.city}}{{/where.km}}" \+ "{{^where.km}}over {{where.city}}{{/where.km}}"++const char WX_SEA_LAYOUT[] =+ "{{#sea}}The state of the {{sea}} at {{time}} local time ({{tz}}), and "+ "the next {{days}} days:{{/sea}}{{^sea}}The state of the sea off " PLACE+ " at {{time}} local time ({{tz}}), and the next {{days}} days:{{/sea}}\n"+ "{{#summary}}\n"+ "Now, at {{summary.points}} points: waves {{summary.lo}} to "+ "{{summary.hi}} m ({{summary.lo_code|sea}}{{#summary.hi_other}} to "+ "{{summary.hi_code|sea}}{{/summary.hi_other}}){{#summary.t_lo}}, water "+ "{{summary.t_lo}} to {{summary.t_hi}} °C{{/summary.t_lo}}.\n"+ "{{#summary.days}}\n"+ "{{wd|wd}} {{day}} {{mon|mon}}: highest waves {{max}} m ({{code|sea}}), " WHERE+ ".\n"+ "{{/summary.days}}\n"+ "{{/summary}}\n"+ "{{#points}}\n"+ "- {{#where}}" WHERE ": {{/where}}waves {{wave}} m ({{wave_code|sea}})"+ "{{#wave_from}} {{wave_from|from}}{{/wave_from}}{{#period}}, period "+ "{{period}} s{{/period}}{{#has_wind_wave}}; wind waves {{wind_wave}} m"+ "{{/has_wind_wave}}{{#has_swell}}, swell {{swell}} m{{#swell_from}} "+ "{{swell_from|from}}{{/swell_from}}{{/has_swell}}{{#sst}}; water "+ "{{sst}} °C{{/sst}}{{#has_wind}}; wind {{wind}} km/h ({{bft|bft}})"+ "{{#wind_from}} {{wind_from|from}}{{/wind_from}}{{#gust}}, gusts "+ "{{gust}} km/h{{/gust}}{{/has_wind}}\n"+ "{{#days}}\n"+ " {{wd|wd}} {{day}} {{mon|mon}}: waves up to {{max}} m ({{code|sea}})"+ "{{#from}} {{from|from}}{{/from}}{{#has_wind}}, wind up to {{wind}} "+ "km/h ({{bft|bft}}){{#gust}}, gusts {{gust}}{{/gust}}{{/has_wind}}\n"+ "{{/days}}\n"+ "{{/points}}\n"+ "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.\n"+ "---\n" SEA_WORDS WIND_WORDS DIR_WORDS DATE_WORDS HOW_WORDS;++const char WX_SEA_BRIEF[] =+ "The sea {{#sea}}of the {{sea}}{{/sea}}{{^sea}}off {{place}}{{#how}} "+ "(where the user is, {{how}}: say which place, and that it may be off)"+ "{{/how}}{{/sea}} at {{time}}: {{#summary}}waves {{summary.lo}} to "+ "{{summary.hi}} m ({{summary.lo_code|sea}} to {{summary.hi_code|sea}})"+ "{{#summary.t_lo}}, water {{summary.t_lo}} to {{summary.t_hi}} "+ "°C{{/summary.t_lo}}; highest by the day: {{#summary.days}}{{wd|wd}} "+ "{{max}} m ({{code|sea}}); {{/summary.days}}{{/summary}}{{^summary}}"+ "{{#points}}waves {{wave}} m ({{wave_code|sea}}){{#sst}}, water {{sst}} "+ "°C{{/sst}}{{#has_wind}}, wind {{wind}} km/h{{/has_wind}}; by the day: "+ "{{#days}}{{wd|wd}} up to {{max}} m ({{code|sea}}); {{/days}}"+ "{{/points}}{{/summary}}The full report is shown to the user as it is: "+ "do not repeat it; answer in a line or two from these figures, in the "+ "user's language.\n"+ "---\n" SEA_WORDS DATE_WORDS;diff --git a/src/weather/metar.c b/src/weather/metar.cindex 26703a5..5835013 100644--- a/src/weather/metar.c+++ b/src/weather/metar.c@@ -44,15 +44,22 @@ static const char *cover_words(const char *c)return c ? c : "";}-static void clouds_of(const struct janas_json *cl, char *out, size_t cap)+static void clouds_of(const struct janas_json *cl, char *out, size_t cap,+ struct wx_obs *o){size_t n = 0;out[0] = 0;+ o->n_layers = 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");+ if (o->n_layers < (int)(sizeof o->layer / sizeof *o->layer)) {+ snprintf(o->layer[o->n_layers].cover,+ sizeof o->layer[o->n_layers].cover, "%s", cov ? cov : "");+ o->layer[o->n_layers++].base_ft = base;+ }n += (size_t)snprintf(out + n, cap - n, "%s%s", n ? ", " : "",cover_words(cov));if (!isnan(base) && n < cap)@@ -119,7 +126,8 @@ int wx_metar_parse(const char *text, size_t len, double lat, double lon,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);+ clouds_of(janas_json_get(best, "clouds"), o->clouds, sizeof o->clouds,+ o);snprintf(o->raw, sizeof o->raw, "%s",janas_json_str(janas_json_get(best, "rawOb"))? janas_json_str(janas_json_get(best, "rawOb"))diff --git a/src/weather/report.c b/src/weather/report.cindex e07515f..fe84772 100644--- a/src/weather/report.c+++ b/src/weather/report.c@@ -7,7 +7,9 @@* 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.+ * The answers are data with a layout (layouts.c, common/template.h).*/+#define _GNU_SOURCE /* timegm */#include <math.h>#include <stdio.h>#include <stdlib.h>@@ -15,6 +17,7 @@#include <time.h>#include "common/geo.h"+#include "common/template.h"#include "weather.h"#define STATION_KM 40 /* the nearest station, within this */@@ -32,145 +35,209 @@ static int forecast(const struct wx_place *p, int days, struct wx_forecast *f,return -1;}-static void sky(int code, const char *symbol, char *out, size_t cap)+/* ---- the data ---- */++void wx_jstr(struct janas_buf *b, const char *key, const char *v){- 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");+ janas_buf_printf(b, ", \"%s\": ", key);+ janas_json_write_str(b, v, strlen(v));}-/* "-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)+/* a number, when there is one */+void wx_jnum(struct janas_buf *b, const char *key, double v, int decimals){- 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++;+ if (!isnan(v))+ janas_buf_printf(b, ", \"%s\": %.*f", key, decimals, v);+}++/* the sky: a WMO code with words in the layout, or MET Norway's symbol+ in words */+static void jsky(struct janas_buf *b, int code, const char *symbol)+{+ if (code >= 0 && wx_code_text(code)) {+ janas_buf_printf(b, ", \"sky\": %d", code);+ } else {+ char s[96] = "not given";+ if (symbol && *symbol)+ wx_symbol_text(symbol, s, sizeof s);+ wx_jstr(b, "sky_text", 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++;+}++/* where the wind blows from, and how hard */+void wx_jwind(struct janas_buf *b, double kmh, double deg)+{+ wx_jnum(b, "wind", kmh, 0);+ if (!isnan(kmh))+ janas_buf_printf(b, ", \"bft\": %d", wx_beaufort(kmh));+ if (!isnan(deg)) {+ wx_jstr(b, "wind_from", geo_compass(deg));+ wx_jnum(b, "wind_deg", deg, 0);}- while (n && out[n - 1] == ' ')- out[--n] = 0;}-static void visibility(const char *v, char *out, size_t cap)+/* "2026-10-02": its weekday (0 Sunday), day and month */+void wx_jdate(struct janas_buf *b, const char *date){- if (!v[0]) {- snprintf(out, cap, "not given");+ struct tm tm = {0};+ if (sscanf(date, "%d-%d-%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday) != 3)return;- }- if (strchr(v, '+')) {- snprintf(out, cap, "%.0f km or more", atof(v) * 1.609);+ int day = tm.tm_mday, mon = tm.tm_mon;+ tm.tm_year -= 1900;+ tm.tm_mon -= 1;+ tm.tm_hour = 12;+ time_t t = timegm(&tm);+ struct tm g;+ gmtime_r(&t, &g);+ janas_buf_printf(b, "\"wd\": %d, \"day\": %d, \"mon\": %d", g.tm_wday, day,+ mon);+}++/* the place, and where the user is when it was not named */+void wx_jplace(struct janas_buf *b, const struct wx_place *p)+{+ struct wx_place q = *p;+ q.how[0] = 0; /* the layout says it */+ char name[256];+ wx_place_name(&q, name, sizeof name);+ janas_buf_puts(b, "{\"place\": ");+ janas_json_write_str(b, name, strlen(name));+ if (p->how[0])+ wx_jstr(b, "how", p->how);+}++static void jmodel(struct janas_buf *b, const struct wx_place *p,+ const struct wx_forecast *f)+{+ janas_buf_puts(b, ", \"model\": {\"source\": ");+ janas_json_write_str(b, f->source, strlen(f->source));+ wx_jstr(b, "url",+ strcmp(f->source, "Open-Meteo") == 0 ? "open-meteo.com"+ : "api.met.no");+ wx_jnum(b, "lat", f->grid_lat, 3);+ wx_jnum(b, "lon", f->grid_lon, 3);+ if (!isnan(f->grid_elev))+ wx_jnum(b, "elev", f->grid_elev, 0);+ wx_jnum(b, "km", geo_km(p->lat, p->lon, f->grid_lat, f->grid_lon), 1);+ janas_buf_puts(b, "}");+}++/* statute miles as given ("6+", "1 1/2") in km */+static void jvisibility(struct janas_buf *b, const char *v)+{+ if (!v[0])return;- }double mi = atof(v);- const char *frac = strchr(v, '/'); /* "1 1/2", "1/4" */+ const char *frac = strchr(v, '/');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);+ int a = atoi(sp ? sp + 1 : v), d = atoi(frac + 1);+ mi = whole + (d ? (double)a / d : 0);}- snprintf(out, cap, "%.1f km", mi * 1.609);+ wx_jnum(b, "vis_km", mi * 1.609, strchr(v, '+') ? 0 : 1);+ if (strchr(v, '+'))+ janas_buf_puts(b, ", \"vis_more\": true");}-static void observation(const struct wx_place *p, const struct wx_obs *o,- const struct wx_forecast *f, struct janas_buf *out)+/* "-SHRA": its parts, "-", "SH", "RA", for the layout's words */+static void jweather(struct janas_buf *b, const char *wx){- char when[64], dir[64], vis[32], words[96];+ static const char *const codes[] = {"TS", "SH", "FZ", "RA", "DZ", "SN",+ "GR", "GS", "FG", "BR", "HZ", "VC"};+ wx_jstr(b, "wx", wx);+ janas_buf_puts(b, ", \"wx_parts\": [");+ const char *s = wx;+ int k = 0;+ if (*s == '-' || *s == '+') {+ janas_buf_printf(b, "\"%c\"", *s);+ k++;+ s++;+ }+ while (*s) {+ size_t i;+ for (i = 0; i < sizeof codes / sizeof *codes; i++)+ if (strncmp(s, codes[i], 2) == 0) {+ janas_buf_printf(b, "%s\"%s\"", k++ ? ", " : "", codes[i]);+ s += 2;+ break;+ }+ if (i == sizeof codes / sizeof *codes)+ s++;+ }+ janas_buf_puts(b, "]");+}++static void jstation(struct janas_buf *b, const struct wx_place *p,+ const struct wx_obs *o)+{+ char when[64];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);+ janas_buf_puts(b, ", \"station\": {\"name\": ");+ janas_json_write_str(b, o->name, strlen(o->name));+ wx_jstr(b, "icao", o->icao);+ wx_jnum(b, "km", o->km, 0);+ wx_jstr(b, "dir", geo_compass(geo_bearing(p->lat, p->lon, o->lat, o->lon)));+ wx_jstr(b, "time", when);+ janas_buf_printf(b, ", \"ago\": %ld",+ (long)difftime(time(NULL), o->at) / 60);+ wx_jnum(b, "temp", o->temp, 0);+ wx_jnum(b, "dew", o->dew, 0);if (!isnan(o->wind_kt)) {if (o->wind_kt < 1)- janas_buf_puts(out, ", calm");+ janas_buf_puts(b, ", \"calm\": true");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));+ janas_buf_puts(b, ", \"variable\": true");+ else+ wx_jstr(b, "from", geo_compass(o->wind_dir));+ if (o->wind_kt >= 1) {+ wx_jnum(b, "kt", o->wind_kt, 0);+ wx_jnum(b, "kmh", o->wind_kt * 1.852, 0);+ janas_buf_printf(b, ", \"bft\": %d",+ wx_beaufort(o->wind_kt * 1.852));+ }+ if (!isnan(o->gust_kt)) {+ wx_jnum(b, "gust_kt", o->gust_kt, 0);+ wx_jnum(b, "gust_kmh", o->gust_kt * 1.852, 0);}- 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");+ jvisibility(b, o->visib);+ if (o->wx[0])+ jweather(b, o->wx);+ if (o->n_layers) {+ janas_buf_puts(b, ", \"clouds\": [");+ for (int i = 0; i < o->n_layers; i++) {+ janas_buf_printf(b, "%s{\"cover\": ", i ? ", " : "");+ janas_json_write_str(b, o->layer[i].cover,+ strlen(o->layer[i].cover));+ if (!isnan(o->layer[i].base_ft)) {+ wx_jnum(b, "ft", o->layer[i].base_ft, 0);+ wx_jnum(b, "m", o->layer[i].base_ft * 0.3048, 0);+ }+ janas_buf_puts(b, "}");+ }+ janas_buf_puts(b, "]");}- 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");+ wx_jnum(b, "pressure", o->pressure, 0);+ wx_jstr(b, "raw", o->raw);+ janas_buf_puts(b, "}");}-static void source_line(const struct wx_place *p, const struct wx_forecast *f,- struct janas_buf *out)+/* The answer from the data and its layout. */+int wx_answer(struct janas_buf *b, const char *name, struct janas_buf *d,+ const char *layout, const char *brief){- 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);+ char err[300];+ if (d->oom || janas_tpl_result(b, name, d->p, d->n, layout, brief, err,+ sizeof err) != 0) {+ struct janas_buf out = {0};+ janas_buf_printf(&out, "The answer could not be written: %s.",+ d->oom ? "out of memory" : err);+ janas_buf_free(d);+ return wx_result(&out, b, 1);+ }+ janas_buf_free(d);+ return 0;}int wx_tool_now(const struct janas_json *args, struct janas_buf *b)@@ -179,10 +246,10 @@ int wx_tool_now(const struct janas_json *args, struct janas_buf *b)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];+ char err[800], name[256];wx_place_name(&p, name, sizeof name);if (!f || forecast(&p, 1, f, err, sizeof err) != 0) {+ struct janas_buf out = {0};janas_buf_printf(&out, "No forecast for %s: %s.", name,f ? err : "out of memory");free(f);@@ -192,109 +259,64 @@ int wx_tool_now(const struct janas_json *args, struct janas_buf *b)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);+ struct janas_buf d = {0};+ wx_jplace(&d, &p);+ janas_buf_printf(&d, ", \"time\": \"%.5s\"", T ? T + 1 : w->time);+ wx_jstr(&d, "tz", f->tz_abbr);+ jsky(&d, w->code, w->symbol);+ wx_jnum(&d, "cloud", w->cloud, 0);+ wx_jnum(&d, "temp", w->temp, 1);+ wx_jnum(&d, "feels", w->feels, 1);+ wx_jnum(&d, "humidity", w->humidity, 0);+ wx_jwind(&d, w->wind, w->wind_dir);+ wx_jnum(&d, "gust", w->gust, 0);+ if (!isnan(w->precip)) {+ janas_buf_puts(&d, ", \"has_precip\": true");+ wx_jnum(&d, "precip", w->precip, 1);+ }+ wx_jnum(&d, "pressure", w->pressure, 0);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(&d, ", \"today\": {\"tmin\": ");+ janas_buf_printf(&d, "%.1f, \"tmax\": %.1f", y->tmin, y->tmax);+ if (!isnan(y->rain_prob)) {+ janas_buf_puts(&d, ", \"has_prob\": true");+ wx_jnum(&d, "rain_prob", y->rain_prob, 0);+ }+ if (y->sunrise[0]) {+ wx_jstr(&d, "sunrise", y->sunrise);+ wx_jstr(&d, "sunset", y->sunset);+ }+ janas_buf_puts(&d, "}");}- janas_buf_puts(&out, "\n");- source_line(&p, f, &out);-+ jmodel(&d, &p, f);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 (r == 1) {+ jstation(&d, &p, &o);+ if (f->has_now && !isnan(f->now.temp) &&+ fabs(f->now.temp - o.temp) >= 3)+ wx_jnum(&d, "temp_diff", fabs(f->now.temp - o.temp), 0);+ 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(&d,+ ", \"rain_disagree\": true, \"station_rain\": "+ "%s, \"model_rain\": %s",+ st_rain ? "true" : "false",+ fc_rain ? "true" : "false");+ } else if (r == 0) {+ janas_buf_printf(&d, ", \"no_station\": %d", STATION_KM);+ } else {+ wx_jstr(&d, "station_error", why);}- 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");+ janas_buf_puts(&d, "}");+ free(f);+ return wx_answer(b, "weather_now", &d, WX_NOW_LAYOUT, WX_NOW_BRIEF);}int wx_tool_forecast(const struct janas_json *args, struct janas_buf *b)@@ -309,45 +331,80 @@ int wx_tool_forecast(const struct janas_json *args, struct janas_buf *b)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) {+ struct janas_buf out = {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);+ struct janas_buf d = {0};+ wx_jplace(&d, &p);+ wx_jstr(&d, "tz", f->tz_abbr);+ janas_buf_puts(&d, ", \"days\": [");+ for (int i = 0; i < f->n_day && i < days; i++) {+ const struct wx_day *y = &f->day[i];+ janas_buf_puts(&d, i ? ", {" : "{");+ wx_jdate(&d, y->date);+ jsky(&d, y->code, y->symbol);+ wx_jnum(&d, "tmin", y->tmin, 1);+ wx_jnum(&d, "tmax", y->tmax, 1);+ if (!isnan(y->rain)) {+ if (y->rain < 0.1)+ janas_buf_puts(&d, ", \"no_rain\": true");+ else+ wx_jnum(&d, "rain", y->rain, 1);+ }+ if (!isnan(y->rain_prob)) {+ janas_buf_puts(&d, ", \"has_prob\": true");+ wx_jnum(&d, "rain_prob", y->rain_prob, 0);+ }+ wx_jwind(&d, y->wind, y->wind_dir);+ wx_jnum(&d, "gust", y->gust, 0);+ wx_jnum(&d, "uv", y->uv, 0);+ if (y->sunrise[0]) {+ wx_jstr(&d, "sunrise", y->sunrise);+ wx_jstr(&d, "sunset", y->sunset);+ }+ janas_buf_puts(&d, "}");+ }+ janas_buf_puts(&d, "]");if (f->n_day < days)- janas_buf_printf(&out, "(%s gives %d days.)\n", f->source, f->n_day);+ janas_buf_printf(&d, ", \"fewer\": %d", 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);+ janas_buf_puts(&d, ", \"hours\": [");+ char prev[11] = "";+ for (int i = 0; i < f->n_hour && i < last; i += step) {+ const struct wx_hour *h = &f->hour[i];+ const char *T = strchr(h->time, 'T');+ janas_buf_printf(&d, "%s{\"time\": \"%.5s\"", i ? ", " : "",+ T ? T + 1 : h->time);+ if (strncmp(prev, h->time, 10) != 0) {+ char date[11];+ snprintf(date, sizeof date, "%.10s", h->time);+ janas_buf_puts(&d, ", \"newday\": {");+ wx_jdate(&d, date);+ janas_buf_puts(&d, "}");+ snprintf(prev, sizeof prev, "%s", date);+ }+ jsky(&d, h->code, h->symbol);+ wx_jnum(&d, "temp", h->temp, 1);+ if (!isnan(h->rain) && h->rain >= 0.1)+ wx_jnum(&d, "rain", h->rain, 1);+ if (!isnan(h->rain_prob)) {+ janas_buf_puts(&d, ", \"has_prob\": true");+ wx_jnum(&d, "rain_prob", h->rain_prob, 0);}+ wx_jwind(&d, h->wind, h->wind_dir);+ wx_jnum(&d, "gust", h->gust, 0);+ janas_buf_puts(&d, "}");}- 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");+ janas_buf_puts(&d, "]");+ jmodel(&d, &p, f);+ janas_buf_puts(&d, "}");free(f);- wx_place_note(p.how, &out);- return wx_result(&out, b, 0);+ return wx_answer(b, "weather_forecast", &d, WX_FORECAST_LAYOUT,+ WX_FORECAST_BRIEF);}diff --git a/src/weather/sea.c b/src/weather/sea.cindex b00729e..f0d2bd9 100644--- a/src/weather/sea.c+++ b/src/weather/sea.c@@ -51,55 +51,59 @@ static int area_points(const struct geo_area *a, struct wx_sea *s)return k;}-static void point_line(const struct wx_sea *s, int days, int with_place,- struct janas_buf *out)+/* One point: now, and its days. */+static void point_json(const struct wx_sea *s, int days, int with_place,+ struct janas_buf *d){- char dir[64];- janas_buf_puts(out, "- ");+ janas_buf_puts(d, "{\"wave\": ");+ janas_buf_printf(d, "%.1f, \"wave_code\": %d", s->wave,+ wx_douglas(s->wave));if (with_place) {- geo_describe(s->lat, s->lon, out);- janas_buf_puts(out, ": ");+ janas_buf_puts(d, ", \"where\": ");+ geo_describe_json(s->lat, s->lon, d);+ }+ if (!isnan(s->wave_dir))+ wx_jstr(d, "wave_from", geo_compass(s->wave_dir));+ wx_jnum(d, "period", s->period, 0);+ if (!isnan(s->wind_wave)) {+ janas_buf_puts(d, ", \"has_wind_wave\": true");+ wx_jnum(d, "wind_wave", s->wind_wave, 1);}- 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);+ janas_buf_puts(d, ", \"has_swell\": true");+ wx_jnum(d, "swell", s->swell, 1);+ if (!isnan(s->swell_dir))+ wx_jstr(d, "swell_from", geo_compass(s->swell_dir));}- if (!isnan(s->sst))- janas_buf_printf(out, "; water %.1f °C", s->sst);+ wx_jnum(d, "sst", s->sst, 1);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(d, ", \"has_wind\": true");+ wx_jwind(d, s->wind, s->wind_dir);+ wx_jnum(d, "gust", s->gust, 0);}- 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);+ janas_buf_puts(d, ", \"days\": [");+ for (int k = 0; k < s->n_day && k < days; k++) {+ const struct wx_sea_day *y = &s->day[k];+ janas_buf_puts(d, k ? ", {" : "{");+ wx_jdate(d, y->date);+ janas_buf_printf(d, ", \"max\": %.1f, \"code\": %d", y->wave_max,+ wx_douglas(y->wave_max));+ if (!isnan(y->wave_dir))+ wx_jstr(d, "from", geo_compass(y->wave_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(d, ", \"has_wind\": true");+ wx_jnum(d, "wind", y->wind_max, 0);+ janas_buf_printf(d, ", \"bft\": %d", wx_beaufort(y->wind_max));+ wx_jnum(d, "gust", y->gust_max, 0);}- janas_buf_puts(out, "\n");+ janas_buf_puts(d, "}");}+ janas_buf_puts(d, "]}");}-static void summary(const struct wx_sea *s, int n, int days,- struct janas_buf *out)+/* A whole sea: from what to what now, and where it is roughest each day. */+static void summary_json(const struct wx_sea *s, int n, int days,+ struct janas_buf *d){double lo = NAN, hi = NAN, t_lo = NAN, t_hi = NAN;int ok = 0;@@ -118,30 +122,33 @@ static void summary(const struct wx_sea *s, int n, int days,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++) {+ janas_buf_printf(d,+ ", \"summary\": {\"points\": %d, \"lo\": %.1f, \"hi\": "+ "%.1f, \"lo_code\": %d, \"hi_code\": %d",+ ok, lo, hi, wx_douglas(lo), wx_douglas(hi));+ if (wx_douglas(lo) != wx_douglas(hi))+ janas_buf_puts(d, ", \"hi_other\": true");+ wx_jnum(d, "t_lo", t_lo, 1);+ wx_jnum(d, "t_hi", t_hi, 1);+ janas_buf_puts(d, ", \"days\": [");+ int any = 0;+ for (int k = 0; k < days; k++) {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))+ if (s[i].ok && k < s[i].n_day && !isnan(s[i].day[k].wave_max) &&+ (at < 0 || s[i].day[k].wave_max > s[at].day[k].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");+ janas_buf_puts(d, any++ ? ", {" : "{");+ wx_jdate(d, s[at].day[k].date);+ janas_buf_printf(d, ", \"max\": %.1f, \"code\": %d, \"where\": ",+ s[at].day[k].wave_max,+ wx_douglas(s[at].day[k].wave_max));+ geo_describe_json(s[at].lat, s[at].lon, d);+ janas_buf_puts(d, "}");}+ janas_buf_puts(d, "]}");}int wx_tool_sea(const struct janas_json *args, struct janas_buf *b)@@ -157,6 +164,7 @@ int wx_tool_sea(const struct janas_json *args, struct janas_buf *b)char err[512], tz[48] = "", title[256], how[96] = "";int n;struct geo_area a;+ struct wx_place place = {0};if (area) {if (!geo_area_find(area, &a)) {janas_buf_printf(&out,@@ -178,6 +186,7 @@ int wx_tool_sea(const struct janas_json *args, struct janas_buf *b)struct wx_place p;if (wx_arg_place(args, &p, b) != 0)return 0;+ place = p;snprintf(how, sizeof how, "%s", p.how);memset(&s[0], 0, sizeof s[0]);s[0].lat = p.lat;@@ -206,20 +215,26 @@ int wx_tool_sea(const struct janas_json *args, struct janas_buf *b)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);+ struct janas_buf d = {0};+ if (area) {+ janas_buf_puts(&d, "{\"sea\": ");+ janas_json_write_str(&d, a.name, strlen(a.name));+ } else {+ wx_jplace(&d, &place);+ }+ janas_buf_printf(&d, ", \"time\": \"%.5s\"", T ? T + 1 : s[0].time);+ wx_jstr(&d, "tz", tz[0] ? tz : "UTC");+ janas_buf_printf(&d, ", \"days\": %d", days);if (area)- summary(s, n, days, &out);+ summary_json(s, n, days, &d);+ janas_buf_puts(&d, ", \"points\": [");+ int k = 0;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);+ if (s[i].ok) {+ janas_buf_puts(&d, k++ ? ", " : "");+ point_json(&s[i], days, area != NULL, &d);+ }+ janas_buf_puts(&d, "]}");+ (void)how;+ return wx_answer(b, "weather_sea", &d, WX_SEA_LAYOUT, WX_SEA_BRIEF);}diff --git a/src/weather/weather.h b/src/weather/weather.hindex 24d13b8..99918c9 100644--- a/src/weather/weather.h+++ b/src/weather/weather.h@@ -148,6 +148,11 @@ struct wx_obs {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" */+ struct {+ char cover[8]; /* "FEW", "OVC", "CAVOK" */+ double base_ft; /* NAN when not given */+ } layer[6]; /* the same, as coded */+ int n_layers;char raw[160];};@@ -208,6 +213,11 @@ const char *wx_code_text(int code);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 wind's force on the Beaufort scale, 0 (calm) to 12. */+int wx_beaufort(double kmh);+/* The sea's state on the Douglas scale, 1 (calm, below 10 cm) to 9+ (phenomenal). */+int wx_douglas(double m);/* The sea's state from the waves' height, on the Douglas scale. */const char *wx_sea_words(double m);/* "from the north-west (321°)" */@@ -247,4 +257,27 @@ 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);+/* ---- report.c: data for a layout (common/template.h) ---- */++/* , "key": value, as JSON: a text; a number with that many decimals,+ nothing when NAN; the wind's force and where it blows from; a date's+ weekday (0 Sunday), day and month (no comma before). */+void wx_jstr(struct janas_buf *b, const char *key, const char *v);+void wx_jnum(struct janas_buf *b, const char *key, double v, int decimals);+void wx_jwind(struct janas_buf *b, double kmh, double deg);+void wx_jdate(struct janas_buf *b, const char *date);+/* {"place": its name, and "how" when it is where the user is (no "}"). */+void wx_jplace(struct janas_buf *b, const struct wx_place *p);+/* The result from the data d (freed) and a layout; an error otherwise. */+int wx_answer(struct janas_buf *b, const char *name, struct janas_buf *d,+ const char *layout, const char *brief);++/* ---- layouts.c ---- */++/* The layouts and briefs of weather_now and weather_forecast+ (common/template.h). */+extern const char WX_NOW_LAYOUT[], WX_NOW_BRIEF[];+extern const char WX_FORECAST_LAYOUT[], WX_FORECAST_BRIEF[];+extern const char WX_SEA_LAYOUT[], WX_SEA_BRIEF[];+#endifdiff --git a/src/weather/words.c b/src/weather/words.cindex 3ab8beb..fcce53a 100644--- a/src/weather/words.c+++ b/src/weather/words.c@@ -144,6 +144,27 @@ const char *wx_wind_words(double kmh)return "hurricane force";}+int wx_beaufort(double kmh)+{+ static const double below[] = {1, 6, 12, 20, 29, 39,+ 50, 62, 75, 89, 103, 118};+ int i = 0;+ while (i < 12 && !(kmh < below[i]))+ i++;+ return i;+}++int wx_douglas(double m)+{+ /* degree 0 is the glassy sea, no waves at all: a model's height is+ never that, so the first degree is 1, below 10 cm */+ static const double below[] = {0.1, 0.5, 1.25, 2.5, 4, 6, 9, 14};+ int i = 0;+ while (i < 8 && !(m < below[i]))+ i++;+ return i + 1;+}+const char *wx_sea_words(double m){if (m < 0.1)diff --git a/tests/test_layout.c b/tests/test_layout.cnew file mode 100644index 0000000..97415fd--- /dev/null+++ b/tests/test_layout.c@@ -0,0 +1,124 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * test_layout.c - a layout put into another language by janas-chat,+ * without a model: a translator that gives the text back as it came, so+ * that what the program puts on its own shows: the tags and keys back in+ * place, the decimal comma, the terms of the glossary (never asked of the+ * model) and the file kept, in a directory of its own under ~/tmp.+ * The sources belong to the program, so they are compiled in here.+ */+#include <stdio.h>+#include <string.h>+#include <unistd.h>++#include "chat/glossary.c"+#include "chat/layout.c"++static int failures;++#define CHECK(c, ...) \+ do { \+ if (!(c)) { \+ printf(__VA_ARGS__); \+ printf("\n"); \+ failures++; \+ } \+ } while (0)++static const char EN[] = "Wind {{wind}} km/h ({{bft|bft}}), sea "+ "{{wave}} m ({{code|sea}}).\n"+ "---\n"+ "bft.1 = light air\n"+ "bft.4 = moderate breeze\n"+ "sea.2 = smooth\n"+ "wd.Mon = Mon\n";++static char asked[4096];+static int calls;++/* The text back as it came: "Translate into ...:\n\n" cut off. */+static int echo(const char *name, const char *system, const char *text,+ char **out)+{+ (void)name;+ (void)system;+ calls++;+ snprintf(asked, sizeof asked, "%s", text);+ const char *t = strstr(text, "\n\n");+ *out = strdup(t ? t + 2 : text);+ return *out ? 0 : -1;+}++int main(void)+{+ CHECK(strcmp(glossary_word("it", "bft.1", 5), "bava di vento") == 0 &&+ strcmp(glossary_word("it", "sea.4", 5), "molto mosso") == 0 &&+ strcmp(glossary_word("es", "bft.12", 6), "temporal huracanado") ==+ 0,+ "the glossary's terms");+ CHECK(!glossary_word("it", "bft.13", 6) &&+ !glossary_word("it", "sea.", 4) &&+ !glossary_word("it", "sea.1x", 6) &&+ !glossary_word("it", "wd.Mon", 6) &&+ !glossary_word("en", "bft.1", 5) &&+ !glossary_word("xx", "bft.1", 5),+ "words the glossary has not");+ CHECK(glossary_mark("it", 1) != glossary_mark("fr", 1) &&+ glossary_mark("en", 1) == 1,+ "the glossary's mark");++ char dir[512];+ const char *home = getenv("HOME");+ snprintf(dir, sizeof dir, "%s/tmp/janas-layout-test-%d", home ? home : ".",+ (int)getpid());+ if (mkdir(dir, 0700) != 0) {+ printf("cannot make %s\n", dir);+ return 1;+ }+ setenv("XDG_CONFIG_HOME", dir, 1);+ layout_set_lang("it");+ layout_set_translator(echo);++ char *it = translated("test", EN);+ CHECK(it != NULL, "no layout");+ if (it) {+ CHECK(strstr(it, "Wind {{wind}} km/h ({{bft|bft}}), sea {{wave}} m "+ "({{code|sea}}).") == it,+ "the tags back in place:\n%s", it);+ CHECK(strstr(it, "bft.1 = bava di vento\n") &&+ strstr(it, "bft.4 = vento moderato\n") &&+ strstr(it, "sea.2 = poco mosso\n") &&+ strstr(it, "wd.Mon = Mon\n") && strstr(it, "decimal = ,\n"),+ "the words:\n%s", it);+ }+ CHECK(strstr(asked, "Italian, with these terms: swell = mare lungo") &&+ strstr(asked, ": Mon [day of the week Mon]") &&+ !strstr(asked, "light air") && !strstr(asked, "smooth"),+ "the request:\n%s", asked);++ /* the second time, from the file */+ char *again = translated("test", EN);+ CHECK(calls == 1 && again && it && strcmp(again, it) == 0,+ "the layout kept (%d requests)", calls);+ free(again);+ free(it);++ /* tidy up: the one file and the two directories made here */+ char path[1200];+ snprintf(path, sizeof path, "%s/janas/layouts/test.it.%016llx.txt", dir,+ (unsigned long long)glossary_mark("it", mark(EN)));+ CHECK(unlink(path) == 0, "no file at %s", path);+ snprintf(path, sizeof path, "%s/janas/layouts", dir);+ rmdir(path);+ snprintf(path, sizeof path, "%s/janas", dir);+ rmdir(path);+ rmdir(dir);++ if (failures) {+ printf("test_layout: %d failures\n", failures);+ return 1;+ }+ printf("test_layout: ok\n");+ return 0;+}diff --git a/tests/test_template.c b/tests/test_template.cnew file mode 100644index 0000000..101d481--- /dev/null+++ b/tests/test_template.c@@ -0,0 +1,141 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * test_template.c - layouts filled with data (src/common/template.c):+ * fields, words, lists and their numbers, parts shown or not, lines of a+ * part's tag left out, the decimal point of the words, what is wrong in a+ * layout, and a translation's shape against its original.+ */+#include <stdio.h>+#include <string.h>++#include "common/template.h"++static int failures;++#define CHECK(c, ...) \+ do { \+ if (!(c)) { \+ printf(__VA_ARGS__); \+ printf("\n"); \+ failures++; \+ } \+ } while (0)++static const char DATA[] =+ "{\"sea\": \"Tyrrhenian Sea\", \"count\": 3, \"temp\": 21.7, \"none\": 0,"+ " \"empty\": \"\", \"tags\": [\"a\", \"b\"], \"aircraft\": [{\"call\": "+ "\"AZ1\", \"dir\": \"NE\", \"route\": {\"from\": \"Rome\", \"to\": "+ "\"Milan\"}}, {\"call\": \"FR2\", \"dir\": \"SW\"}, {\"call\": \"U23\", "+ "\"dir\": \"N\", \"emergency\": \"7700\"}]}";++/* The layout filled with DATA, or "ERROR: why". */+static const char *fill(const char *tpl)+{+ static char text[2048];+ struct janas_json_doc *d = janas_json_parse(DATA, strlen(DATA), NULL, 0);+ struct janas_buf out = {0};+ char err[200];+ if (!d || janas_tpl_render(tpl, strlen(tpl), janas_json_root(d), &out, err,+ sizeof err) != 0)+ snprintf(text, sizeof text, "ERROR: %s", d ? err : "data");+ else+ snprintf(text, sizeof text, "%.*s", (int)out.n, out.p ? out.p : "");+ janas_buf_free(&out);+ janas_json_free(d);+ return text;+}++#define SAME(tpl, want) \+ do { \+ const char *got = fill(tpl); \+ CHECK(strcmp(got, want) == 0, "%s\n--- got\n%s\n--- wanted\n%s", tpl, \+ got, want); \+ } while (0)++static void test_fill(void)+{+ SAME("{{count}} over the {{sea}}.", "3 over the Tyrrhenian Sea.");+ SAME("{{temp}} C\n---\ndecimal = ,", "21,7 C");+ SAME("[{{missing}}][{{none}}]", "[][0]");+ SAME("{{#aircraft}}{{@n}}. {{call}} {{dir|dir}}; {{/aircraft}}\n---\n"+ "dir.NE = nord-est\ndir.SW = sud-ovest",+ "1. AZ1 nord-est; 2. FR2 sud-ovest; 3. U23 N; ");+ SAME("{{#aircraft}}{{call}}{{#route}} {{from}}-{{to}}{{/route}}"+ "{{^route}} -{{/route}}{{#emergency}} SOS {{emergency}}"+ "{{/emergency}},{{/aircraft}}",+ "AZ1 Rome-Milan,FR2 -,U23 - SOS 7700,");+ SAME("{{#tags}}<{{.}}>{{/tags}}", "<a><b>");+ SAME("{{^none}}no{{/none}}{{^empty}} empty{{/empty}}{{#count}} "+ "some{{/count}}",+ "no empty some");+ /* a line of a part's tag alone is left out whole */+ SAME("List:\n{{#aircraft}}\n- {{call}}\n{{/aircraft}}\nEnd.",+ "List:\n- AZ1\n- FR2\n- U23\nEnd.");+ SAME("{{#aircraft}}{{#route}}{{sea}}: {{route.from}}{{/route}}"+ "{{/aircraft}}",+ "Tyrrhenian Sea: Rome");+ SAME("a word with a new line: {{dir|w}}\n---\nw = x\n# a note\n"+ "w.3 = no",+ "a word with a new line: ");+ SAME("{{count|n}}\n---\nn.3 = three\\nlines", "three\nlines");+ CHECK(strncmp(fill("{{#aircraft}}open"), "ERROR", 5) == 0,+ "a part not closed");+ CHECK(strncmp(fill("{{#aircraft}}x{{/route}}"), "ERROR", 5) == 0,+ "closed by another name");+ CHECK(strncmp(fill("x {{count"), "ERROR", 5) == 0, "a tag not ended");+ CHECK(strncmp(fill("{{/count}}"), "ERROR", 5) == 0, "a close alone");+}++static void test_shape(void)+{+ const char *en = "{{count}} aircraft over the {{sea}}:\n{{#aircraft}}\n"+ "{{@n}}. {{call}} heading {{dir|dir}}\n{{/aircraft}}\n"+ "---\ndir.NE = north-east\ndir.SW = south-west";+ const char *it = "Sul {{sea}} volano {{count}} aerei:\n{{#aircraft}}\n"+ "{{@n}}. {{call}} verso {{dir|dir}}\n{{/aircraft}}\n"+ "---\ndir.SW = sud-ovest\ndir.NE = nord-est\ndir.X "+ "= y\ndecimal = ,";+ char why[200];+ CHECK(!janas_tpl_same_shape(en, strlen(en), it, strlen(it), why,+ sizeof why) &&+ strstr(why, "words"),+ "a word more: %s", why);+ const char *it2 = "Sul {{sea}} volano {{count}} aerei:\n{{#aircraft}}\n"+ "{{@n}}. {{call}} verso {{dir|dir}}\n{{/aircraft}}\n"+ "---\ndir.SW = sud-ovest\ndir.NE = nord-est";+ CHECK(+ janas_tpl_same_shape(en, strlen(en), it2, strlen(it2), why, sizeof why),+ "fields moved, words in another order: %s", why);+ const char *it3 = "Sul {{sea}} volano {{count}} aerei:\n{{#aircraft}}\n"+ "{{@n}}. {{call}} verso {{dir|dir}}\n{{/aircraft}}\n"+ "---\ndir.SW = sud-ovest\ndir.NE = nord-est\n"+ "decimal = ,";+ CHECK(+ janas_tpl_same_shape(en, strlen(en), it3, strlen(it3), why, sizeof why),+ "a decimal point added: %s", why);+ const char *bad = "Sul {{mare}} volano {{count}} aerei:\n{{#aircraft}}\n"+ "{{@n}}. {{call}} verso {{dir|dir}}\n{{/aircraft}}\n"+ "---\ndir.SW = sud-ovest\ndir.NE = nord-est";+ CHECK(!janas_tpl_same_shape(en, strlen(en), bad, strlen(bad), why,+ sizeof why) &&+ strstr(why, "fields"),+ "a field renamed: %s", why);+ const char *lost = "Sul {{sea}} volano {{count}} aerei.\n---\n"+ "dir.SW = sud-ovest\ndir.NE = nord-est";+ CHECK(!janas_tpl_same_shape(en, strlen(en), lost, strlen(lost), why,+ sizeof why),+ "a part lost");+}++int main(void)+{+ test_fill();+ test_shape();+ if (failures) {+ printf("test_template: %d failures\n", failures);+ return 1;+ }+ printf("test_template: ok\n");+ return 0;+}diff --git a/tests/test_weather_parse.c b/tests/test_weather_parse.cindex b257132..87cd6c7 100644--- a/tests/test_weather_parse.c+++ b/tests/test_weather_parse.c@@ -861,6 +861,9 @@ static void words(void)CHECK(strcmp(wx_sea_words(0.08), "calm") == 0 &&strcmp(wx_sea_words(1.5), "moderate") == 0,"Douglas");+ CHECK(wx_douglas(0.05) == 1 && wx_douglas(0.3) == 2 &&+ wx_douglas(1.5) == 4 && wx_douglas(20) == 9,+ "Douglas degrees");wx_from_dir(321, s, sizeof s);CHECK(strcmp(s, "from the north-west (321°)") == 0, "direction: '%s'", s);}