Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
serve: the modalities a model card claims are the ones the engine loaded
Léon Avic Simmonsc60f78ad03c2
diff --git a/c/deepseek_v41.c b/c/deepseek_v41.cindex d4e2df1d..adecf92a 100644--- a/c/deepseek_v41.c+++ b/c/deepseek_v41.c@@ -3537,7 +3537,10 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {coli_serve_stdio_init();int eos_ids[8];int n_eos = serve_eos(m, snap, eos_ids, 8);- coli_serve_write_ready(stdout, rss_gb());+ /* CAPS between READY and STAT: the gateway reads it in the handshake, so it+ * knows the served modalities before the first request. m->vision is NULL+ * for a text-only container and for a VL config whose tower is missing. */+ coli_serve_write_ready_caps(stdout, rss_gb(), m->vision ? "vision=1" : "vision=0");serve_emap(m);float *logits = xmalloc((size_t)c->vocab * sizeof(float), "logits");/* tok_encode stops at its output capacity: one extra id distinguishesdiff --git a/c/family_registry.py b/c/family_registry.pyindex bffcafad..2da04ed9 100644--- a/c/family_registry.py+++ b/c/family_registry.py@@ -31,6 +31,11 @@ class FamilyCapabilities:grammar_payload: boolaudio_payload: boolthinking: bool+ # The gateway has a placeholder expansion for this family's pictures. Whether+ # the checkpoint being served loaded its tower is the engine's word (the CAPS+ # handshake line, openai_server.Engine.vision), never this bit's: a glm53+ # export can carry vision_config and no model.visual.* tensors.+ image: bool = False@dataclass(frozen=True, slots=True)@@ -1147,7 +1152,7 @@ FAMILIES = (# share COMMON_CAP, which says otherwise -- the flag is descriptive# (it only feeds the capability dict) so nothing broke, but a client# reading it programmatically was told the opposite of the truth.- capabilities=FamilyCapabilities(True, False, False, True),+ capabilities=FamilyCapabilities(True, False, False, True, image=True),has_gateway_adapter=True,has_cli_adapter=True,# Dal chat_template.jinja del checkpoint: nessun a capo, e <think>@@ -1343,7 +1348,7 @@ FAMILIES = (expert_inventory=_individual_expert_inventory(_GLM_EXPERT),config_section="text_config",limits=FamilyLimits(8192, 262144, 1024, 8192, 1, 8, "Q36_MAXT"),- capabilities=FamilyCapabilities(False, False, False, True),+ capabilities=FamilyCapabilities(False, False, False, True, image=True),has_gateway_adapter=True,# coli run stays unwired on purpose: cmd_run dispatches per arch after# this gate, and without a qwen36 branch the engine would inherit GLM's@@ -1376,7 +1381,7 @@ FAMILIES = (fixed_resident_inventory=_qwen38_fixed_resident_inventory,config_section="text_config",limits=FamilyLimits(8192, 262144, 1024, 8192, 1, 1, "Q38_MAXT"),- capabilities=FamilyCapabilities(True, False, False, True),+ capabilities=FamilyCapabilities(True, False, False, True, image=True),has_gateway_adapter=True,# Like Qwen3.6, direct `coli run` is intentionally not exposed until# an engine-specific CLI prompt path exists; chat/serve use the gateway.@@ -1455,7 +1460,7 @@ FAMILIES = (# tools yes (DSML, see v41_dsml.py), grammars no: the engine reads the six-field# SUBMIT header and has no constrained decoder, so a grammar has to be refused# at the gateway rather than desync the wire.- capabilities=FamilyCapabilities(True, False, False, True),+ capabilities=FamilyCapabilities(True, False, False, True, image=True),has_gateway_adapter=True,# coli run stays unwired, for the reason qwen36 gives above and one more:# cmd_run dispatches per arch after this gate, and with no deepseek_v41@@ -1812,5 +1817,6 @@ def public_metadata(family):"grammar_payload": family.capabilities.grammar_payload,"audio_payload": family.capabilities.audio_payload,"thinking": family.capabilities.thinking,+ "image": family.capabilities.image,},}diff --git a/c/glm53.c b/c/glm53.cindex ff19690f..47425233 100644--- a/c/glm53.c+++ b/c/glm53.c@@ -2299,7 +2299,14 @@ static void vision_load(GModel *m) {const Cfg *c = &m->c;m->has_vision = 0;if (c->vis_layers <= 0) return;- if (!st_find(&m->S, "model.visual.patch_embed.proj.weight")) return;+ if (!st_find(&m->S, "model.visual.patch_embed.proj.weight")) {+ /* La config annuncia una torre che il checkpoint non porta: si serve+ * solo testo, e lo si dice qui e al gateway (CAPS vision=0), invece di+ * lasciarlo scoprire a chi manda una foto. */+ fprintf(stderr, "vision_config present but model.visual.* tensors absent: "+ "serving text only, images will be refused\n");+ return;+ }const char *V = "model.visual.";m->vision.config = (ColiVisionConfig){@@ -3682,6 +3689,9 @@ static void serve_loop(GModel *m, Tok *tokenizer) {setvbuf(stdin, NULL, _IONBF, 0);slots_init(m);serve_line("\x01\x01READY\x01\x01\n");+ /* Fra READY e STAT: il gateway lo legge nella stretta di mano, quindi sa+ * che modalita' serve prima della prima richiesta (docs/serve_protocol.md). */+ serve_line("CAPS vision=%d\n", m->has_vision ? 1 : 0);serve_line("STAT 0 0.00 0.0 %.1f\n", rss_gb());/* La griglia va DOPO READY: il lettore di boot del server scarta tutto* fino al sentinel, e colibri.c fa lo stesso (READY, STAT, poi EMAP). */diff --git a/c/openai_server.py b/c/openai_server.pyindex fdab0091..4c2a0cee 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -2403,6 +2403,17 @@ def qwen36_has_vision(model_dir):return isinstance(meta, dict) and isinstance(meta.get("vision"), dict)+def has_image_parts(messages):+ """Whether any message carries a picture part (the shapes expand_*_images() read)."""+ for message in messages if isinstance(messages, list) else ():+ content = message.get("content") if isinstance(message, dict) else None+ if isinstance(content, list) and any(+ isinstance(part, dict) and part.get("type") in ("image_url", "input_image")+ for part in content):+ return True+ return False++def expand_glm53_images(messages, model_dir):"""Sostituisce le parti immagine coi loro segnaposto e ne estrae le patch.@@ -4192,7 +4203,7 @@ def _engine_extension_args(engine_k):return {"logprobs": engine_k, "gbytes_before_ext": True}-def read_engine_turn(stream, sentinel, on_bytes):+def read_engine_turn(stream, sentinel, on_bytes, caps=None):pending = b""while True:byte = stream.read(1)@@ -4208,7 +4219,16 @@ def read_engine_turn(stream, sentinel, on_bytes):on_bytes(pending[:-len(sentinel)])pending = pending[-len(sentinel):]- fields = stream.readline().decode("utf-8", "replace").strip().split()+ # CAPS key=value ... between READY and STAT: what the engine loaded (a vision+ # tower or not), said BEFORE the status line so a server knows the modalities+ # it serves before it takes its first request. Engines that predate the line+ # say nothing, and `caps` stays as the caller left it.+ while True:+ fields = stream.readline().decode("utf-8", "replace").strip().split()+ if fields[:1] != ["CAPS"]:+ break+ if caps is not None:+ caps.update(entry.partition("=")[::2] for entry in fields[1:] if "=" in entry)if len(fields) < 5 or fields[0] != "STAT":raise RuntimeError(f"invalid engine status: {' '.join(fields)}")return {@@ -4514,7 +4534,11 @@ class Engine:self.hits_seq = 0 # latest "TIERS" snapshot from the engineself.profile = collections.deque(maxlen=PROFILE_TURNS) # per-turn phase timingsself.profile_seq = 0- read_engine_turn(self.process.stdout, READY, lambda _: None)+ self.caps = {} # the engine's CAPS handshake line, key=value+ read_engine_turn(self.process.stdout, READY, lambda _: None, self.caps)+ # True/False when the engine said whether it loaded a vision tower; None when+ # it said nothing (an engine that predates CAPS, or a family without a tower).+ self.vision = {"1": True, "0": False}.get(self.caps.get("vision"))self.dispatcher = threading.Thread(target=self._dispatch_stdout,name="colibri-stdout", daemon=True)self.dispatcher.start()@@ -5167,12 +5191,26 @@ class APIServer(ThreadingHTTPServer):rules its engine announced, so a client can build a valid requestwithout trial and error."""entry = model_object(self.model_id, self.created)+ entry["input_modalities"] = self.input_modalities()if is_image_engine(self.engine):info = getattr(self.engine, "info", None) or {}entry["capabilities"] = ["image_generation"]entry["image"] = {key: info.get(key) for key in IMAGE_OPTION_KEYS}return entry+ def input_modalities(self):+ """What a request to this server may carry: text, plus image when BOTH the+ family has a placeholder expansion and the engine said it loaded its tower.+ The family alone is not the truth (a glm53 export can declare vision_config+ and ship no model.visual.* tensors, and the engine then serves text), and+ the engine alone is not either (a tower the gateway cannot feed is no+ modality). An engine that announced nothing is text: the card under-claims+ rather than promising a picture nobody checked."""+ modalities = ["text"]+ if family_by_id(ARCH).capabilities.image and getattr(self.engine, "vision", None) is True:+ modalities.append("image")+ return modalities+def generate(self, prompt, max_tokens, temperature, top_p, on_text, *args, **kwargs):started = time.monotonic()first_output = False@@ -5556,6 +5594,7 @@ class APIHandler(BaseHTTPRequestHandler):if self._is_authed():payload["scheduler"] = self.server.scheduler.snapshot()payload["kv_slots"] = self.server.kv_slots+ payload["input_modalities"] = self.server.input_modalities()payload["continue_assistant"] = os.environ.get("COLI_CONTINUE_ASSISTANT", "1") != "0" and ARCH in CONTINUATION_FAMILIEStiers = getattr(self.server.engine, "tiers", None) if self.server.engine else Noneif tiers: payload["tiers"] = tiers@@ -6712,6 +6751,15 @@ class APIHandler(BaseHTTPRequestHandler):embedding non possono divergere. Both chat endpoints come through here,so a picture is one thing whichever API delivered it."""model_dir = getattr(self.server.engine, "model_dir", None)+ if getattr(self.server.engine, "vision", None) is False and has_image_parts(messages):+ # The engine said at its handshake that it loaded no tower. Refuse here,+ # by name, before the picture is preprocessed and before the engine+ # answers it with a bare BAD_REQUEST (a 500 the client cannot act on).+ raise APIError(400, "this engine loaded no vision tower: the checkpoint declares "+ "one in its config but its weights are not in the container, "+ "so images cannot be served. Reconvert the checkpoint with its "+ "vision weights, or send text only.",+ "messages", "unsupported_content_type")if ARCH == "glm53":messages, images = expand_glm53_images(messages, model_dir)elif ARCH == "deepseek_v41":@@ -7103,6 +7151,13 @@ def serve(model, host="127.0.0.1", port=8000, model_id=None, api_key=None,else:runtime = Engine(engine,model,cap,max_tokens,env,kv_slots,family)server.engine = runtime+ if family.modality != "image":+ # Said once at start-up, so a checkpoint that declares a tower it does+ # not carry is visible in the log and not only in a client's 400.+ print(f"[gateway] input modalities: {', '.join(server.input_modalities())}"+ + (" (the engine loaded no vision tower; a picture gets a 400)"+ if family.capabilities.image and runtime.vision is False else ""),+ file=sys.stderr)print(f"OpenAI-compatible API listening on http://{host}:{port}/v1", file=sys.stderr)signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start())# On Windows SIGTERM is never delivered (os.kill is TerminateProcess);diff --git a/c/qwen36.c b/c/qwen36.cindex 6d2b27a7..a083b213 100644--- a/c/qwen36.c+++ b/c/qwen36.c@@ -4170,6 +4170,9 @@ static void serve_loop(Model *m){coli_serve_binary_mode();setvbuf(stdin,NULL,_IONBF,0);fputs("\x01\x01READY\x01\x01\n",stdout);+ /* fra READY e STAT: il gateway lo legge nella stretta di mano, quindi sa che+ * modalita' serve prima della prima richiesta (docs/serve_protocol.md) */+ printf("CAPS vision=%d\n",m->vis_ready?1:0);printf("STAT 0 0.00 0.0 %.2f\n",rss_gb());fflush(stdout);emap_emit(m); /* dopo READY e STAT: il boot reader legge STAT dopo il sentinel */diff --git a/c/qwen38.c b/c/qwen38.cindex 494f0b38..3edb0b83 100644--- a/c/qwen38.c+++ b/c/qwen38.c@@ -1811,6 +1811,9 @@ static void serve_loop(Model *m){fprintf(stderr,"[serve] unable to allocate QSA state\n");return;}fputs("\x01\x01READY\x01\x01\n",stdout);+ /* between READY and STAT: the gateway reads it in the handshake, so it knows+ * the served modalities before the first request (docs/serve_protocol.md) */+ printf("CAPS vision=%d\n",m->vis_ready?1:0);printf("STAT 0 0.00 0.0 %.2f\n",rss_gb());fflush(stdout);serve_emap(m); /* after READY and STAT: the boot reader discards what precedes them */diff --git a/c/serve_codec.h b/c/serve_codec.hindex ae15a77b..35444da5 100644--- a/c/serve_codec.h+++ b/c/serve_codec.h@@ -358,14 +358,25 @@ static inline ColiServeReadResult coli_serve_read_command(return coli_serve_read_command_alloc(input, profile, command, malloc);}-static inline int coli_serve_write_ready(FILE *output, double rss_gb)+/* The handshake, with an optional CAPS line between READY and STAT: what the+ * engine loaded, as "key=value ..." (today `vision=0|1`). It sits BEFORE the+ * status line on purpose: the server reads it while it waits for STAT, so it+ * knows what it serves before the first request arrives. NULL writes the+ * handshake exactly as coli_serve_write_ready() always has. */+static inline int coli_serve_write_ready_caps(FILE *output, double rss_gb, const char *caps){if (fputs("\x01\x01READY\x01\x01\n", output) == EOF ||+ (caps && fprintf(output, "CAPS %s\n", caps) < 0) ||fprintf(output, "STAT 0 0.0 0.0 %.2f 0 0\n", rss_gb) < 0)return 0;return fflush(output) == 0;}+static inline int coli_serve_write_ready(FILE *output, double rss_gb)+{+ return coli_serve_write_ready_caps(output, rss_gb, NULL);+}+static inline int coli_serve_write_accept(FILE *output, const char *id, int prompt_tokens){return fprintf(output, "ACCEPT %s %d\n", id, prompt_tokens) >= 0 &&diff --git a/c/tests/glm53_serve_harness.py b/c/tests/glm53_serve_harness.pyindex abab16ce..6709fb6f 100644--- a/c/tests/glm53_serve_harness.py+++ b/c/tests/glm53_serve_harness.py@@ -72,6 +72,8 @@ def handshake(process):if "READY" not in ready:raise AssertionError(f"prima riga {ready!r}, atteso il sentinello READY")stat = read_line(process.stdout)+ while stat.startswith("CAPS "): # CAPS vision=<0|1> sits between READY and STAT+ stat = read_line(process.stdout)if not stat.startswith("STAT "):raise AssertionError(f"seconda riga {stat!r}, atteso STAT")diff --git a/c/tests/glm53_vision_serve_harness.py b/c/tests/glm53_vision_serve_harness.pyindex 381a219d..c7224706 100644--- a/c/tests/glm53_vision_serve_harness.py+++ b/c/tests/glm53_vision_serve_harness.py@@ -111,7 +111,12 @@ def main() -> int:if "READY" not in read_line(process.stdout):print("FAIL: nessun READY")return 1- read_line(process.stdout) # STAT+ line = read_line(process.stdout) # CAPS vision=<0|1>, then STAT+ while line.startswith("CAPS "):+ line = read_line(process.stdout)+ if not line.startswith("STAT "):+ print(f"FAIL: dopo READY {line!r}, atteso STAT")+ return 1first = ask(process, 1, prompt, images[0])second = ask(process, 2, prompt, images[1])process.stdin.close()diff --git a/c/tests/test_family_registry.py b/c/tests/test_family_registry.pyindex a41ac219..ea2aa36c 100644--- a/c/tests/test_family_registry.py+++ b/c/tests/test_family_registry.py@@ -121,6 +121,23 @@ class FamilyRegistryTest(unittest.TestCase):json.dumps(public_metadata(family))self.assertIn(family.id, by_id)+ def test_capabilities_carry_the_image_bit_for_families_with_an_image_path(self):+ # The bit says the gateway has a placeholder expansion for the family. Whether+ # the checkpoint being served actually loaded its tower is the engine's word+ # (the CAPS handshake line), never the family's: a glm53 export can carry+ # vision_config and no model.visual.* tensors.+ by_id, _ = _build_registry(FAMILIES)+ for family_id, expected in (("glm53", True), ("qwen38", True), ("qwen36", True),+ ("deepseek_v41", True), ("glm", False), ("kimi", False),+ ("inkling", False), ("olmoe", False),+ ("deepseek_v4", False), ("qwen_image", False)):+ with self.subTest(family=family_id):+ self.assertIs(by_id[family_id].capabilities.image, expected)+ self.assertIs(public_metadata(by_id[family_id])["capabilities"]["image"],+ expected)+ # the four positional flags keep their meaning for every existing caller+ self.assertFalse(FamilyCapabilities(True, False, False, True).image)+def test_glm53_exposes_engine_kv_slot_limit(self):by_id, _ = _build_registry(FAMILIES)self.assertEqual(by_id["glm53"].limits.max_kv_slots, 16)diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex 72eaf450..22feeb23 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -1495,6 +1495,19 @@ class ProtocolTest(unittest.TestCase):self.assertEqual(stats["prompt_tokens"], 7)self.assertTrue(stats["length_limited"])+ def test_reads_caps_between_ready_and_stat(self):+ # A vision engine says what it loaded BEFORE its status line, so the gateway+ # knows the served modalities before it answers its first request. An engine+ # that says nothing leaves the dict empty and the status parse untouched.+ caps = {}+ stream = io.BytesIO(READY + b"CAPS vision=1 other=x\nSTAT 0 0 0 0\n")+ stats = read_engine_turn(stream, READY, lambda _: None, caps)+ self.assertEqual(caps, {"vision": "1", "other": "x"})+ self.assertEqual(stats["completion_tokens"], 0)+ caps = {}+ read_engine_turn(io.BytesIO(READY + b"STAT 0 0 0 0\n"), READY, lambda _: None, caps)+ self.assertEqual(caps, {})+def test_rejects_invalid_kv_pool_before_engine_start(self):with self.assertRaisesRegex(ValueError, "kv_slots"):serve("/missing", kv_slots=0)@@ -7208,5 +7221,99 @@ class DispatcherLogprobTailTest(unittest.TestCase):self.assertEqual(echoes[0]["topk"], [])+class EngineCapsTest(unittest.TestCase):+ def test_engine_learns_its_vision_tower_from_the_handshake(self):+ # CAPS vision=<0|1> sits between READY and STAT; an engine that predates the+ # line (or has no tower to speak of) leaves the flag unknown, not False.+ for line, expected in ((b"CAPS vision=1\n", True), (b"CAPS vision=0\n", False),+ (b"", None)):+ with self.subTest(line=line):+ process = FakeProcess(lambda _process, _frame: None)+ process.stdout = BlockingStream(READY + line + b"STAT 0 0 0 0\n")+ with patch("openai_server.ARCH", "glm53"), \+ patch("openai_server.subprocess.Popen", return_value=process):+ engine = Engine("glm53", "model")+ try:+ self.assertIs(engine.vision, expected)+ finally:+ engine.close()+++class ServedModalityTest(unittest.TestCase):+ """What /v1/models says it accepts is what the engine loaded. The tower is a+ property of the checkpoint (a glm53 export can carry vision_config and no+ model.visual.* tensors), not of the family, so the card follows the engine's+ handshake, and a picture sent to an engine that announced no tower is refused+ by name at the gateway instead of dying in the engine as a bare BAD_REQUEST."""++ def serve(self, vision):+ engine = FakeEngine()+ if vision is not None:+ engine.vision = vision+ server = APIServer(("127.0.0.1", 0), engine, "test-model", "secret", 16, kv_slots=1)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()++ def stop():+ server.scheduler.close()+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ self.addCleanup(stop)+ return engine, f"http://127.0.0.1:{server.server_port}"++ def request(self, base, path, body=None):+ headers = {"Authorization": "Bearer secret"}+ data = None+ if body is not None:+ data = json.dumps(body).encode()+ headers["Content-Type"] = "application/json"+ return urlopen(Request(base + path, data=data, headers=headers), timeout=2)++ def test_card_and_health_report_the_live_tower(self):+ with patch("openai_server.ARCH", "glm53"):+ for vision, expected in ((True, ["text", "image"]), (False, ["text"]),+ (None, ["text"])):+ with self.subTest(vision=vision):+ _engine, base = self.serve(vision)+ with self.request(base, "/v1/models") as response:+ card = json.load(response)["data"][0]+ self.assertEqual(card["input_modalities"], expected)+ with self.request(base, "/v1/models/test-model") as response:+ self.assertEqual(json.load(response)["input_modalities"], expected)+ with self.request(base, "/health") as response:+ self.assertEqual(json.load(response)["input_modalities"], expected)++ def test_a_family_without_an_image_path_never_claims_images(self):+ # Even an engine that announces a tower is text-only to its clients when+ # the gateway has no placeholder expansion for the family.+ with patch("openai_server.ARCH", "glm"):+ _engine, base = self.serve(True)+ with self.request(base, "/v1/models") as response:+ self.assertEqual(json.load(response)["data"][0]["input_modalities"], ["text"])++ def test_tower_less_engine_refuses_a_picture_by_name(self):+ picture = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ with patch("openai_server.ARCH", "glm53"):+ engine, base = self.serve(False)+ with self.assertRaises(HTTPError) as caught:+ self.request(base, "/v1/chat/completions", {+ "model": "test-model",+ "messages": [{"role": "user", "content": [+ {"type": "text", "text": "what is this?"}, picture]}]})+ self.addCleanup(caught.exception.close)+ self.assertEqual(caught.exception.code, 400)+ error = json.load(caught.exception)["error"]+ self.assertIn("vision tower", error["message"])+ self.assertEqual(error["param"], "messages")+ self.assertEqual(engine.calls, []) # refused before the engine+ # the same engine still serves text+ with self.request(base, "/v1/chat/completions", {+ "model": "test-model",+ "messages": [{"role": "user", "content": "hello"}]}) as response:+ self.assertEqual(response.status, 200)+ self.assertEqual(len(engine.calls), 1)++if __name__ == "__main__":unittest.main()diff --git a/c/tests/test_serve_codec.c b/c/tests/test_serve_codec.cindex de93dde9..51d81e06 100644--- a/c/tests/test_serve_codec.c+++ b/c/tests/test_serve_codec.c@@ -197,6 +197,26 @@ static void test_writer_golden_bytes(void)fclose(output);}+/* The handshake with a CAPS line: what the engine loaded, said between READY+ * and STAT so the server knows it before it takes a request. NULL caps must+ * produce the handshake byte for byte as before. */+static void test_ready_caps_golden_bytes(void)+{+ FILE *output = tmpfile();+ assert(output);+ binary_stream(output);+ assert(coli_serve_write_ready_caps(output, 1.25, "vision=1"));+ assert(coli_serve_write_ready_caps(output, 1.25, NULL));+ static const unsigned char expected[] =+ "\x01\x01READY\x01\x01\nCAPS vision=1\nSTAT 0 0.0 0.0 1.25 0 0\n"+ "\x01\x01READY\x01\x01\nSTAT 0 0.0 0.0 1.25 0 0\n";+ unsigned char actual[sizeof(expected) + 16];+ size_t count = read_output(output, actual, sizeof(actual));+ assert(count == sizeof(expected) - 1);+ assert(memcmp(actual, expected, count) == 0);+ fclose(output);+}+static void test_allocation_failures_are_fatal_to_the_caller(void){static const char frame[] = "SUBMIT req 0 1 1 0.7 0.95\nx\n";@@ -219,6 +239,7 @@ int main(void)test_submit_and_controls();test_invalid_headers_and_bodies();test_writer_golden_bytes();+ test_ready_caps_golden_bytes();test_allocation_failures_are_fatal_to_the_caller();puts("serve codec tests: ok");return 0;diff --git a/docs/serve_protocol.md b/docs/serve_protocol.mdindex b90ad88a..bbd0b0a4 100644--- a/docs/serve_protocol.md+++ b/docs/serve_protocol.md@@ -19,6 +19,7 @@ summarized at the end. Line formats below are quoted from the emitting `printf`s```\x01\x01READY\x01\x01+CAPS vision=<0|1>STAT 0 0.00 0.0 <rss_gb>HWINFO <cores> <ram_total_gb> <ram_avail_gb> <ngpu> <vram_total_gb> <cpu_name>|<gpu_name>TIERS <vram_experts> <ram_experts> <disk_experts> <vram_gb> <ram_gb>@@ -29,6 +30,14 @@ The server must not send requests before `READY`. `HWINFO`/`TIERS`/`EMAP` aretelemetry (see below) and may grow — **servers must ignore line kinds they do notrecognize**; that is the protocol's forward-compatibility rule.+`CAPS key=value ...` is optional and sits *between* `READY` and `STAT`: it says what+the engine actually loaded, and the server reads it while waiting for `STAT`, so the+served modalities are known before the first request. Today the one key is `vision`+(`1`: a vision tower is loaded; `0`: none — a text-only checkpoint, or a config that+declares a tower whose tensors are not in the container). Engines that say nothing+leave the server's flag unknown. glm53, qwen38, qwen36 and deepseek_v41 emit it;+`openai_server.py` derives `/v1/models` `input_modalities` from it.+## Requests (server → engine)```@@ -98,6 +107,7 @@ turn: `HWINFO`, `PERF`, `ENTROPY`, `GPUS`, `TIERS`, `EMAP`, `HITS` (formats belo|---|---|---|| `TIERS` | `TIERS <vram> <ram> <disk> <vram_gb> <ram_gb>` | expert count per tier + resident bytes || `HWINFO` | `HWINFO <cores> <ram_total> <ram_avail> <ngpu> <vram_total> <cpu>\|<gpu>` | host snapshot (GBs are floats) |+| `CAPS` | `CAPS key=value ...` | handshake only, between `READY` and `STAT`: what the engine loaded (`vision=0\|1`) || `EMAP` | `EMAP <rows> <cols> <hex>` | one byte per expert, row-major over `rows×cols` (sparse layers +MTP × experts): `byte = (tier<<6) \| heat` — 2-bit tier (0 disk / 1 RAM / 2 VRAM), 6-bit log₂-bucketed usage heat || `HITS` | `HITS <rows> <cols> <hex>` | 1 bit per expert, experts routed since the previous `HITS` || `PERF` | `PERF <id> <dt> <t_edisk> <t_ewait> <t_emm> <t_attn> <t_kvb> <t_head>` | this turn's PROFILO deltas, seconds |