#!/usr/bin/env python3 """Keepalive proxy in front of SGLang, vLLM or llama.cpp (v6.62). No content logging, and the only rewriting is the tool-schema guard (role 4); two routes, POST /v1/systemone (role 5) and the operator's POST /proxy/stop (role 7), are answered here instead of relayed. Ten roles, nothing else: 1. fill the silences of the SSE stream (SGLang's tool-call parser buffers the arguments: 127 s of measured silence for a 400-line file write) by injecting the OFFICIAL Anthropic "ping" event every KEEPALIVE_S seconds on the Anthropic dialect (an SSE comment ": keepalive" KILLS Claude-family parsers: measured 2026-08-23, client death 10-20 s after the first comment) and an authentic empty chunk on the OpenAI dialect (opencode/AI SDK stall detectors ignore comments and drop the stream after ~140-180 s without a real chunk). It starts before the engine answers: SGLang sends a stream's headers with its first chunk, after the queue and the prefill, so past KEEPALIVE_S without them the proxy opens the stream itself (v6.31); 2. never leave a generation running for a client that is gone: the proxy names every request itself (x-override-rid), POSTs /abort_request BEFORE it closes the upstream socket, and drains the answer when the engine offers no rid to abort with. The caller of a non-streamed answer, who hears nothing until it is whole, is watched instead: when it leaves, the upstream is ended, and the engine drops the request on its own. So is the caller of a stream until the engine answers (v6.31): a request queued behind a full KV pool otherwise stayed in the engine's queue after its caller had gone; 3. never lull a client on a dead upstream: past MAX_SILENCE_S an EXPLICIT SSE error event is sent, then the stream is closed. MAX_SILENCE_S must stay ABOVE the worst legitimate prefill (40 min measured for 690K tokens on a cold cache), hence the 3600 s default; 4. keep one tool schema from killing a whole session: the 'pattern' values that Python's re cannot compile are dropped from tool parameter schemas, because the engine validates them with a Python regex and 400s the request otherwise. Nothing else in the body is ever touched; 5. answer typed decisions on POST /v1/systemone (the wire contract of TypeSafe's Jev) from the lane behind it: one single-token completion per question, the option labels read off top_logprobs, so a pipeline or an agent gets choice, score and yes/no probabilities from the model it already runs, with nothing generated and nothing parsed. The "System One endpoint" section below carries the design and its receipts; 6. keep a request through an engine restart: one that arrives while the engine does not answer and its unit (PROXY_HOLD_UNITS) is on its way back waits for it, at most PROXY_HOLD_MAX_S, instead of failing at once. A streamed one hears from the proxy at once (200, then the keepalives of role 1), but on the Ollama routes, whose NDJSON carries no keepalive: those wait in silence, as a non-streamed one does; see "Holding a request"; 7. stop every generation when the cockpit's memory floor asks (POST /proxy/stop, from this machine with the engine's key): each client's connection is cut, not ended, so that it never takes a cut answer for a whole one, and after a stop that cut one, new generations wait while the box is short of memory (see "The memory floor's stop" below); 8. say in the journal when a tool call's arguments name a host of Cohere's report (TOOL_TARGETS: Alibaba Cloud's OSS domain, under which its Routify relay sits, and the cloud metadata addresses), whatever the client, but in a tool that reads, searches or writes files (QUIET_TOOLS): the host family and the tool's name, never the arguments, and the answer relayed as it came. The cockpit turns the line into a banner (docs/agents-and-network.md); 9. say in the journal when a client sends again a long prompt it left without an answer (RESENT): how long it had waited, how many times in a row, and what widens the client's timeout. The cockpit turns the line into a banner (docs/clients.md); 10. on a box with pair.json (discussion #45), send each generation that names one of this repo's lanes' models to the box of the pair that serves it, a peer's own proxy with that over TLS both ways (each box's certificate pinned by the other, PAIR_PORT). A lane name no box serves, and any other name, stays on this box, as on a box alone (decision 986). GET /v1/models lists every box's models (see "Two boxes behind one endpoint" below). A model both boxes serve is shared: a conversation stays on the box that holds its prefix, a new one goes to the box with the fewest requests in flight (v6.52, docs/pair.md). v6.62: the Inkling 2 Mini lane, on SGLang under the name inkling-2-mini, is a lane of the pair's routes, its template reads a reasoning effort itself, none included (its lowest, 0.0), so a request's "none" reaches it as it came instead of becoming the Qwen templates' enable_thinking false, which it does not read (it reasoned at its default, high), and POST /v1/systemone is refused while it serves: its card says its lowest effort does not turn the reasoning off, so the first token, the one System One reads its options' labels off, is its thought's. And an image costs, while it serves, what its processor counts (INKLING_VISION_NAMES): one token per 40-pixel cell, each side rounded up, plus 3, with no size clamp, where the Qwen-VL sizing the guard charged stopped at 16,386 tokens and an 8000x6000 photo costs 30,003 (code review of v1.59.0, measured on the reference box, 2026-11-24). v6.61: the Liquid AI LFM3 lane, on vLLM under the name lfm3-1.7b, is a lane of the pair's routes, and its template, which reads enable_thinking alone as Ornith's does, gets a request's reasoning effort the way Ornith's gets it (ornith_effort): none and minimal turn the reasoning off, every other level keeps it. pi and opencode send it none and high, the two states it holds. System One stays refused there, as on every vLLM lane. v6.60: the Liquid AI LFM2.5 24B-A2B lane, on SGLang under the name lfm2.5-24b-a2b, is a lane of the pair's routes, and POST /v1/systemone is refused while it serves (400, the lanes it serves on named): its chat template opens a thought at every answer and reads no switch (enable_thinking, reasoning_effort), so the first token, the one System One reads its options' labels off, is its thought's, and those labels were measured on the Qwen tokenizer alone. v6.59: a client is told the box transcribes speech while the NVIDIA Nemotron Transcribe lane serves (v1.51): llama.cpp's server on a port of its own, which holds the GPU instead of a text engine the way the image and video lanes do, and a text request then read "It is stopped, restarting or still loading (about 9 minutes)" of an engine that comes back only by a switch. Nothing reaches that lane through this proxy: it answers its own audio routes on its own port. v6.58: a client is told the box serves images while either image lane serves: the MiniMax-H3-Image lane, a second one beside Qwen-Image 2.1, holds the GPU instead of a text engine the same way, and a text request then read "It is stopped, restarting or still loading (about 9 minutes)" of an engine that comes back only by a switch. The message names the image lane's unit that serves. v6.57: a GGUF lane's checkpoint is its file. One revision of Unsloth's repository holds every quantization of the model, and the Unsloth lane serves two of them under one name (v1.49.0): read as the revision alone, a box on UD-Q4_K_XL and one on UD-IQ3_XXS shared their requests as one checkpoint (decision 1018), and a Load from one to the other was no change of checkpoint (decision 1041). llama-server's -m names a file of the snapshot: its checkpoint is the SHA-1 of the revision and that file's path, 40 hexadecimal characters as the pair carries a revision. A box on v6.56 or older serving that lane says the revision alone, and shares nothing with this one: two boxes of one pair update together. The other engines' --revision is read as before. v6.56: a client's bearer reaches every engine spelled the way the engine spells it. The door reads the scheme in any case, as SGLang's own check does (measured 2026-10-08: "bearer " admitted) and v6.38 only stripped the whitespace around the value, but llama.cpp compares the "Bearer " prefix exactly: the same well-formed key sent lowercase came back 401 "Invalid API Key" on the Unsloth lane (measured 2026-11-12) while every SGLang and vLLM lane served it. The door has already compared the key byte for byte (engine_admits), so the relay normalizes the scheme alone, and only when the value is exactly what the door admits: one space, the key after it. And X-Conversation-Id stays at the door: llama-server attaches a request carrying it to a resumable stream that stops when the stream is cancelled, never when its connection closes (server-stream.cpp, b12291; found in review of v1.48.0), so closing, the abort of the llama.cpp lanes (CLOSE_ABORTS), and the memory floor's stop left it running to its end. v6.55: the Qwen3.8 Flash-Next Unsloth GGUF lane (v1.48), served by llama.cpp's llama-server, which names itself "llamacpp" on /v1/models. Like vLLM it has none of SGLang's info, load or abort routes, and it stops a request whose connection closes, streamed or not (its server-context.cpp and server-queue.cpp, b12291): closing is its abort there too (CLOSE_ABORTS). Its window is the context of a slot, which its /v1/models row says (meta.n_ctx), and its pool the windows of all its slots (/props total_slots); a prompt is counted by its own routes (its chat count route, its /tokenize's content, /v1/messages/count_tokens); its names are one more flash model's (the flash ceiling holds, but past a window of 262,144, as on the FP4-Local lane: wide_flash), and System One says which lanes it serves on, as on vLLM. A reasoning effort of "none" becomes enable_thinking false, as on the other Qwen lanes (qwen_effort_none). The pair reads its unit's command as it reads the others': its name by --alias, its checkpoint by the snapshot its -m names, its requests at once by -np (names_in, revision_in, slots_in). v6.54: the Qwen3.8 Flash-Next FP4-Local lane at its 1M window (FLASH_LOCAL_CONTEXT=1m, v1.45.2) has no flash ceiling: its engine's window, read on /v1/models with the names it serves (served_window), says so, and its prompts are bounded by the pool's share (wide_flash). v6.53: an SSE answer's end is read as its engine sends it, whatever its client's pace (v1.44.0, decisions 1106 to 1109). The thread that reads the engine never waits for the one that writes the client: the answer waits in a spool bounded at PROXY_SPOOL_MAX_MIB (32), past which the generation stops and the client is cut (CLIENT TOO SLOW). The engine's death, cut or end is decided as it is read: out of every stop's reach, the order read once in systemd, the request bound or the other box told, the relay only writing what was decided. A stop counts a generation once, ends a running vLLM answer's upstream at once, and takes the generations that go out while it is under way. The entry of a pair reads what the other box sends PAIR_ORDER_GRACE_S after every client that leaves, for a death and an order (decision 1112). v6.52: two boxes that serve one model share its requests (role 10, decisions 996 to 998). A request for a model this box serves, which the other box of its pair serves too, goes to the box it shares its longest known prefix with (fingerprints of its first 4 KiB, 8 KiB, 16 KiB and so on, kept 10 minutes per box) when that covers 30 % of it or 32 KiB, else to the box with the fewest requests in flight (each box says in the list it gives the other how many generations it runs, x_alzeo_running, how many of them the other box sent, x_alzeo_running_yours, and how many its lane runs at once, read in its unit, x_alzeo_slots), and to that one whenever the box it would go to runs more than half its lane's slots ahead of the other, and 1.5 times as many (decision 1014). A box that refuses it before a byte went out hands it back. One that does not answer (PAIR_SHARE_CONNECT_S for its connection) or says 503 or 529 then gets no shared request for PAIR_SPREAD_COOL_S, one that finds the prompt too long for its pool still gets the shorter ones. What this box refuses before it sends (its memory floor, a prompt too long for its pool, a long prompt its warming engine cannot measure), and what its engine refuses at the first try (connection refused, 502, 503, 504), goes to the other box. A request whose answer began, a token count, and a request with X-Alzeo-Here: 1 stay on the box they were sent to. Only a box that serves a model from the same checkpoint shares it (decision 1018): each box says the one its engine runs, read in the command its engine was started with (x_alzeo_revision; PAIR_CHECKPOINT when no unit says it), and a request sent on carries the entry's (X-Alzeo-Pair-Checkpoint), which the other box refuses with a 409 when it serves another. A request the other box had whole and closed the connection on runs nowhere else, its client told 503 (decision 1017). One an engine closed the connection on, or died with, goes to that engine's box or nowhere for PAIR_KILLER_KEEP_S (decision 1019); a stop ordered to the lane's unit, an Abort all or the memory floor binds nothing, and a box that ends so a request the other box sent tells it before the cut (X-Alzeo-Pair-Ended, decision 1031); a restart binds as an engine's death (decision 1030). v6.51: a request body is JSON in UTF-8, or a 415: in UTF-16 or UTF-32, which the vLLM lanes read too (FastAPI's json, where the SGLang lanes' orjson refuses it), the guards here found none of the fields they look for. A client of a listed key never names the engine's request id, as the other box of a pair since v6.50, and neither names it in a header (x-override-rid, vLLM's X-Request-Id) or in any form an engine reads one from a body: "rid" (written with escapes too, a batch's list too), "request_id", the Vertex route's "parameters". A body that may hold one and cannot be read whole gets a 400. SGLang aborts every request whose id starts with one it aborts, when its client leaves too: ids "0" to "f" in any of them ended every generation of the box. v6.50: two boxes behind one endpoint (role 10, discussion #45, decisions 961-966). A box whose config directory holds pair.json reads its peers' /v1/models (every PAIR_TTL_S seconds, and again when a peer answers 409 that it serves another model now), sends a generation that names a model of one of this repo's lanes to the box that serves it, and answers a lane name no box serves with its own lane, as a box alone does (decision 986). The boxes talk over TLS both ways (decisions 971-978, as NVIDIA PAIR's nodes do): each has a certificate of its own, made by pair.py, which the other pins in its pair.json, and a box of a pair listens on PAIR_PORT (30002) for its peers only, a connection without a pinned certificate refused right after its handshake. A request that comes in there is a hop from the box of its certificate: served where it lands or refused (409), never sent on again. The certificate is the pair's only credential: no box holds the other's API key, which is also its cockpit's login, and the pair port takes the generation routes and GET /v1/models only, admitted to this box's engine with this box's own key, and the summary of this box its tile shows. The port is opened within seconds of pair.json naming a peer and closed once it names none: nothing restarts. Nothing changes on a box without pair.json. v6.49: a long prompt sent again after its client gave up on it is said in the journal (role 9). On the Ornith lane a prompt of 494,089 tokens the prefix cache could not serve took 19 min before its first token, and Claude Code with its own default timeouts left it after 620 s, twice, then sent it without streaming and left after 300 s, twice: each time, the request was closed (nobody waited for it) and the engine lost part of the prompt it had computed, so the answer came at the fifth attempt, after 35 min (the reference box, 2026-10-30, issue #61). The journal said CLIENT GONE, then the same body again, and nothing else. Now a client that leaves a request of at least RESEND_MIN_BYTES after RESEND_MIN_S without an answer has its prompt (the system, messages and tools, hashed, whatever it asks of the answer: Claude Code's retries move from a stream to none) kept for RESEND_WINDOW_S, and the same prompt arriving within it is written as "RESENT the prompt its client left without an answer after N s", with the client's name from its User-Agent and what widens its timeout. Nothing relayed changes. v6.48: a tool call that names a host of Cohere's report is said in the journal (role 8). Cohere reported on 2026-10-26 that Qwen3.8-Flash-Next, given a shell in an agent test, sent a PUT to an Alibaba Cloud OSS bucket in Beijing. The proxy sees each tool call before the client runs it: the arguments of every call, put back together from a stream (the OpenAI tool_calls deltas, Anthropic's input_json_delta, the Responses API's function_call_arguments) or read from a whole answer, are matched against TOOL_TARGETS when the request ends, and a match is written as "TOOL TARGET in a call", with nothing of the arguments. A tool that reads, searches or writes files, or hands work to a sub-agent, is not read: a page quoting these hosts, or a search for them, is no request to them. Nothing relayed changes. v6.47: the memory floor's stop (role 7). SGLang ends an aborted generation as a finished one, end_turn on /v1/messages and finish_reason "abort" on the OpenAI routes, so a client of the cockpit's memory floor got the part generated before the stop as its whole answer: Claude Code kept a compaction summary cut in the middle of a word (the reference box, 2026-10-25), and Hermes, the Anthropic SDK's stream and LiteLLM do the same. The cockpit's stop comes here now: each generation relayed is stopped (by rid on SGLang, by closing its connection on vLLM, where the floor could stop nothing) and its client is cut, and after a stop that cut one, for the floor's pause and then while MemAvailable stays under the floor (PROXY_FLOOR_EPISODE_S at most), a new generation is refused with 529 overloaded_error (503 off /v1/messages) and the cause. Memory alone refuses nothing. On the OpenAI routes a stream the engine ends with finish_reason "abort", whatever aborted it, is cut instead of relayed. v6.46: a body the proxy writes again for the engine keeps its text as UTF-8. Seven guards parse a body and write it again (the reasoning effort routes, the Qwen, Nemotron and Ornith effort translations, the tool schema patterns, the model name on vLLM), and the prompt counter writes the text it sends the engine's tokenizer. They wrote it with json.dumps' default, which escapes every character outside ASCII: a Chinese character took 6 bytes instead of 3 and an emoji 12 instead of 4, so the engine got a body two to three times the one sent, the proxy held it at 5.65 and 7.98 times its size while its guards worked on it, against 3.98 for an image as base64 (reference box, 2026-10-24, 24 MiB bodies sent as UTF-8; 3.98 and 3.99 now), and the counter measured a prompt against COUNT_BODY_MAX_BYTES at that inflated size. They write it through rewritten(), in UTF-8; a lone surrogate, which a JSON escape allows and UTF-8 cannot carry, keeps its escape. The door opens /health, /ready and /metrics themselves, where it opened every path under them as the engine does: /health_generate, which runs a one-token generation on an idle engine, was relayed from the network with no key (D02 of the 2026-10-24 security review). It and every other path under those three need the key now, and the SGLang units of this repo turn off the generation that /health itself ran (SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATION=0). A peer on the network has HEADER_BYTES_MAX (64 KiB) for a request's line and headers in all, where the standard parser bounded each line and their number but not their sum, about 6.4 MiB a connection before any key (D03); past it, 431. A body on /health, /ready or /metrics, which take none, is refused unread (413), and a network peer's body that sends no byte for BODY_STALL_S (30 s) is let go with its room in the budget, where it held both for 900 s a byte (D04). v6.45: the Ornith 1.5 122B lane (Ornith AI's model on vLLM) takes a reasoning effort as its chat template reads it, enable_thinking alone: none and minimal turn the reasoning off, every other level keeps it whole, as the box decided (2026-10-21). Its template reads no effort, and a "none" handed to it as it came left the reasoning on. A level that turns it off wins over the request's own enable_thinking, as on the Qwen lanes: omp sends enable_thinking true beside its level. v6.44: the corruption tripwire reads vLLM's reasoning too. vLLM streams the thinking as delta.reasoning, which the guard did not read: on the Flash FP4-Local lane, a Qwen lane on vLLM whose token id 0 is "!", a decode that lost its state while it reasoned went unseen (found in review, 2026-10-20). v6.43: the Flash FP4-Local lane (NVIDIA's FP4 build of the flash model, on vLLM) is a Qwen lane: the flash lane's one-prompt ceiling holds while it serves, as its window is the flash lane's, and a reasoning effort of "none" becomes enable_thinking false there as on SGLang, since its chat template is the flash lane's and refuses "none" (vLLM hands the template a "none" sent inside chat_template_kwargs as it came). System One says which lanes it serves on, on any vLLM lane. v6.42: what a cloud review of the repository found open, closed (2026-10-18). The identity wall reads the Bearer scheme in any case, as the engine and the door do; a caller's x-override-* headers stay at the door, the rid aside, as the SGLang lanes start their engine with the header overrides on; the relay's pump no longer returns from a finally, which Python 3.14 warns of. Its unit gives it no more of the machine than it uses (no new privileges, the system and the homes read-only, no capability, the system calls of a service, docker's socket out of reach) and holds 2G, as a body costs it about four times its bytes while the guards work on it. v6.41: what a review of the repository found open, closed (2026-10-17). The network's share of the port is bounded: another machine holds at most PROXY_MAX_CONN_PER_ADDRESS connections open, the network PROXY_MAX_REMOTE_CONN, and such a connection has CLIENT_HEADER_S in all for its request's headers; the bodies in flight share BODY_BUDGET_BYTES, a compressed body is refused (415). Behind the identity wall a client key reaches the routes that generate, count and read, not the engine's operator routes; a redirect from the engine is relayed, never followed. /v1/score's token ids are bounded and its label_token_ids refused like token_ids_logprob; a video is priced at SGLang's own ceiling where a prompt can wedge the engine, the media of an uncountable body as media; token ids past every lane's vocabulary wait while it is unknown; the counting routes have a ceiling of their own; a held request is judged again for the engine that comes back; and an abandoned /v1/messages answer is aborted on an SGLang lane that takes the request id override. v6.40: the Nemotron lane (NVIDIA's Bolt on vLLM) takes a reasoning effort as its chat template reads it, enable_thinking and medium_effort: none and minimal turn the reasoning off, low and medium ask its shorter one, high and above its default. vLLM handed the template a top-level "none" it does not read, and the answer came back inside the reasoning, its content null (measured 2026-10-15); pi and the OpenAI SDKs send the field so. v6.39: an engine that has neither of SGLang's info routes is not asked them again. Every read of the pool on the Kolibri lane (vLLM) began with /server_info and /get_server_info, two 404s, and the hold's probe asked /server_info each time it looked: the proxy notes that this engine has none, reads vLLM's own facts at once, and probes /health there, which on vLLM generates nothing. A new engine (any restart, any lane switch) is asked again (found in review, 2026-10-14), and so is one that took the port with no start the proxy saw (a proxy told no unit to watch): the first read that finds it is not vLLM drops what was read from the vLLM engine and goes back to SGLang's routes (the review of the fix, the same day). v6.38: the client's key reaches the engine without the whitespace around it. The spaces around a header's value are not part of it (RFC 9110, section 5.5), and SGLang reads it so: a key sent as "Bearer " passed on a Qwen lane. The proxy forwarded the header as it came, and vLLM's own check, like the Kolibri lane's (vllm_engine_auth.py), compares the value exactly: the same client got a 401 there (the production checks after v1.29.0, 2026-10-14). v6.37: the Kolibri lane serves on vLLM behind this door, and four things SGLang does that vLLM does not are now asked of the engine instead of assumed. Its /v1/models says which one serves ("owned_by": "vllm"). vLLM has neither /server_info nor /get_server_info: the pool and the window come from its /metrics (cache_config_info's kv_cache_size_tokens, the figure its boot log prints) and its /v1/models (max_model_len), where without them every body past 256 KiB was held as "not measured yet" for good. vLLM stops a request whose connection closes (measured 2026-10-14: one running before the client left, none 0.5 s after, no token in the next 2 s, the stream and the plain answer alike): a client that leaves closes the upstream there, where it was drained up to DRAIN_MAX_S for want of an /abort_request. vLLM refuses a model it does not serve (404) where SGLang answers any name: a body naming another model is given the served one, so a client keeps working across a lane switch as it always did. And what was learned of one engine is dropped with it: the vocabulary (Kolibri's is 128,000 tokens, every Qwen lane's 248,320; the probe now names the served model, which vLLM requires, and reads vLLM's wording too) and whether the engine honours x-override-rid, once its unit starts again. The name is given again on every attempt (a request held through Kolibri's boot went with its old one), and after a switch nobody asked about (the last lane's facts stayed 600 s). The connection of a client that left is shut down, not only closed: a close waited for the stream's next byte, which during a long prefill is its first token. And the engine a request went to is noted when it goes: a dropped fact made an abandoned Kolibri stream take SGLang's /abort_request and drain. System One needs a Qwen lane (its labels are measured on the Qwen tokenizer) and says so on Kolibri, a 400, where it failed as a 502. v6.36: a path under /ready passes the door without a key, as the engine leaves it open (its auth rule opens /health, /ready and /metrics; the door had /health and /metrics only, so a readiness probe got 401 here and 200 from the engine, found 2026-10-11). v6.35: a lane switch is followed at once, request or not. The pool, the window and the names read from the engine were kept 600 s and dropped only by a request that found the engine gone, so after a switch made while no request came, a lane that boots in less than 600 s served its first minutes under the stopped lane's: the 27B, which boots in about 7 min on the reference box, refused every prompt past the flash lane's 250,000 ceiling for up to 2.5 min and /v1/systemone answered as the flash (found 2026-10-08), and a restart of the 27B kept the pool of the boot before. The units the installed proxy names in PROXY_HOLD_UNITS are now asked for their invocation id when those facts are read, at most every 2 s, and a new one, which systemd gives every start, drops them. A proxy that names no unit keeps them its 600 s, as before. v6.34: the serving key is checked before a body is read. The README promises that the key is this port's one gate, and a caller without it still had its body read whole (up to MAX_BODY_BYTES) and, past the size guard's nomination line, counted by the engine on the proxy's own key, before the engine's 401. Without the identity wall, a request now has to carry what the engine's own check admits (the same rule, measured on the live engine), or it gets the engine's own 401 at once; /health and /metrics stay open, as the engine keeps them. Where the engine would accept a prompt past the share of its pool the size guard lets through (the 27B lane: 863,638 tokens accepted, 794,552 usable), the guard nominates a body by a bound, not an average: a token is at least one byte, so a body counts as its length in bytes until the engine's count says otherwise (2.5 bytes a token let digit-heavy text through uncounted, and a prompt in that zone wedges the scheduler); where the engine's window is under that share, it refuses past it itself. And token_ids_logprob is refused where the engine reads it: on a batch that mixes it with an ordinary request, the served build's scheduler dies (sglang#34719). v6.33: an answer relayed from the engine carries one Server header and one Date. The proxy writes its own, and relayed the engine's beside them (uvicorn's `server: uvicorn` and `date`): two of each on every relayed answer, which RFC 9110 (5.3) does not allow. aiohttp refuses such an answer by default in 3.13.4, and in its strict mode (python -X dev) since then, so a LiteLLM gateway in front of the proxy answered "Duplicate 'Server' header found." (issue #39, 2026-10-06). The engine's two are no longer relayed, as the cockpit's agent relay already did. v6.32: /server_info no longer carries the engine's key anywhere. v6.24 took SGLang's key fields out of the answer, at the top and in every internal state, but the answer also repeats the engine's whole command line in launch_command, the key included (the flash lane on the reference box, found by the audit of 2026-10-03): a named client behind the wall could still read the one secret the wall keeps from it. The value of every key flag is now masked in every string of the answer, and the engine's key itself wherever it shows; the TLS key password field goes with the key fields. v6.31: a stream is kept, and watched, before the engine answers. SGLang holds a stream's status and headers back until its first chunk, after the request was queued and its prompt computed, and this proxy wrote nothing before them and did not watch the caller. On 2026-10-03, eight agents whose contexts (771,301 tokens at 01:00) overflowed the KV pool (437,184) waited longer than opencode's 300 s for headers; opencode gave up and sent again, and each request it gave up on stayed queued until the engine reached it, computed its prompt for nobody, and was aborted at the proxy's first write: 704 between 01:24 and 11:36, and 163 requests in the queue at the end, for eight agents. Now the caller of a stream is watched until the engine answers, and its leaving ends the upstream, which the engine sees within 4 s; past KEEPALIVE_S the stream is opened and kept alive, as a hold does; past MAX_SILENCE_S without the engine's first byte the request is dropped, as a silent stream is. v6.30: a level SGLang refuses at the top of a request that also names one in chat_template_kwargs is dropped. SGLang takes the chat_template_kwargs copy over the top-level one, so the top-level copy changed nothing but the answer, a 400 from its validation: omp's default dialect sends both (omp 18.4.9, 2026-10-01). The level the client put in chat_template_kwargs is kept, a null there is filled as an absent one is, and a top-level level SGLang accepts is still left alone. v6.29: a body that never arrived whole is not sent on. A caller that closed before the last byte of its body (a reset at once after sending, or a client dying mid-send) left the proxy a short read, and the proxy sent the engine what had come: of 300 requests closed so, 11 were read short and sent on all the same. No engine can serve that, so nothing was generated, but no request should go out so. It now ends "CLIENT GONE before its body", and the engine is not asked. (The engine still sees a body cut short when the proxy closes its side as the request goes out, its caller gone: by design, the engine never has it.) v6.28: a request is held while its engine comes back (issue #26). systemd starts a crashed engine again 15 s after it stops, and the boot takes 7 to 11 min; every request of that window got a 503 at once, and the clients gave up long before the engine was back: opencode 1.18.32 retried a 503 six times on its Retry-After and failed the session after 151 s (measured against a fake engine, 2026-10-01). Now a request that finds the engine not answering, while a unit named in PROXY_HOLD_UNITS is starting, between two attempts, up, or in the stop half of a restart, waits for it. A streamed request gets its 200 and the role-1 keepalives at once, which opencode and Claude Code both waited on for 400 s and then took the answer; a non-streamed one waits in silence. Should the request still fail once the wait is over (the engine not back within PROXY_HOLD_MAX_S, or the prompt too long for the lane that came back), a stream the proxy opened ends with an error event, and both clients then send it again (measured), to an engine that now answers. With no unit named, nothing waits. An engine's mid-stream cut now reaches the client as a cut, with no error event and no closing chunk: Claude Code sends a cut stream again as a stream, which the hold keeps alive, where the error event made it retry without one, held in silence, which it gave up on after about 330 s (an engine made a zombie under real clients on the reference box, 2026-10-01). v6.27: the second pass of the same review found the guards still judgeable by value type. The engine's request models (pydantic v2, lax) coerce "999999", 999999.0 and [-1] spelled as strings into the ints the scheduler then acts on, and the guards only read the raw JSON type, so the crash shapes were one pair of quotes away (verified against the installed build: n, logprobs, top_logprobs, top_logprobs_num, and the elements of stop_token_ids, input_ids and prompt). The guards now judge each value as the engine reads it (_engine_int), and the vertex route also judges parameters.sampling_params, which the scheduler spreads into SamplingParams. Found in review, 2026-09-26. v6.26: the review's three open guard findings, closed. S4: a key spelled with a \\u escape (e.g. \\u0074op_logprobs) carried none of the bytes the guards scanned for, so the ceiling and the token-id refusals were skipped; any \\u in the body now forces the parse. S5: the sampling and logprob guards also cover /v1/responses, /invocations and /vertex_generate, read input_ids as a batch of lists, read sampling_params as a list, read prompt as token ids on /v1/completions, and the oversize guard reaches /generate and the other non-/v1/ generation routes. S6: the TLS handshake no longer runs in the accept loop (one silent connection parked every other client behind its timeout); it now runs in the connection's own thread on its own budget, and a handshake that dies leaves one journal line, no traceback. Found in review, 2026-09-24; fixed 2026-09-26. v6.25: a caller that leaves a non-streamed answer stops the generation. The proxy waited inside the upstream call for the whole answer, so it never saw that caller go and kept the upstream open: the engine worked to the end (measured on the box, a 69k-token prefill and its decode ran 53.6 s past the caller), then got an abort that found nothing to abort. The caller's socket is watched during that wait now, and at its EOF the upstream is ended: SGLang checks its own HTTP client every 4 s for a non-streamed request and drops it (the same prefill stopped 4.0 s after the caller left). A non-streamed body the engine ends early is no longer relayed as complete: the client sees the cut, as it would from the engine itself. An Anthropic body is counted by the engine's own /v1/messages/count_tokens, tools included and screenshots priced from their headers wherever they sit: five screenshots in tool_result blocks were counted 2,044,251 tokens and refused, for 28,463 served. A raw control or non-ASCII byte in a query is a 400 instead of a dropped socket; the values logged once are remembered as digests, in bounded memory, and an effort level is printed short; and a client named by the identity wall is named on the line that opens its request too, in one word. And the flash lane's one-prompt ceiling follows the lane that serves, by its model's name (FLASH_PROMPT_CEILING_TOKENS), instead of being moved by a switch, with a restart, while the old lane still served. Found in review, 2026-09-24. v6.24: the identity wall covers every route and every method but /health (it looked at POST /v1/... only, while the engine's key went upstream on everything relayed, so GET /server_info, /generate, /flush_cache and /abort_request needed no listed key); a path still escaped after one decode is refused, since SGLang decodes again before it routes; relayed /server_info answers lose the engine's key fields in both modes; and an unreadable keys file says so instead of "missing, malformed or empty". Found in review, 2026-09-24. v6.23: the pool is read from /server_info, and from the deprecated /get_server_info only on an engine that answers 404 to the new route. SGLang logs a deprecation warning for each call of the old one, on the 27B image and the flash image alike, and says it will go. v6.22: an engine that is gone because the box switched to its image lane says so. The text engine is stopped on purpose by that switch and nothing brings it back until someone switches back, so "stopped, restarting or still loading (about 9 minutes)" sent clients to wait for an engine that was not coming. The error path, and only it, asks systemd whether an image lane is active (at most every 5 s) and names the way back (v6.58: the two of them, qwen38-image and qwen38-image-h3). v6.21: PROXY_BIND chooses the interface this proxy answers on, and it answered on every one of them before. Seven days of journal on the reference box: 8,288 requests, all from 127.0.0.1, because the clients that need it run on the same machine. The default does not move, since somebody else's laptop may legitimately point at this port. v6.20: the request fields SGLang leaves unbounded and dies on rather than refusing are refused here instead. top_logprobs (chat), logprobs (completions) and top_logprobs_num (/generate) past a ceiling: the number reaches logprobs.topk(max_k) unexamined and, past the vocabulary, raises "selected index k out of range" inside the scheduler, which ends the engine for every client (sglang#40076, open; reproduced on the reference box). And the family sglang#31597 catalogued in July, whose two fixes were closed without being merged: a stop_token_ids or input_ids entry past the vocabulary indexes a scatter_add_ or the embedding out of bounds, and n expands a list before anything is scheduled. The vocabulary is learned from the one place the engine states it, the message refusing an out-of-range logit_bias; when that probe fails the guard stands down rather than refuse traffic it cannot judge, and a negative id is refused either way. v6.19: POST /v1/systemone, typed decisions with the Jev wire contract, served by the lane this proxy fronts. One chat completion of one token per question, options as single-token letters, probabilities from top_logprobs, the state as the shared prefix the radix cache reuses. top_logprobs on /v1/chat/completions and never token_ids_logprob on /generate: on the served build the latter kills the scheduler on the first batch that mixes it with an ordinary request (sglang#34719), and a shared lane mixes on every step. Jev's three aliases resolve to the served model and every other name is refused the way the hosted API refuses it, so the TypeSafe SDK runs here with one base URL changed and a bad request reads the same: 422 with a detail list that names the path that failed, 400 for a request that parses and cannot be served, each shape probed case by case against api.typesafe.ai. v6.18: a reasoning-effort level the chat template knows but SGLang's request model does not is relayed through chat_template_kwargs instead of being refused at the door. Nothing in SGLang's own enum is touched. v6.17: the identity wall learns the second half of its job. v6.16 named WHO; admission is a separate question, and forwarding the client's token verbatim meant a labeled request met the engine's own --api-key and died there: the wall identified everyone and admitted no one (found live on the reference box, not in a test: the fake engines enforce nothing, the real one does). QWEN38_UPSTREAM_API_KEY names the engine's key to the proxy; when both are set, the client's bearer names them on the journal line and the engine's key admits them upstream, on relays and on abort calls alike. Without it the old verbatim behavior stays, and the banner warns loudly: an engine with no key check of its own, or one shared key on purpose, changes nothing. v6.16: two walls operators kept building in front of this box, built in but opt-in. Optional TLS: name a certificate with QWEN38_TLS_CERT (and QWEN38_TLS_KEY when the key is a separate file) and the listening socket speaks it; unset changes nothing for the loopback and tailnet users this box is designed for. Optional per-client identity: QWEN38_CLIENT_KEYS_FILE is a JSON map of bearer token to label; when set, a /v1/ request without a listed key gets 401 in its own dialect, /health stays open for monitoring, and the label rides every journal line of that request (who sent what, the question one shared key can never answer). A keys file that is missing, malformed or empty makes the unit refuse to start: an identity wall that vanished silently is worse than no wall. What the engine sees is v6.17's business now (which key admits a named client); naming them is this version's. v6.15: an image costs what it costs, and a refusal a client can act on. The oversize guard charged every media part a flat 4,096 tokens. Measured against this engine at twelve sizes, an agent screenshot really costs 880 (1280x720) to 1,562 (1680x950), so a session holding 24 of them carried ~61,000 tokens of context it was not using: on 2026-09-12 a 139,868-token conversation was refused as "200,684 prompt tokens". Every oversize refusal this box has logged was such a session. The guard now reads the image header (PNG, JPEG, GIF, WebP) and prices it with the vision tower's own geometry (patch 16 x merge 2, clamped into the processor's pixel range), exact at all twelve sizes; the flat budget survives only for what has no readable header. The refusal also says "the prompt is too long" and carries error.code=context_length_exceeded, because a client that does not recognise the refusal as an overflow just resends the same prompt: opencode did, twice, 3 s apart. v6.14: an abandoned request no longer becomes a zombie. Three holes, all measured here on 2026-09-09 (6,582 flood lines in one day, one request decoding 6 minutes for nobody): a client that gave up during prefill left a request the proxy could not name, because it learned the rid from the first SSE event; the Anthropic dialect's id (msg_) was sent to /abort_request although it names nothing the engine knows; and the abort was fired in a thread that raced the socket close, which is what deletes the state the abort needs (sglang #35255, in main since 2026-09-04 and in neither image this repo serves). The proxy now imposes the rid with x-override-rid on the routes that honour it, aborts synchronously before closing, and on /v1/messages, where the engine mints its own id and applies no header overrides, drains the answer to its end instead of orphaning it. v6.13: Claude Code's Artifact tool carries an ECMA-262 'pattern' with Unicode property escapes ([^\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}...]). SGLang validates every tool schema with jsonschema, whose 'regex' format check compiles patterns with Python's re, which raises "bad escape \\p": the engine answered 400 to EVERY request of the session (measured 09/09 against Claude Code v2.1.266, sglang serving_chat.py:868). The proxy drops the patterns Python cannot compile and forwards the rest untouched. v6.12: the tripwire trips at 128 marker characters (48 is a plausible banner line in a code block; 128 is not something a model writes, and real corruption runs to max_tokens), and the OpenAI dialect gets "data: [DONE]" after the error event so a strict client sees a terminated stream, not a truncated one. v6.11: a corruption tripwire. A decode kernel that loses its state on this hardware emits runs of token id 0, which is "!" in the Qwen tokenizer (sglang#36537, #36558, #36806, #36845). The proxy counts consecutive marker characters across the stream and, past CORRUPTION_RUN of them, aborts the generation upstream and sends the client an explicit error instead of a wall of exclamation marks. It reads only the delta text it already relays; nothing is logged or rewritten. v6.10: the cached KV pool is dropped whenever the engine proves unreachable or a refresh read fails. It was cached for 600 s and invalidated nowhere, so after an engine restart the oversize guard enforced the previous engine's limit for up to ten minutes; the pool is a boot lottery and differs by lane (about 863k on 27B against 184k on flash), so a prompt accepted against a stale larger pool could be relayed to a smaller engine and wedge its scheduler. v6.9: an engine that does not answer (stopped, crashed, restarting, loading) gets a 503 engine_unavailable with Retry-After on EVERY path, never a false context_too_long: on 30/08 the size fallback refused a 68k-token request as "~409k tokens" while the engine was restarting after a GPU fault. Unknown request shapes still refuse on size. v6.8: oversize guard counts with the engine tokenizer (size only nominates), 8 percent margin, absolute per-lane prompt ceiling (PROMPT_CEILING_TOKENS). v6.7: abort_request on client loss. v6.6: upstream reads via read1() and TCP_NODELAY on the client side. resp.read(8192) on chunked HTTP BLOCKS until 8 KB (~30 SSE events) accumulate before relaying them at once: measured 2026-08-23, median inter-event gap 0 ms / max 1307 ms through the proxy vs a steady 118 ms direct. read1() returns as soon as bytes are available, so the stream stays token by token. """ import base64, collections, concurrent.futures, hashlib, hmac, http.client, io, ipaddress, json, math, os, queue, re, select, socket, ssl, string, subprocess, sys, threading, time, urllib.parse, urllib.request, urllib.error, uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class EngineUnreachable(Exception): """The engine did not answer /tokenize: stopped, crashed, restarting or still loading.""" # The image and video lanes hold the GPU instead of a text engine once the box is # switched to one of them, and a text engine does not come back from that by itself. # Asked only on the error path, where the answer changes what the client is told, # and at most every 5 s per lane. Two image lanes (v6.58): Qwen-Image 2.1 and MiniMax-H3-Image. IMAGE_UNITS = ("qwen38-image.service", "qwen38-image-h3.service") _IMAGE_SEEN = {u: {"ts": -1e9, "active": False} for u in IMAGE_UNITS} VIDEO_UNIT = "qwen38-video.service" _VIDEO_SEEN = {"ts": -1e9, "active": False} # and the NVIDIA Nemotron Transcribe lane (v6.59), a speech recognizer on a port of its own TRANSCRIBE_UNIT = "qwen38-transcribe.service" _TRANSCRIBE_SEEN = {"ts": -1e9, "active": False} def _lane_active(unit: str, seen: dict) -> bool: now = time.monotonic() if now - seen["ts"] > 5: try: seen["active"] = subprocess.run(["systemctl", "is-active", "--quiet", unit], timeout=2).returncode == 0 except Exception: seen["active"] = False seen["ts"] = now return seen["active"] def image_lane_serving(): """The unit of the image lane that serves, or None.""" return next((u for u in IMAGE_UNITS if _lane_active(u, _IMAGE_SEEN[u])), None) def video_lane_serving(): return _lane_active(VIDEO_UNIT, _VIDEO_SEEN) def transcribe_lane_serving(): return _lane_active(TRANSCRIBE_UNIT, _TRANSCRIBE_SEEN) # ── Holding a request while its engine comes back (v6.28, role 6) ────────── # Only the units the installed proxy names count: a proxy run by hand or by a test, with # PROXY_HOLD_UNITS unset, answers an absent engine at once, as it always did. HOLD_UNITS = tuple(os.environ.get("PROXY_HOLD_UNITS", "").split()) HOLD_MAX_S = float(os.environ.get("PROXY_HOLD_MAX_S", "1200") or 0) HOLD_POLL_S = float(os.environ.get("PROXY_HOLD_POLL_S", "2") or 2) # An engine that answers again and still fails the request (its info route is up, its # generations still 503: a boot not quite done) gets it again this many times, each after a # pause. Without the bound and the pause, the request went back to it in a loop with no # sleep until PROXY_HOLD_MAX_S (found in review before v6.28 shipped). HOLD_ROUNDS_MAX = 10 _HOLD_SEEN = {"ts": -1e9, "coming": False} _HOLD_LOCK = threading.Lock() # The systemd jobs that end with the unit started. A restart runs its stop half as the unit # "deactivating" under a job of type restart, and a stop under one of type stop (both read # from `systemctl list-jobs` on the reference box, 2026-10-01). _BACK_JOBS = ("start", "restart", "try-restart", "reload-or-start") def engine_coming(): """True when a unit named in PROXY_HOLD_UNITS is starting, waiting for its next attempt, up, or stopping only to start again: a restart. A hold that ended on the restart's stop half sent every waiting client an error to answer (seen 2026-10-01, when the cockpit restarted an engine left without its scheduler). systemd is asked at most every 2 s.""" if not HOLD_UNITS or HOLD_MAX_S <= 0: return False return text_lane_coming() def text_lane_coming(): """engine_coming's reading of systemd, whatever the hold's settings: a unit named in PROXY_HOLD_UNITS up, starting, waiting for its next attempt, or stopping to start again. False when none is named.""" if not HOLD_UNITS: return False with _HOLD_LOCK: now = time.monotonic() if now - _HOLD_SEEN["ts"] > 2: try: out = subprocess.run(["systemctl", "show", *HOLD_UNITS, "-p", "ActiveState", "--value"], capture_output=True, text=True, timeout=3).stdout.split() coming = any(st in ("active", "activating", "reloading") for st in out) if not coming: coming = any(kind in _BACK_JOBS for _, kind in unit_jobs()) _HOLD_SEEN["coming"] = coming except Exception: _HOLD_SEEN["coming"] = False _HOLD_SEEN["ts"] = now return _HOLD_SEEN["coming"] def engine_answers(path=None): """True when the engine answers at all: any status under 500 on its info route (path: on that one). A held request may go then; 5xx is SGLang starting or stopping, and no answer is no engine.""" try: headers = {"Authorization": f"Bearer {_api_key()}"} except OSError: headers = {} # a 401 still says an engine is there # v6.39: an engine without SGLang's info routes (vLLM) is probed on /health, which there # generates nothing req = urllib.request.Request(UPSTREAM + (path or _INFO_ROUTE["path"] or "/health"), headers=headers) try: urllib.request.urlopen(req, timeout=10).read() return True except urllib.error.HTTPError as e: return e.code < 500 except Exception: return False def unit_jobs(): """[(unit, job type)] of the jobs systemd runs or has queued on the units named in PROXY_HOLD_UNITS, from `systemctl list-jobs` (JOB UNIT TYPE STATE); [] when none is named or systemd does not say.""" if not HOLD_UNITS: return [] try: out = subprocess.run(["systemctl", "list-jobs", "--no-legend", "--no-pager", *HOLD_UNITS], capture_output=True, text=True, timeout=3).stdout except Exception: return [] return [(f[1], f[2]) for f in (ln.split() for ln in out.splitlines()) if len(f) >= 3 and f[1] in HOLD_UNITS] def unit_stopping_by_order(): """True while systemd stops a unit named in PROXY_HOLD_UNITS by order: a job of type stop (the cockpit's Load of another lane, its Stop button, an operator's systemctl stop). The engine closing a request then is that order, not what the request did: an ordered stop bound every request in flight to its box for 10 minutes (decision 1019, found in review, 2026-11-04). A restart is no such order, whoever asked for it (decision 1030, 2026-11-04): the cockpit restarts an engine a request may have wedged (autoheal, zombie), and a request bound then waits here for its engine to come back. But a restart whose unit starts another checkpoint than the one this box served last is the cockpit's Load of another checkpoint of the same lane, an order too (decision 1041, 2026-11-04), unless the cockpit makes it to recover the engine (recovery_runs): its autoheal and zombie restarts (decision 1049). A crash has no job until its restart is due. False when systemd does not say.""" marked = recovery_runs() # before the jobs: a run read after them may be the restart's next one jobs = unit_jobs() if any(kind == "stop" for _, kind in jobs): return True served = _LAST_LANE["lane"][1] for unit, kind in jobs: if kind in ("restart", "try-restart") and served and not marked.get(unit): nxt = revision_in(unit_start_texts(unit)) if nxt and nxt != served: return True return False # Decision 1049 (2026-11-04): the cockpit says which restarts it makes to recover an engine, each with the run it restarts # (the unit's InvocationID) and when, from the job that runs it (cockpit.py, run_job): such a restart is never an order, # whatever checkpoint it loads. RECOVERY_FILE = os.path.expanduser(os.environ.get("QWEN38_RECOVERY_FILE") or "~/.config/qwen38/recovery-restarts.json") RECOVERY_MARK_S = 600.0 # a mark older than this is not the recovery under way RECOVERY_START_S = 120.0 # its restart leaves active this soon after the mark, or it is another restart's def recovery_runs(): """{unit: True} for each unit named in PROXY_HOLD_UNITS whose run the cockpit restarts now to recover its engine: its mark names the unit's run, is younger than RECOVERY_MARK_S, and the unit left active, or changed state, within RECOVERY_START_S of it. A mark the cockpit left behind (its restart refused) made a later Load of that run a recovery, and a run read after the jobs could be the restart's next one, the recovery then an order (the 5th review of v1.43.0, 2026-11-04). {} when nothing says so; no systemctl without a fresh mark.""" try: with open(RECOVERY_FILE, encoding="utf-8") as f: marks = json.load(f) except Exception: return {} now, found = time.time(), {} for unit, mark in (marks.items() if isinstance(marks, dict) else ()): at = mark.get("at") if isinstance(mark, dict) else None if unit not in HOLD_UNITS or not isinstance(at, (int, float)) or not 0 <= now - at < RECOVERY_MARK_S: continue try: out = subprocess.run(["systemctl", "show", unit, "-p", "InvocationID", "-p", "ActiveExitTimestamp", "-p", "StateChangeTimestamp", "--timestamp=unix"], capture_output=True, text=True, timeout=3).stdout props = dict(ln.split("=", 1) for ln in out.splitlines() if "=" in ln) except Exception: continue # the restart it was written for: the unit left active (ActiveExitTimestamp, set once as the restart begins), # or changed state, after the mark and within RECOVERY_START_S. A mark the cockpit left behind (stopped between # the mark and the restart, a removal that failed) counted for the next restart of that run, and the Load of # another checkpoint then bound what it ended (the 7th review of v1.43.0). The last change alone moves with each # step of a stop (systemd's unit_notify stamps every low-level state), and a stop slower than RECOVERY_START_S # outlived its mark (the 8th review, 2026-11-05) if props.get("InvocationID") and mark.get("invocation") == props["InvocationID"] \ and any(at - 2 <= t <= at + RECOVERY_START_S for t in (unix_stamp(props.get("ActiveExitTimestamp")), unix_stamp(props.get("StateChangeTimestamp"))) if t is not None): found[unit] = True return found def unix_stamp(value): """A timestamp systemctl show printed with --timestamp=unix ("@1730757600"), or None (empty, "n/a", missing).""" try: return float(str(value).strip().lstrip("@")) except (TypeError, ValueError): return None def with_scripts(text): """A command and the scripts it names, their comments left out: what a lane's engine runs ([] for no command). A script is read whatever its bytes: one edited by hand in Latin-1 raised out of every reader of the unit, and the request then asking died with no answer (the 4th review of v1.43.0, 2026-11-04).""" if not text: return [] found = [text] for script in re.findall(r"(/\S+\.sh)\b", text): try: with open(script, encoding="utf-8", errors="replace") as f: found.append("\n".join(ln for ln in f.read().splitlines() if not ln.lstrip().startswith("#"))) except OSError: pass return found def unit_start_texts(unit): """What a unit's next start runs: its ExecStart and the scripts it names ([] when systemd does not say, or for a unit that is no lane's: PROXY_HOLD_UNITS names them).""" if unit not in HOLD_UNITS: return [] try: out = subprocess.run(["systemctl", "show", unit, "-p", "ExecStart", "--value"], capture_output=True, text=True, timeout=3).stdout.strip() except Exception: return [] return with_scripts(out) def engine_gone_reason(): """What an unanswering engine means on this box, and what brings it back.""" image = image_lane_serving() if image: return (f"This box is serving images right now ({image}), and a text engine " "does not come back by itself: switch back to a text lane from the cockpit's " "switcher, or run ./switch-model.sh with a text target") if video_lane_serving(): return ("This box is serving video right now (qwen38-video.service), and a text engine " "does not come back by itself: switch back to a text lane from the cockpit's " "switcher, or run ./switch-model.sh with a text target") if transcribe_lane_serving(): return ("This box is transcribing speech right now (qwen38-transcribe.service), and a text engine " "does not come back by itself: switch back to a text lane from the cockpit's " "switcher, or run ./switch-model.sh with a text target") return "It is stopped, restarting or still loading (a restart takes minutes, about 9 on a DGX Spark)" # The interface this proxy listens on. It answered on every one of them until v6.21, and # on the reference box seven days of journal showed 8,288 requests, every last one from # 127.0.0.1: the clients that need it (opencode, Claude Code, the cockpit) run on the # same machine. An interface nobody uses is an interface worth not opening, so an # operator can close it, and the default stays what it was because someone else's laptop # may legitimately point at this port. BIND = os.environ.get("PROXY_BIND", "0.0.0.0").strip() or "0.0.0.0" UPSTREAM = os.environ.get("UPSTREAM", "http://127.0.0.1:30000") KEEPALIVE_S = float(os.environ.get("KEEPALIVE_S", "10")) MAX_SILENCE_S = float(os.environ.get("MAX_SILENCE_S", "3600")) CLIENT_IO_S = float(os.environ.get("CLIENT_IO_S", "900")) # write blocked toward a frozen client TLS_HANDSHAKE_S = float(os.environ.get("QWEN38_TLS_HANDSHAKE_S", "10")) # A TLS client that connects and then says nothing must not pin a handshake thread (or, # before S6, the accept loop itself) open for CLIENT_IO_S; the handshake gets this # short, separate budget. # Oversize guard (v6.7): a prompt longer than the engine's KV pool is not rejected by # this SGLang build, it wedges the scheduler (measured 29/08). The proxy learns the # pool size from /get_server_info once the upstream is healthy and refuses, with a # clear 400, a body the engine's own count puts past it. # Where the engine would accept a prompt that can wedge it (see wedge_possible), which bodies # get counted is decided by a bound (v6.34): a token is at least one byte, so no body can be # more tokens than it has bytes, and one that fits by its byte length fits. It was 2.5, an # average: prose runs 3.4 to 4.6 bytes a token on the served tokenizer, but digits are one # token each, so a body of numbers went through uncounted at well over twice its estimate. # A value at or under 0 would divide by nothing. CHARS_PER_TOKEN_MIN = float(os.environ.get("CHARS_PER_TOKEN_MIN", "1.0")) if CHARS_PER_TOKEN_MIN <= 0: CHARS_PER_TOKEN_MIN = 1.0 # The average this guard used before v6.34. It still nominates where no wedge is possible # (the engine refuses past its own window), and it judges a body the engine cannot count (a # shape its tokenizer refuses), so those paths decide as they did. It is not a bound, which # is why it never refuses a body the engine has counted. NOCOUNT_CHARS_PER_TOKEN = 2.5 # Usable share of the pool for one prompt: the rest is room for the answer and the # scheduler's own buffers. The 92 percent comes from the flash lane as it was in v1.5: # with a 178,560-token pool a single prompt topped out near 165K (CHANGELOG v1.5.x). OVERSIZE_MARGIN_FRAC = float(os.environ.get("OVERSIZE_MARGIN_FRAC", "0.08")) # Absolute ceiling for one prompt, in tokens (0 = none). The KV pool is not the only limit: # on the flash lane the prefill of a long prompt grows the engine's footprint by ~0.27 GiB # per 1k tokens beyond ~90k (measured 29/08), so the ceiling that keeps the box away from # the memory edge is a token count set per lane by install.sh, not a share of the pool. PROMPT_CEILING_TOKENS = int(os.environ.get("PROMPT_CEILING_TOKENS", "0") or 0) # The flash lane's own ceiling, applied while the flash lane is what serves (v6.25), which # the served model's name says. It was PROMPT_CEILING_TOKENS above, set per install and # moved by switch-model.sh at switch time with a proxy restart, while the old lane still # served: a switch to flash queued behind a 27B serving 1M refused every prompt past # 250,000 until the next boot, and the restart cut every stream in flight (found in review, # 2026-09-24). PROMPT_CEILING_TOKENS stays, as a ceiling on any lane. FLASH_PROMPT_CEILING_TOKENS = int(os.environ.get("FLASH_PROMPT_CEILING_TOKENS", "0") or 0) FLASH_SERVED_NAMES = frozenset({"qwen3.8-flash-next", "qwen3.8-flash-next-fp4", "qwen3.8-flash-next-unsloth"}) # The Qwen lanes vLLM serves (v6.43): the Flash FP4-Local lane, the flash model in NVIDIA's FP4 # build, with the flash lane's chat template. Named one by one: a lane vLLM serves under another # name (Kolibri, the Nemotron lanes) has a template of its own, and its bodies go as they came. QWEN_VLLM_NAMES = frozenset({"qwen3.8-flash-next-fp4"}) # The Qwen lanes llama.cpp serves (v6.55): the Unsloth GGUF lane, whose template is the GGUF's with the Qwen lanes' fixes # (patch-template.py --gguf), named one by one as above. QWEN_LLAMACPP_NAMES = frozenset({"qwen3.8-flash-next-unsloth"}) # The engines that stop a request whose connection closes, and have none of SGLang's abort routes (v6.55): vLLM # (measured 2026-10-14) and llama.cpp's llama-server, whose wait for an answer, streamed or not, ends with its HTTP # client and cancels its task (read in its server-context.cpp and server-queue.cpp, b12291, 2026-11-12). Closing is # their abort, and draining would keep a generation going for nobody. CLOSE_ABORTS = frozenset({"vllm", "llamacpp"}) # Hard ceiling on one request body, in bytes (0 = none). The oversize guard # below measures prompt bodies once they are read; without a cap a lying or broken # Content-Length in the gigabytes is allocated before anything is counted, # and a non-numeric one kills the handler thread with a ValueError (measured: # the client gets zero bytes back and the journal only says "no outcome"). # 256 MiB is ~100x the largest legit text request on the 1M lane and leaves # heavy vision payloads room. MAX_BODY_BYTES = int(os.environ.get("MAX_BODY_BYTES", str(256 * 1024 * 1024)) or 0) # Every body in flight at once, in bytes (2026-10-16; 0 = none). MAX_BODY_BYTES caps one body # and nothing capped them together: each is read whole and parsed again by the guards, and four # legitimate bodies near the cap reached the unit's MemoryMax of 1G at once, where the kernel kills # the proxy and every stream in flight with it (found in review, 2026-10-16; the unit holds 2G # since 2026-10-18, as a body costs the proxy about four times its bytes). Past this budget a # body is not read: 503 with Retry-After, which the SDKs and the agents retry. A body arriving # when none is in flight is always read, so a budget under the cap never refuses one forever. BODY_BUDGET_BYTES = int(os.environ.get("BODY_BUDGET_BYTES", str(384 * 1024 * 1024)) or 0) # A body at or under BODY_SMALL_BYTES is always read and holds none of the budget; a larger one # takes its bytes from it as they arrive, BODY_SMALL_BYTES at a time (2026-10-17). The budget was # taken whole on the Content-Length before a byte was read, and kept to the end: a key holder # announcing large bodies and sending nothing held all of it, and every other body, the box's own # clients' included, got a 503 (found in review, 2026-10-17). A larger body that finds no room on # its way is refused then, except the oldest one being read, which waits up to BODY_WAIT_S for # the room the others give back: two bodies read at once could otherwise each keep the other out # until both were refused. BODY_SMALL_BYTES = int(os.environ.get("BODY_SMALL_BYTES", str(1024 * 1024)) or 0) BODY_WAIT_S = float(os.environ.get("BODY_WAIT_S", "30") or 0) # A network peer's body that sends no byte for BODY_STALL_S is let go, and the room it held in # BODY_BUDGET_BYTES goes back at once (2026-10-24): read under CLIENT_IO_S, a body held its thread # and that room for 900 s a byte (D04 of the 2026-10-24 security review). Only while the body comes # in: the engine's prefill and the answer come after it, and the proxy then reads nothing from the # client but its leaving. Loopback keeps CLIENT_IO_S. BODY_STALL_S = float(os.environ.get("BODY_STALL_S", "30") or 0) _BODY_BUDGET = {"used": 0, "seq": 0} _BODY_READERS = set() # the admission numbers of the larger bodies being read now _BODY_BUDGET_LOCK = threading.Lock() _BODY_ROOM = threading.Condition(_BODY_BUDGET_LOCK) # Time to first response byte from the upstream on GETs (models, health, load: # always fast or dead). Generations keep no deadline: a cold 690k-token # prefill legitimately takes tens of minutes to answer, streaming or not, and # any finite timeout there would break that flagship use case. UPSTREAM_GET_TIMEOUT_S = float(os.environ.get("UPSTREAM_GET_TIMEOUT_S", "30")) def lane_ceiling(): """The one-prompt ceiling for the lane that serves now (0 = none): PROMPT_CEILING_TOKENS on any lane, and the flash lane's own while it serves. A lane that cannot be told gets the flash one too, when it is set: a refusal a client can retry is the cheaper mistake, the ceiling being what keeps a long flash prefill off the memory edge.""" ceiling = PROMPT_CEILING_TOKENS if FLASH_PROMPT_CEILING_TOKENS > 0: try: served = set(served_models()) except EngineUnreachable: served = set() if not served or (served & FLASH_SERVED_NAMES and not wide_flash(served)): ceiling = FLASH_PROMPT_CEILING_TOKENS if ceiling <= 0 else min(ceiling, FLASH_PROMPT_CEILING_TOKENS) return ceiling # The flash lanes that serve past the model's own window by YaRN: the FP4-Local lane (FLASH_LOCAL_CONTEXT=1m, v1.45.2) # and the Unsloth GGUF lane (its installer's CTX and YARN, 2026-11-12). WIDE_FLASH_NAMES = QWEN_VLLM_NAMES | frozenset({"qwen3.8-flash-next-unsloth"}) def wide_flash(served): """True when what serves is one of those lanes at a window past the native 262,144, which its engine says on /v1/models with the names just read (served_window: vLLM's max_model_len, llama.cpp's meta.n_ctx), as the cockpit reads it (and oc-fit-limits.py, the FP4-Local lane's). Measured, the FP4-Local lane to 1,036,576 tokens with 15.1 GiB of memory left (2026-11-09), the Unsloth GGUF lane to 985,296 with 12 GiB left (one request, YaRN at four times, its KV cache in q8_0, 2026-11-12): their prompts are bounded by the pool's share, not by the flash ceiling, which kept a long prefill of the SGLang flash lane off the memory edge. The flash ceiling refused every prompt past 250,000 at that window (code review of v1.45.2; the Unsloth GGUF lane's, code review of v1.48.0).""" if not served & WIDE_FLASH_NAMES or served & (FLASH_SERVED_NAMES - WIDE_FLASH_NAMES): return False return (_SERVED.get("window") or 0) > 262144 def wedge_possible(pool): """True when the engine would accept a prompt past the share of its pool this guard lets through, the zone where a prompt is queued and never admitted (a wedge): its window (max_req_input_len) is larger than that share, or not known. On the 27B lane the engine accepts up to 863,638 tokens on a pool of 863,644, past the 794,552 usable here (measured 2026-10-08). Only there is a body nominated by its bound, at a measured cost of one more count (115 ms on a lone 300 kB prompt, 1.65 s on a burst of eight). Where the window is under that share (the flash lane: 262,138 for 428,823 usable of 466,112), the engine refuses past it itself, and the average nominates as it always did.""" window = _POOL.get("window") return pool is None or not window or window > int(pool * (1.0 - OVERSIZE_MARGIN_FRAC)) def nomination_estimate(n_bytes, pool): """The token estimate that decides whether a body is counted: its bound where a wedge is possible, the pre-v6.34 average elsewhere.""" return n_bytes / (CHARS_PER_TOKEN_MIN if wedge_possible(pool) else NOCOUNT_CHARS_PER_TOKEN) def prompt_limit(pool): """Usable prompt tokens: the pool share, capped by the serving lane's ceiling when set.""" limit = int(pool * (1.0 - OVERSIZE_MARGIN_FRAC)) ceiling = lane_ceiling() if ceiling > 0: limit = min(limit, ceiling) return limit MEDIA_BLOCKS = ("image", "image_url", "input_audio", "video_url", "document", "audio_url") # Fallback budget for a media part whose real cost cannot be derived: audio, video, # documents, and images whose header the parser below does not recognise. An IMAGE # is never guessed at any more, because guessing was the bug (see _image_tokens). TOKENS_PER_MEDIA = int(os.environ.get("TOKENS_PER_MEDIA", "4096")) # Vision geometry of every checkpoint this repo serves (patch_size 16, merge_size 2 # in preprocessor_config.json, identical on the 27B and flash lanes): the vision # tower sees a grid of MEDIA_PATCH_PX-sized cells and emits one token per cell. MEDIA_PATCH_PX = int(os.environ.get("MEDIA_PATCH_PX", "32")) MEDIA_MIN_PIXELS = int(os.environ.get("MEDIA_MIN_PIXELS", "65536")) # size.shortest_edge MEDIA_MAX_PIXELS = int(os.environ.get("MEDIA_MAX_PIXELS", "16777216")) # size.longest_edge # Tokens a single image adds beyond its cells: <|vision_start|> and <|vision_end|>. # The stripped body loses the whole block, so the delta is cells + 2 (measured). MEDIA_WRAP_TOKENS = 2 # An IMAGE whose header the parser does not recognise is still bounded: the # processor clamps it to MEDIA_MAX_PIXELS, so no image can ever cost more than # that many cells. Charging the bound (16,384 at the stock geometry) instead of # the flat budget keeps the guard honest in the direction that matters, because # a 3840x2160 screenshot really costs 8,162 and the flat 4,096 would UNDER-count # it. opencode only ever attaches jpeg, png, gif and webp, all four of which the # parser reads, so this is the belt to the parser's braces. IMAGE_BLOCKS = ("image", "image_url") # Bytes of the payload to look at when reading an image header. PNG, GIF and WebP # carry the size in the first 32; JPEG hides it behind APPn segments and quant # tables, so the scan needs room, and 48 KiB covers an EXIF thumbnail too. MEDIA_HEADER_BYTES = 48 * 1024 # Corruption tripwire: consecutive "!" (token id 0) that mean the decode path lost # its state rather than the model writing prose. 0 disables the guard. CORRUPTION_RUN = int(os.environ.get("CORRUPTION_RUN", "128") or 0) CORRUPTION_MARK = "!" # Role 8, Cohere's report (2026-10-26): the OSS domain Qwen3.8-Flash-Next sent a file to (the Routify # file relay of the report's host list sits under it too) and the cloud metadata addresses. Matched # in lower case. A bare "routify" matched the Svelte framework of that name (found in review). TOOL_TARGETS = ("aliyuncs.com", "169.254.169.254", "100.100.100.200") # The routes whose answers carry tool calls, the only ones role 8 keeps a whole answer of. TOOL_ROUTES = ("/v1/chat/completions", "/v1/messages", "/v1/responses") # Tools that read, search or write files, plan, or hand work to a sub-agent (whose own calls come # through here), and reach no host themselves: an agent that greps for these hosts or edits a page # that quotes them (this repo's own docs/agents-and-network.md) is no request to them. Exact names, # in lower case: a pattern on part of a name skipped write_stdin, which types into a shell, and an # http_patch (found in review). QUIET_TOOLS = frozenset(( # opencode, Claude Code and pi "read", "read_file", "write", "write_file", "edit", "edit_file", "multiedit", "patch", "apply_patch", "create_file", "str_replace_editor", "str_replace_based_edit_tool", "notebookread", "notebookedit", "grep", "glob", "find", "list", "ls", "codesearch", "websearch", "web_search", "lsp", "todoread", "todowrite", "task", "skill", # Hermes Agent, read in its tools on the box (2026-10-28): its terminal, execute_code, browser_* # and web_extract act, and are read "search_files", "session_search", "todo_list", "memory", "delegate_task", "x_search", "read_terminal")) # Bytes of a whole answer kept to read its tool calls, once one of TOOL_TARGETS shows in it. TOOL_ANSWER_MAX = 8 << 20 # Bytes of tool arguments kept per streamed request for that check (a whole answer: TOOL_ANSWER_MAX). TOOL_WATCH_MAX = 1 << 20 # What an event carrying a piece of a tool call holds, in one of the three dialects, whatever the # spaces an engine writes around "tool_calls" (only two spellings were known, found in review). TOOL_EVENT_RE = re.compile(rb'"tool_calls"\s*:\s*\[\s*\{|tool_use|input_json|function_call') # Role 9 (v6.49, issue #61): a long prompt its client left without an answer, then sent again. A body # under RESEND_MIN_BYTES computes in seconds, and a client that left before RESEND_MIN_S left for # another reason than a timeout; RESEND_WINDOW_S is how soon the same prompt counts as sent again. RESEND_MIN_BYTES = int(os.environ.get("RESEND_MIN_BYTES", str(256 * 1024)) or 0) RESEND_MIN_S = float(os.environ.get("RESEND_MIN_S", "60")) RESEND_WINDOW_S = float(os.environ.get("RESEND_WINDOW_S", "120")) _GAVE_UP: dict = {} # prompt fingerprint -> {"t": when its client left, "secs": waited, "n": in a row} _GAVE_UP_LOCK = threading.Lock() # The ends of a client that left while the engine computed its request, before any answer: streamed (the # proxy sending keepalives, or waiting for the engine's first byte) and not (Claude Code's fallback after # 10 min). Not "on write": the engine had answered, the client left while the answer was relayed. Not # "during hold": the lane was starting, and the engine never had the request (code review, 2026-10-31). GAVE_UP_OUTCOMES = ("CLIENT GONE during keepalive", "CLIENT GONE before the engine answered", "CLIENT GONE during non-sse wait") # What a retry changes in a body and the prompt does not: Claude Code sent the same prompt with "stream": # true, then false (1,833,479 bytes, then 1,833,480). Matched on the raw bytes, wherever they are: a prompt # that quotes one is read the same way at each attempt. RESEND_SKIP_RE = re.compile(rb'"(stream|stream_options|max_tokens)"\s*:\s*(?:true|false|null|-?[0-9]+|\{[^{}]*\})') def prompt_fingerprint(body, route): """The prompt a body asks about, hashed from its raw bytes, but for what it asks of the answer (stream, stream_options, max_tokens), which Claude Code's retries change. Nothing is parsed or copied: the guards already read every body several times, and parsing it once more raised what a body costs this proxy past its unit's MemoryMax at the body budget (8 times its bytes for one of emoji, found by tests/test_proxy_memory_ceiling.py). None for a body too small to take long, or a route that generates nothing.""" if not body or RESEND_MIN_BYTES <= 0 or len(body) < RESEND_MIN_BYTES or route not in TOOL_ROUTES: return None return body_fingerprint(body, route) def body_fingerprint(body, route): """prompt_fingerprint's hash, for a body of any size: the raw bytes but for what a retry changes.""" h = hashlib.sha256(route.encode()) view, pos = memoryview(body), 0 for m in RESEND_SKIP_RE.finditer(body): h.update(view[pos:m.start()]) h.update(m.group(1)) # the key stays, its value and the spaces around it do not pos = m.end() h.update(view[pos:]) return h.hexdigest()[:16] # Decision 1019 (2026-11-03): a request an engine closed the connection on while it had it may be what took that # engine down, and so may one the other box of a pair had whole and closed the connection on (decision 1017). A # client sends a 5xx's request again within seconds (Claude Code, opencode, the SDKs), and that retry reached the # other box's engine by the sharing's fallback: one request and its retry took both boxes down (code review of # v1.43.0). Such a request is kept by its fingerprint, with the box it happened on, PAIR_KILLER_KEEP_S: until then it # goes to that box or nowhere, never shared, handed back or taken over. It can take one box down, as on a box alone. PAIR_KILLER_KEEP_S = float(os.environ.get("PAIR_KILLER_KEEP_S") or 600) PAIR_KILLER_KEEP_S = PAIR_KILLER_KEEP_S if math.isfinite(PAIR_KILLER_KEEP_S) and PAIR_KILLER_KEEP_S >= 0 else 600.0 PAIR_KILLER_MAX = 1024 # the fingerprints kept, the oldest dropped first _KILLERS: "collections.OrderedDict[str, tuple]" = collections.OrderedDict() # fingerprint -> (box, until) _KILLERS_LOCK = threading.Lock() # The lane this box's engine served at its last answer: (its names, its checkpoint), one tuple set at once (1018) _LAST_LANE = {"lane": (frozenset(), None)} def killer_note(fp, box): """The engine of box ("" for this box, whatever its pair.json says: _killed_here) closed the connection on the request of fingerprint fp: its body as routing saw it (_pair_routed), never a body this proxy rewrote since (a tool schema, a reasoning effort, the served name), whose fingerprint the client's retry never matched (found in review, 2026-11-04). Returns the binding it replaced, (box, until) or None: what undoing this one gives back (killer_forget).""" if not fp or PAIR_KILLER_KEEP_S <= 0: return None now = time.monotonic() with _KILLERS_LOCK: for old in [k for k, (_, until) in _KILLERS.items() if until <= now]: del _KILLERS[old] # ended: they only took room among the PAIR_KILLER_MAX kept before = _KILLERS.pop(fp, None) _KILLERS[fp] = (box, now + PAIR_KILLER_KEEP_S) while len(_KILLERS) > PAIR_KILLER_MAX: _KILLERS.popitem(last=False) return before def killer_forget(fp, box, before=None): """The binding of fingerprint fp to box undone: an order said after the death that made it (decisions 1054 and 1061), an order a clean end or a cut showed after a death here (_relay_inner). before: the binding fp had before the request undone now first bound it (killer_note), given back while it lasts: an order that ended a retry erased the binding an earlier real death of the same body had made, and the next retry could take this box's engine down too (decision 1019; the 8th review of v1.43.0, 2026-11-05).""" if not fp: return with _KILLERS_LOCK: if (_KILLERS.get(fp) or (None,))[0] == box: del _KILLERS[fp] if before is not None and before[1] > time.monotonic(): _KILLERS[fp] = before def peer_may_serve(conf, name): """True when a box of the pair may serve name: its list names it now; its read failed and its last good list named it, for PAIR_KNOWN_WAIT_S; or it was never read, for the PAIR_FIRST_READ_S after pair.json was read. Only the current list counted, and a box whose read failed, or a pair.json read again, let this box answer with the other model it serves now (the delta's 3rd review, 2026-11-04). Those are _pair_served_nowhere's bounds: without them, a box off for an hour had a request bound here refused for 10 minutes, where the same request unbound got this box's lane's answer after 30 s (decision 986; the 4th review of v1.43.0, 2026-11-04).""" for p in conf.get("peers") or (): row = _PAIR_MODELS.get(p["name"]) if name in ((row or {}).get("models") or ()) or peer_row_may_serve(row, name): return True return False def peer_row_may_serve(row, name): """A box of the pair whose list does not name `name` now may still serve it: its read failed and its last good list named it, for PAIR_KNOWN_WAIT_S, or it never read well, for the PAIR_FIRST_READ_S after pair.json was read. A row read well serves what it lists (a 409 "moved" leaves no error). The one rule of peer_may_serve and _pair_served_nowhere: two copies of it drifted, and one kept its last list 15 minutes (the 5th and 6th reviews of v1.43.0, 2026-11-04). A row never read since pair.json was (None) may too, for PAIR_FIRST_READ_S (the 7th review).""" now = time.monotonic() if row is None: return now - _PAIR["loaded"] < PAIR_FIRST_READ_S if not row.get("error"): return False if row.get("known") is None: return now - _PAIR["loaded"] < PAIR_FIRST_READ_S return name in row["known"] and now - (row.get("known_ts") or 0) < PAIR_KNOWN_WAIT_S def refusal_serves(data, name): """True when a refusal of the pair (409 model_not_served, either dialect) says its box serves name still: from another checkpoint (decision 1018). Its "served" lists what each box serves.""" try: served = (json.loads(data).get("error") or {}).get("served") or {} return any(isinstance(v, list) and name in v for v in served.values()) except Exception: return False def ndjson_death(lines): """True when a whole line of an NDJSON stream is an error that names an engine's death (vLLM's EngineCore, or this proxy's HOP_CLOSED) at its top level. Matched anywhere in the bytes, an Ollama tool call's arguments, a raw object, could carry the words (the 7th review of v1.43.0, 2026-11-04).""" for line in lines.split(b"\n"): if b'"error"' not in line or (b"EngineCore" not in line and HOP_CLOSED.encode() not in line): continue try: err = json.loads(line).get("error") except Exception: continue msg = err.get("message") if isinstance(err, dict) else err if isinstance(msg, str) and ("EngineCore encountered an issue." in msg or HOP_CLOSED in msg): return True return False def whole_lines(part, chunk): """NDJSON relayed line by line: (the whole lines of part + chunk, the rest of a line not whole yet). A line that never ends goes as it comes, past 64 KiB. One reading for the box that relays and the entry (the 6th review of v1.43.0).""" lines = part + chunk end = lines.rfind(b"\n") + 1 whole, part = lines[:end], lines[end:] if len(part) > 65536: whole, part = whole + part, b"" return whole, part def killers_live(): """True while a binding is kept: the ones that ended leave first, from the front, the oldest noted (each note moves its own to the end). Only a note purged them, and after one binding a box alone hashed every body for good (the delta's 3rd review, 2026-11-04).""" if not _KILLERS: return False now = time.monotonic() with _KILLERS_LOCK: while _KILLERS and next(iter(_KILLERS.values()))[1] <= now: _KILLERS.popitem(last=False) return bool(_KILLERS) def killer_box(fp): """The box an engine closed on the request of fingerprint fp moments ago ("" for this box), or None.""" if not fp or not killers_live(): return None now = time.monotonic() with _KILLERS_LOCK: got = _KILLERS.get(fp) if got is not None and got[1] <= now: _KILLERS.pop(fp, None) got = None return got[0] if got else None def resend_advice(user_agent): """(the client's name, what widens its timeout) from a User-Agent, printable and short.""" ua = "".join(c for c in (user_agent or "")[:60] if 32 <= ord(c) < 127).strip() if ua.lower().startswith("claude-cli/"): return (ua.split(" ")[0], "Claude Code gives up on a turn after 10 min, then 5 min without " "streaming: claude-local, or API_TIMEOUT_MS=3600000 with CLAUDE_STREAM_IDLE_TIMEOUT_MS " "and CLAUDE_BYTE_STREAM_IDLE_TIMEOUT_MS at 1800000, lets it wait (docs/clients.md)") return (ua.split(" ")[0] or "a client without a User-Agent", "its client's timeout is shorter than this prompt takes to compute: widen it (docs/clients.md)") # Optional TLS: name the operator's own certificate (tailnet CA, LAN-trusted) and # the socket speaks it. The proxy invents no trust, it speaks the one you point at. TLS_CERT = os.environ.get("QWEN38_TLS_CERT", "") TLS_KEY = os.environ.get("QWEN38_TLS_KEY", "") # The engine's own key, held by the proxy for admission (v6.17). Unset means the # client's header goes through verbatim, exactly as before: fine for an engine # with no key check of its own, or one shared key on purpose. UPSTREAM_API_KEY = os.environ.get("QWEN38_UPSTREAM_API_KEY", "") # Optional per-client identity: JSON {"": "