Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
server: /status needs the API key and forgets the answer's end (#212); constant-time key check, an explicitly empty key refuses to start (#213); an engine exit quotes its last log line (#215); tool calls end at their own </parameter> and </tool_call>, so values may contain them (#210)
Niko1221fa59b3f3a9a9
diff --git a/serve/frontend.py b/serve/frontend.pyindex 670bcfbe0..23144e408 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -242,6 +242,61 @@ CALL_START = "<tool_call>"CALL_END = "</tool_call>"+PARAM_END = "</parameter>"+FUNC_END = "</function>"+++def param_end(text: str, final: bool = False) -> int:+ """Where a parameter value in `text` ends: the first `</parameter>` followed (after whitespace) by the next+ `<parameter=` or `</function>` - the same text inside a value (a file that documents the call format, #210) is+ part of the value. -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it)."""+ at = text.find(PARAM_END)+ while at >= 0:+ after = text[at + len(PARAM_END):].lstrip()+ if after.startswith(("<parameter=", FUNC_END)):+ return at+ if not after or "<parameter=".startswith(after) or FUNC_END.startswith(after):+ return at if final else -2+ at = text.find(PARAM_END, at + 1)+ return -1+++def call_end(text: str) -> int:+ """Where a tool call's body ends (#210): the `</tool_call>` after the call's own `</function>`, found by walking+ its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in+ the call format ends at the first `</tool_call>`, as before."""+ s = text.lstrip()+ pos = len(text) - len(s)+ if not s.startswith("<function="):+ return text.find(CALL_END) if not "<function=".startswith(s) else -1+ gt = text.find(">", pos)+ if gt < 0:+ return -1+ pos = gt + 1+ while True:+ rest = text[pos:]+ s = rest.lstrip()+ pos += len(rest) - len(s)+ if s.startswith("<parameter="):+ gt = text.find(">", pos)+ if gt < 0:+ return -1+ end = param_end(text[gt + 1:])+ if end < 0:+ return -1+ pos = gt + 1 + end + len(PARAM_END)+ elif s.startswith(FUNC_END):+ rest = text[pos + len(FUNC_END):]+ s = rest.lstrip()+ if s.startswith(CALL_END):+ return pos + len(FUNC_END) + len(rest) - len(s)+ return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos)+ elif not s or "<parameter=".startswith(s) or FUNC_END.startswith(s):+ return -1+ else:+ return text.find(CALL_END, pos)++def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decodedwhen the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON@@ -257,9 +312,9 @@ def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:rest = rest[rest.index("<parameter=") + len("<parameter="):]pname = rest[:rest.index(">")]rest = rest[rest.index(">") + 1:]- end = rest.find("</parameter>")+ end = param_end(rest, final=True)value = rest[:end] if end >= 0 else rest- rest = rest[end + len("</parameter>"):] if end >= 0 else ""+ rest = rest[end + len(PARAM_END):] if end >= 0 else ""if value.startswith("\n"):value = value[1:]if value.endswith("\n"):@@ -351,16 +406,17 @@ class OutputParser:self.sp += 1rest = rest[1:]self.sval_started = True- end = rest.find("</parameter>")+ end = param_end(rest)if end >= 0:value = rest[:end]if value.endswith("\n"):value = value[:-1]args(json.dumps(value)[1:-1] + '"')- self.sp += end + len("</parameter>")+ self.sp += end + len(PARAM_END)self.ss = "between"continue- safe = len(rest) - self._hold(rest, ("</parameter>",))+ # an undecided </parameter> (-2) is held from its start, like a tag still arriving+ safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,))if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before </parameter>safe -= 1if safe > 0:@@ -368,7 +424,7 @@ class OutputParser:self.sp += safereturn outelif self.ss == "raw":- end = rest.find("</parameter>")+ end = param_end(rest)if end < 0:return outvalue = rest[:end]@@ -381,7 +437,7 @@ class OutputParser:except ValueError:v = valueargs(json.dumps(v, ensure_ascii=False))- self.sp += end + len("</parameter>")+ self.sp += end + len(PARAM_END)self.ss = "between"else:return out@@ -449,7 +505,7 @@ class OutputParser:self.buf = self.buf[i + len(CALL_START):]self.state = "call"else:- i = self.buf.find(CALL_END)+ i = call_end(self.buf)if self.stream_tools:if i >= 0:whole, self.buf = self.buf, self.buf[:i] # scan only the bodydiff --git a/serve/server.py b/serve/server.pyindex f35ca86d3..89b88b59f 100644--- a/serve/server.py+++ b/serve/server.py@@ -24,6 +24,7 @@ import argparseimport collectionsimport base64import hashlib+import hmacimport codecsimport jsonimport os@@ -216,6 +217,11 @@ class StrataEngine:if "issue #29" in line:return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log ""line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.")+ rc = self.proc.poll()+ last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "")+ if rc is not None and rc >= 0 and last: # it ended by itself: its own last words say why (#215)+ return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please "+ "report it at github.com/Niko1221/Strata/issues with the log.")return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | ""grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a ""smaller model (Q2_0 / IQ2_XS).")@@ -914,6 +920,8 @@ class Service:if os.environ.get("STRATA_DEBUG") and raw_ids:print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True)self.status["busy"] = False+ self.status.pop("tail", None) # #212: the answer's end is not kept once it is done+ self.status.pop("tool", None)for ev in parser.finish():yield "event", evyield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),@@ -1245,7 +1253,7 @@ def make_handler(svc: Service):return Trueauth = self.headers.get("Authorization", "")given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")- if given == svc.api_key:+ if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-timereturn Trueself._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}})return False@@ -1310,6 +1318,8 @@ def make_handler(svc: Service):self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model,"images": svc.vision is not None, "api_key": bool(svc.api_key)})elif path == "/status":+ if not self._authorized(): # #212: it shows the end of the last answer+ returnwith svc.status_lock:s = dict(svc.status)now = time.time()@@ -1728,6 +1738,12 @@ def main() -> int:model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision,sampling_defaults=sampling_defaults,fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)+ if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key="+ for i, x in enumerate(sys.argv)):+ # #213: an empty key would switch authentication off without a word+ print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out",+ file=sys.stderr)+ return 2svc.api_key = a.api_key or cfg.get("api_key", "")svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)diff --git a/serve/test_server.py b/serve/test_server.pyindex 4320e726d..b3f70c557 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -196,6 +196,61 @@ class ImageMarkers(unittest.TestCase):svc.embeddings.path.unlink(missing_ok=True)+class StatusNeedsTheKey(unittest.TestCase):+ """#212: /status shows the end of the answer being written, so it needs the key like /v1/*."""++ def test_status(self):+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ svc.api_key = "k3y"+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}/status"+ try:+ with self.assertRaises(urllib.error.HTTPError) as e:+ urllib.request.urlopen(base, timeout=10)+ self.assertEqual(e.exception.code, 401)+ e.exception.close()+ req = urllib.request.Request(base, headers={"Authorization": "Bearer k3y"})+ with urllib.request.urlopen(req, timeout=10) as r:+ self.assertEqual(r.status, 200)+ self.assertNotIn("tail", json.loads(r.read()))+ finally:+ httpd.shutdown()+ httpd.server_close()+++class ToolCallTerminators(unittest.TestCase):+ """#210: a value that contains </parameter> or </tool_call> (a file documenting the call format) is kept whole."""+ CONTENT = ("Close each value with </parameter> and the call with </function></tool_call>.\n"+ "<parameter=x>\nnot a parameter\n</parameter>\nend")+ SCHEMA = [{"name": "write", "parameters": {"properties": {"path": {"type": "string"},+ "content": {"type": "string"}}}}]++ def run_parser(self, stream_tools, step):+ from serve.frontend import OutputParser+ text = ("</think>\n\n<tool_call>\n<function=write>\n<parameter=path>\ndoc.md\n</parameter>\n"+ f"<parameter=content>\n{self.CONTENT}\n</parameter>\n</function>\n</tool_call>")+ p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools)+ evs = []+ for i in range(0, len(text), step):+ evs += p.feed(text[i:i + step])+ evs += p.finish()+ return evs++ def test_values_keep_the_terminators(self):+ for stream_tools in (False, True):+ for step in (1, 7, 10_000):+ with self.subTest(stream_tools=stream_tools, step=step):+ evs = self.run_parser(stream_tools, step)+ calls = [e.call for e in evs if e.kind == "tool_call"]+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0].arguments, {"path": "doc.md", "content": self.CONTENT})+ self.assertFalse([e for e in evs if e.kind == "content" and e.text.strip()])+ if stream_tools:+ streamed = "".join(e.text for e in evs if e.kind == "tool_args")+ self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT})++class ClientShapes(unittest.TestCase):"""What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into theconversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message."""