Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

web: render markdown in the chat pane, and stop clamping it to 1024 tokens

JustVugg6e9024234f72
diff --git a/c/coli b/c/coli
index 63b724c9..64f4f28b 100755
--- a/c/coli
+++ b/c/coli
@@ -266,6 +266,15 @@ def need_model(model, engine=None):
"deepseek-v4" if arch == "deepseek_v4" else "colibri")
sys.exit(f"{C.yel}{target} engine is not built.{C.r} Run: make -C c {target}")
+# One-shot runs keep the historic 1024. Interactive sessions get 16384, because
+# the browser and the TUI both offer a per-request limit and the server treats
+# --ngen as a hard ceiling it clamps to (#260) -- so a low ceiling makes the
+# user's own control inert instead of merely cautious. Still a ceiling, not a
+# target: generation ends at EOS either way.
+def ngen_for(a, interactive=False):
+ if getattr(a, "ngen", None): return a.ngen
+ return 16384 if interactive else 1024
+
def env_for_engine(a, arch):
if arch == "glm":
return env_for(a)
@@ -295,11 +304,11 @@ def env_for_engine(a, arch):
if sys.platform != "win32":
env.setdefault("OMP_PROC_BIND", "close")
env.setdefault("OMP_PLACES", "cores")
- if a.ngen: env["NGEN"] = str(a.ngen)
+ env["NGEN"] = str(ngen_for(a)) # ngen_for keeps the historic 1024 here
if a.temp is not None: env["COLI_TEMP"] = str(a.temp)
if arch == "olmoe":
env["CHAT"] = "1"
- if a.ngen: env["MAX_NEW"] = str(a.ngen)
+ env["MAX_NEW"] = str(ngen_for(a))
if a.temp is not None: env["TEMP"] = str(a.temp)
# --ram reaches the engines that read it. kimi_k3 gained a RAM budget in
# #855; before that `grep -c RAM_GB c/kimi_k3.c` returned 0, so `coli chat
@@ -416,7 +425,7 @@ def env_for(a):
e.setdefault("PILOT_REAL", "1")
e["COLI_POLICY"]=a.policy
if a.ram: e["RAM_GB"]=str(a.ram)
- if a.ngen: e["NGEN"]=str(a.ngen)
+ e["NGEN"]=str(ngen_for(a))
if a.topp: e["TOPP"]=str(a.topp)
if a.topk: e["TOPK"]=str(a.topk)
if a.temp is not None: e["COLI_TEMP"]=str(a.temp) # 0 = greedy; default motore: 1.0 + nucleus 0.95
@@ -840,7 +849,7 @@ def cmd_run(a):
cmd += ["--prompt-file",prompt_path]
else:
cmd.append(prompt)
- cmd += ["--max-tokens",str(a.ngen)]
+ cmd += ["--max-tokens",str(ngen_for(a,interactive=True))]
if a.ram: cmd += ["--memory-gb",str(a.ram)]
if os.environ.get("COLI_THINK","0")=="1": cmd.append("--thinking")
result=subprocess.call(cmd,env=env_for_engine(a,arch))
@@ -913,7 +922,7 @@ def chat_attached(a, base, model_id):
if msg==":reset": msgs=[]; print(f" {C.dim}✦ new conversation{C.r}\n"); continue
msgs.append({"role":"user","content":msg})
body=json.dumps({"model":model_id,"messages":msgs,"stream":True,
- "max_tokens":a.ngen}).encode()
+ "max_tokens":ngen_for(a,interactive=True)}).encode()
req=urllib.request.Request(base.rstrip("/")+"/v1/chat/completions", data=body,
headers={"Content-Type":"application/json"})
if a.api_key: req.add_header("Authorization", f"Bearer {a.api_key}")
@@ -1008,7 +1017,7 @@ def cmd_chat(a):
# legacy 8, an explicit value -- 0 included -- passes verbatim).
cmd=[sys.executable,openai_server.__file__,"--model",a.model,
"--engine",engine,"--arch",arch,"--model-id",model_id,
- "--host","127.0.0.1","--port","8000","--max-tokens",str(a.ngen)]
+ "--host","127.0.0.1","--port","8000","--max-tokens",str(ngen_for(a,interactive=True))]
if a.cap is not None: cmd+=["--cap",str(a.cap)]
if a.api_key: cmd+=["--api-key",a.api_key]
p=subprocess.Popen(cmd,env=env_for_engine(a,arch))
@@ -1148,8 +1157,8 @@ def cmd_chat(a):
print(f"\r {C.dgray}└─ {st['tok']} tok · {st['tps']:.2f} tok/s · hit {st['hit']:.0f}% · RSS {st['rss']:.1f} GB · {el:.0f}s{C.r}")
if st.get("interrupted"):
print(f" {C.yel}⏹ interrupted; type :more to continue the response{C.r}")
- elif st["tok"]>=a.ngen:
- print(f" {C.yel}…stopped at --ngen ({a.ngen}); type :more to continue the response{C.r}")
+ elif st["tok"]>=ngen_for(a,interactive=True):
+ print(f" {C.yel}…stopped at --ngen ({ngen_for(a,interactive=True)}); type :more to continue the response{C.r}")
print()
else:
if st.get("interrupted"): print(f" {C.yel}⏹ interrupted{C.r}")
@@ -1185,7 +1194,7 @@ def cmd_serve(a):
"glm-5.2-colibri")
try:
openai_server.serve(a.model,a.host,a.port,model_id,a.api_key,
- a.cap,a.ngen,engine,env_for_engine(a,arch),a.cors_origin,
+ a.cap,ngen_for(a,interactive=True),engine,env_for_engine(a,arch),a.cors_origin,
a.max_queue,a.queue_timeout,a.kv_slots,allowed_hosts=a.allowed_host)
finally:
try: os.unlink(serve_pidfile(a.port))
@@ -1371,7 +1380,11 @@ def main():
# legacy 8 (openai_server.cap_for_arch). An explicit --cap N -- 0 included --
# reaches the engine verbatim; see colibri.c's coli_resolve_cap().
common.add_argument("--cap", type=int, default=None, help="cache slots/layer (default: auto)")
- common.add_argument("--ngen", type=int, default=1024) # rete di sicurezza: la fine vera la decidono gli stop token
+ # default None, resolved per command by ngen_for() below. 1024 is a sensible
+ # safety net for a one-shot `coli run`; it is the wrong number for a session
+ # where the browser shows a "max output tokens" control, because the server
+ # clamps to it and the control silently does nothing above 1024 (#889).
+ common.add_argument("--ngen", type=int, default=None) # rete di sicurezza: la fine vera la decidono gli stop token
common.add_argument("--topp", type=float, default=0); common.add_argument("--topk", type=int, default=0)
common.add_argument("--temp", type=float, default=None) # temperatura token (0=greedy, default 1.0+nucleus .95)
ap=argparse.ArgumentParser(prog="coli", parents=[common], description="colibri — run GLM-5.2 locally")
diff --git a/c/tests/test_v4_cli.py b/c/tests/test_v4_cli.py
index faf33692..47153272 100644
--- a/c/tests/test_v4_cli.py
+++ b/c/tests/test_v4_cli.py
@@ -126,6 +126,26 @@ class V4CliTest(unittest.TestCase):
env = self.cli.env_for_engine(args, "kimi")
self.assertNotIn("RAM_GB", env)
+ def test_ngen_default_differs_for_interactive_commands(self):
+ """#889: `coli web` passed --max-tokens 1024, and openai_server clamps a
+ request to that ceiling (#260), so the browser's own "max output tokens"
+ control silently did nothing above 1024. One-shot runs keep 1024; a
+ session where the user has a control gets a ceiling that is not in the
+ way. An explicit --ngen always wins."""
+ run = argparse.Namespace(ngen=None)
+ self.assertEqual(self.cli.ngen_for(run), 1024)
+ self.assertEqual(self.cli.ngen_for(run, interactive=True), 16384)
+ explicit = argparse.Namespace(ngen=300)
+ self.assertEqual(self.cli.ngen_for(explicit), 300)
+ self.assertEqual(self.cli.ngen_for(explicit, interactive=True), 300)
+
+ def test_one_shot_env_still_carries_the_historic_ngen(self):
+ """The default moved to None so the two cases can be told apart. These
+ sites must not become "unset": before, NGEN was always exported."""
+ args = argparse.Namespace(ngen=None, temp=None, ram=0, ctx=0)
+ env = self.cli.env_for_engine(args, "deepseek_v4")
+ self.assertEqual(env["NGEN"], "1024")
+
def test_kimi_does_not_get_v4_only_settings(self):
"""The widening is RAM_GB alone; CTX and the V4 speculation defaults stay
where they were."""
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 4f3dc535..6b89423f 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -35,6 +35,7 @@ import { activeRequests, supportsCacheSlots } from "@/lib/runtime"
import { Brain } from "./Brain"
import { Profiling } from "./Profiling"
import { persistPublicSettings, stored } from "@/lib/storage"
+import { Markdown } from "@/components/Markdown"
import { cn } from "@/lib/utils"
import { useLocale } from "./i18n"
@@ -356,7 +357,14 @@ export default function App() {
{messages.map((item) => (
<article key={item.id} className={cn("message", item.role)}>
<div className="avatar">{item.role === "user" ? "Y" : <Feather className="size-4" />}</div>
- <div><div className="message-meta">{item.role === "user" ? t("chat.you") : t("chat.colibri")}</div><div className="message-body">{item.content || <span className="typing" aria-label="Generating"><i /><i /><i /></span>}</div></div>
+ <div><div className="message-meta">{item.role === "user" ? t("chat.you") : t("chat.colibri")}</div><div className="message-body">{item.content
+ ? (item.role === "assistant"
+ /* User turns stay literal: the person typed those
+ characters and expects to see them back. Only the
+ model's output is markdown. */
+ ? <Markdown source={item.content} />
+ : item.content)
+ : <span className="typing" aria-label="Generating"><i /><i /><i /></span>}</div></div>
</article>
))}
<div ref={bottomRef} />
diff --git a/web/src/components/Markdown.tsx b/web/src/components/Markdown.tsx
new file mode 100644
index 00000000..67a805c2
--- /dev/null
+++ b/web/src/components/Markdown.tsx
@@ -0,0 +1,97 @@
+import { Check, Copy } from "lucide-react"
+import { useCallback, useMemo, useState } from "react"
+import { highlight, parseMarkdown, type Block, type Span } from "@/lib/markdown"
+
+/* Renders an assistant turn the way `coli chat`'s TUI already does: fenced code
+ * in a labelled box, real bold, coloured inline code, headings and bullets, and
+ * no marker ever visible.
+ *
+ * Everything below builds React ELEMENTS. Nothing reaches innerHTML, so model
+ * output cannot become markup no matter what it contains — the property that
+ * makes this safe to point at an untrusted generation without a sanitiser.
+ */
+
+function Inline({ spans }: { spans: Span[] }) {
+ return (
+ <>
+ {spans.map((span, index) => {
+ if (span.kind === "bold") return <strong key={index}>{span.text}</strong>
+ if (span.kind === "code") return <code key={index} className="md-inline">{span.text}</code>
+ return <span key={index}>{span.text}</span>
+ })}
+ </>
+ )
+}
+
+function CodeBlock({ lang, text, open }: { lang: string; text: string; open: boolean }) {
+ const [copied, setCopied] = useState(false)
+ const tokens = useMemo(() => highlight(text, lang), [text, lang])
+
+ const copy = useCallback(() => {
+ // Clipboard is unavailable over plain http on a non-localhost origin, which
+ // is exactly how `coli web --host <lan-ip>` is used. Fail quietly to the
+ // textarea path rather than throwing into the console.
+ const done = () => { setCopied(true); window.setTimeout(() => setCopied(false), 1200) }
+ if (navigator.clipboard?.writeText) {
+ navigator.clipboard.writeText(text).then(done, () => undefined)
+ return
+ }
+ const area = document.createElement("textarea")
+ area.value = text
+ area.setAttribute("readonly", "")
+ area.style.position = "fixed"
+ area.style.opacity = "0"
+ document.body.appendChild(area)
+ area.select()
+ try { document.execCommand("copy"); done() } catch { /* nothing to do */ }
+ document.body.removeChild(area)
+ }, [text])
+
+ return (
+ <div className="md-code">
+ <div className="md-code-head">
+ <span>{lang || "code"}</span>
+ <button type="button" onClick={copy} aria-label={copied ? "Copied" : "Copy code"}>
+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ </button>
+ </div>
+ <pre>
+ <code>
+ {tokens.map((token, index) =>
+ token.kind === "plain"
+ ? <span key={index}>{token.text}</span>
+ : <span key={index} className={`tok-${token.kind}`}>{token.text}</span>,
+ )}
+ {/* An unclosed fence means the answer is still arriving inside it.
+ A caret says "more is coming" instead of leaving the box looking
+ finished and truncated. */}
+ {open ? <span className="md-caret" /> : null}
+ </code>
+ </pre>
+ </div>
+ )
+}
+
+export function Markdown({ source }: { source: string }) {
+ const blocks = useMemo<Block[]>(() => parseMarkdown(source), [source])
+ return (
+ <div className="md">
+ {blocks.map((block, index) => {
+ if (block.kind === "code")
+ return <CodeBlock key={index} lang={block.lang} text={block.text} open={block.open} />
+ if (block.kind === "h") {
+ const Tag = (`h${Math.min(block.level + 2, 6)}`) as "h3" | "h4" | "h5" | "h6"
+ return <Tag key={index} className="md-h"><Inline spans={block.spans} /></Tag>
+ }
+ if (block.kind === "li")
+ return (
+ <div key={index} className="md-li">
+ <span className="md-bullet">{block.ordered ? "›" : "•"}</span>
+ <span><Inline spans={block.spans} /></span>
+ </div>
+ )
+ return <p key={index} className="md-p"><Inline spans={block.spans} /></p>
+ })}
+ </div>
+ )
+}
diff --git a/web/src/index.css b/web/src/index.css
index 58c30e1a..079655e4 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -190,3 +190,31 @@ button:focus-visible, input:focus-visible, textarea:focus-visible, select:focus-
.prof-tiles { grid-template-columns: 1fr 1fr; }
.prof-charts { grid-template-columns: 1fr; }
}
+
+/* --- markdown in the chat pane -------------------------------------------
+ * Matches what coli chat's TUI renders: fenced code in a labelled box, real
+ * bold, coloured inline code, headings and bullets. The pane sets
+ * white-space: pre-wrap for raw text; markdown blocks manage their own
+ * whitespace, so .md resets it and the code block turns it back on. */
+.md { white-space: normal; }
+.md > * + * { margin-top: 10px; }
+.md-p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
+.md-h { margin: 0; color: var(--primary); font-weight: 700; font-size: 14px; letter-spacing: .01em; }
+.md-li { display: grid; grid-template-columns: 14px minmax(0,1fr); gap: 6px; white-space: pre-wrap; overflow-wrap: anywhere; }
+.md-bullet { color: var(--primary); line-height: 1.75; }
+.md-inline { padding: 1px 5px; border: 1px solid var(--border); border-radius: 5px; background: rgba(255,255,255,.04); color: #f0b429; font-size: 12.5px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
+
+.md-code { border: 1px solid var(--border); border-radius: 9px; background: rgba(0,0,0,.28); overflow: hidden; }
+.md-code-head { display: flex; align-items: center; justify-content: space-between; padding: 5px 10px; border-bottom: 1px solid var(--border); color: #7f8c91; font-size: 10px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; }
+.md-code-head button { display: grid; place-items: center; padding: 3px; border: 0; border-radius: 5px; background: transparent; color: #7f8c91; cursor: pointer; }
+.md-code-head button:hover { color: #d8e0e2; background: rgba(255,255,255,.06); }
+/* overflow-x on the pre, never on the page: a long line must scroll inside
+ * its own box rather than widening the chat column. */
+.md-code pre { margin: 0; padding: 10px 12px; overflow-x: auto; }
+.md-code code { display: block; white-space: pre; color: #cfd8db; font-size: 12.5px; line-height: 1.6; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
+.tok-kw { color: #7aa2f7; }
+.tok-str { color: #9ece6a; }
+.tok-num { color: #ff9e64; }
+.tok-com { color: #6b7780; font-style: italic; }
+.md-caret { display: inline-block; width: 7px; height: 13px; margin-left: 1px; background: var(--primary); opacity: .75; animation: md-blink 1s steps(2) infinite; vertical-align: text-bottom; }
+@keyframes md-blink { 50% { opacity: 0; } }
diff --git a/web/src/lib/markdown.test.ts b/web/src/lib/markdown.test.ts
new file mode 100644
index 00000000..a8c63c78
--- /dev/null
+++ b/web/src/lib/markdown.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest"
+import { highlight, parseInline, parseMarkdown, type Block } from "./markdown"
+
+const kinds = (blocks: Block[]) => blocks.map((b) => b.kind)
+
+describe("parseInline", () => {
+ it("hides the markers, not the text", () => {
+ expect(parseInline("a **b** c")).toEqual([
+ { kind: "text", text: "a " },
+ { kind: "bold", text: "b" },
+ { kind: "text", text: " c" },
+ ])
+ expect(parseInline("run `make check` now")).toEqual([
+ { kind: "text", text: "run " },
+ { kind: "code", text: "make check" },
+ { kind: "text", text: " now" },
+ ])
+ })
+
+ it("leaves a single asterisk alone", () => {
+ // 3 * 4, a glob, a footnote. The TUI makes the same call for the same
+ // reason: emphasis with one asterisk is rarer than multiplication.
+ expect(parseInline("3 * 4 = 12")).toEqual([{ kind: "text", text: "3 * 4 = 12" }])
+ })
+
+ it("does not swallow the line on an unterminated marker", () => {
+ // Mid-stream the model has typed the opening backtick and not the closing
+ // one. Eating the rest of the line into a code span would make the answer
+ // visibly lurch as the next chunk arrives.
+ expect(parseInline("an unclosed ` backtick")).toEqual([
+ { kind: "text", text: "an unclosed ` backtick" },
+ ])
+ expect(parseInline("an unclosed ** bold")).toEqual([
+ { kind: "text", text: "an unclosed ** bold" },
+ ])
+ })
+})
+
+describe("parseMarkdown", () => {
+ it("recognises the shapes the TUI recognises", () => {
+ const md = [
+ "# Title",
+ "",
+ "Some **prose**.",
+ "",
+ "- one",
+ "- two",
+ "1. first",
+ "",
+ "```python",
+ "def f():",
+ " return 1",
+ "```",
+ "",
+ "after",
+ ].join("\n")
+ expect(kinds(parseMarkdown(md))).toEqual(["h", "p", "li", "li", "li", "code", "p"])
+ })
+
+ it("keeps fenced text verbatim and records the language", () => {
+ const blocks = parseMarkdown("```python\nx = '# not a heading'\n```")
+ expect(blocks).toHaveLength(1)
+ const block = blocks[0]
+ if (block.kind !== "code") throw new Error("expected a code block")
+ expect(block.lang).toBe("python")
+ expect(block.text).toBe("x = '# not a heading'")
+ expect(block.open).toBe(false)
+ })
+
+ it("treats an unclosed fence as open to the end", () => {
+ // THE streaming case: the answer stops inside the code block. Leaving the
+ // fence unrecognised would print ``` into the prose and render the code as
+ // a paragraph, then reflow it when the closing fence arrives.
+ const blocks = parseMarkdown("intro\n\n```c\nint main(void) {")
+ expect(kinds(blocks)).toEqual(["p", "code"])
+ const block = blocks[1]
+ if (block.kind !== "code") throw new Error("expected a code block")
+ expect(block.open).toBe(true)
+ expect(block.text).toBe("int main(void) {")
+ })
+
+ it("does not interpret markdown inside code", () => {
+ const blocks = parseMarkdown("```\n**not bold** and `not code`\n```")
+ const block = blocks[0]
+ if (block.kind !== "code") throw new Error("expected a code block")
+ expect(block.text).toBe("**not bold** and `not code`")
+ })
+
+ it("survives an empty string and a bare fence", () => {
+ expect(parseMarkdown("")).toEqual([])
+ expect(kinds(parseMarkdown("```"))).toEqual(["code"])
+ })
+})
+
+describe("highlight", () => {
+ it("classifies keywords, strings, numbers and comments", () => {
+ const toks = highlight('def f():\n return "x" # note\n', "python")
+ const of = (k: string) => toks.filter((t) => t.kind === k).map((t) => t.text)
+ expect(of("kw")).toContain("def")
+ expect(of("kw")).toContain("return")
+ expect(of("str")).toContain('"x"')
+ expect(of("com")).toContain("# note")
+ })
+
+ it("uses the language's own comment marker", () => {
+ // '#' opens a comment in python and is an operator nowhere in C; getting
+ // this wrong paints half a C file grey.
+ expect(highlight("int x = 1; // c", "c").some((t) => t.kind === "com" && t.text === "// c")).toBe(true)
+ expect(highlight("#include <stdio.h>", "c").some((t) => t.kind === "com")).toBe(false)
+ expect(highlight("# a python comment", "python").some((t) => t.kind === "com")).toBe(true)
+ })
+
+ it("stops an unterminated string at the newline", () => {
+ // Mid-stream code is full of these. Painting the rest of the block as a
+ // string would make every subsequent line change colour as it arrives.
+ const toks = highlight('s = "open\nnext = 1\n', "python")
+ const str = toks.find((t) => t.kind === "str")
+ expect(str?.text).toBe('"open')
+ expect(toks.some((t) => t.kind === "num" && t.text === "1")).toBe(true)
+ })
+
+ it("leaves an unknown language plain rather than guessing", () => {
+ const toks = highlight("def f(): pass", "brainfuck")
+ expect(toks.every((t) => t.kind !== "kw")).toBe(true)
+ })
+
+ it("is lossless: the concatenated tokens are the input", () => {
+ // The property that matters most. A highlighter that drops or duplicates a
+ // character corrupts the code the user is about to copy.
+ for (const [src, lang] of [
+ ['def f():\n return "a" # c\n', "python"],
+ ["int main(void) { /* x */ return 0; }", "c"],
+ ["let x = `t${1}`; // y", "ts"],
+ ["", "python"],
+ ["no language here", ""],
+ ] as const) {
+ expect(highlight(src, lang).map((t) => t.text).join("")).toBe(src)
+ }
+ })
+})
diff --git a/web/src/lib/markdown.ts b/web/src/lib/markdown.ts
new file mode 100644
index 00000000..8c0e4426
--- /dev/null
+++ b/web/src/lib/markdown.ts
@@ -0,0 +1,221 @@
+/* Markdown for the chat pane, matching what `coli chat`'s TUI already renders.
+ *
+ * The TUI (c/coli, class MD) turns ``` into boxed blocks with a language label,
+ * **x** into real bold, `x` into coloured inline code, # into headings and "- "
+ * into real bullets, and never shows a marker. The web pane showed the raw
+ * string: every asterisk, backtick and hash literal, and code as one grey
+ * paragraph. This closes that gap.
+ *
+ * WHY THIS IS PARSED RATHER THAN PULLED IN
+ *
+ * react-markdown would do it, and brings the whole unified/remark tree with it —
+ * roughly forty transitive packages to render bold text, in a project whose six
+ * dependencies are all small utilities. It also renders through HTML, which for
+ * model output is an XSS surface we would then have to sanitise. The renderer
+ * that consumes this builds React elements instead, so untrusted output cannot
+ * become markup by construction.
+ *
+ * STREAMING
+ *
+ * The TUI holds back partial markers because it writes to a terminal it cannot
+ * take back. React re-renders from the accumulated string every chunk, so that
+ * problem does not exist here — but an UNCLOSED fence does: mid-stream the text
+ * ends inside a code block. `parseMarkdown` treats a fence with no closing pair
+ * as open to the end, which is what the user is actually looking at, rather than
+ * leaking ``` into the prose.
+ */
+
+export type Span =
+ | { kind: "text"; text: string }
+ | { kind: "bold"; text: string }
+ | { kind: "code"; text: string }
+
+export type Block =
+ | { kind: "p"; spans: Span[] }
+ | { kind: "h"; level: number; spans: Span[] }
+ | { kind: "li"; spans: Span[]; ordered: boolean }
+ | { kind: "code"; lang: string; text: string; open: boolean }
+
+const FENCE = /^\s*```/
+
+/** Inline: **bold** and `code`. Single * is left alone — it is multiplication,
+ * a glob, or a footnote far more often than it is emphasis, and the TUI makes
+ * the same call for the same reason. */
+export function parseInline(line: string): Span[] {
+ const spans: Span[] = []
+ let text = ""
+ let i = 0
+ const flush = () => {
+ if (text) { spans.push({ kind: "text", text }); text = "" }
+ }
+ while (i < line.length) {
+ const ch = line[i]
+ if (ch === "`") {
+ const end = line.indexOf("`", i + 1)
+ if (end > i) {
+ flush()
+ spans.push({ kind: "code", text: line.slice(i + 1, end) })
+ i = end + 1
+ continue
+ }
+ // unterminated: a backtick the model has not closed yet. Show it as text
+ // rather than swallowing the rest of the line into a code span.
+ text += ch; i++; continue
+ }
+ if (ch === "*" && line[i + 1] === "*") {
+ const end = line.indexOf("**", i + 2)
+ if (end > i + 1) {
+ flush()
+ spans.push({ kind: "bold", text: line.slice(i + 2, end) })
+ i = end + 2
+ continue
+ }
+ text += "**"; i += 2; continue
+ }
+ text += ch; i++
+ }
+ flush()
+ return spans
+}
+
+export function parseMarkdown(source: string): Block[] {
+ const lines = source.split("\n")
+ const blocks: Block[] = []
+ let code: { lang: string; body: string[] } | null = null
+ let para: string[] = []
+
+ const flushPara = () => {
+ if (!para.length) return
+ blocks.push({ kind: "p", spans: parseInline(para.join("\n")) })
+ para = []
+ }
+
+ for (const line of lines) {
+ if (FENCE.test(line)) {
+ if (code) {
+ blocks.push({ kind: "code", lang: code.lang, text: code.body.join("\n"), open: false })
+ code = null
+ } else {
+ flushPara()
+ code = { lang: line.trim().slice(3).trim().replace(/`/g, ""), body: [] }
+ }
+ continue
+ }
+ if (code) { code.body.push(line); continue }
+
+ const trimmed = line.trim()
+ if (!trimmed) { flushPara(); continue }
+
+ const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed)
+ if (heading) {
+ flushPara()
+ blocks.push({ kind: "h", level: heading[1].length, spans: parseInline(heading[2]) })
+ continue
+ }
+ const bullet = /^[-*+]\s+(.*)$/.exec(trimmed)
+ if (bullet) {
+ flushPara()
+ blocks.push({ kind: "li", spans: parseInline(bullet[1]), ordered: false })
+ continue
+ }
+ const numbered = /^\d+[.)]\s+(.*)$/.exec(trimmed)
+ if (numbered) {
+ flushPara()
+ blocks.push({ kind: "li", spans: parseInline(numbered[1]), ordered: true })
+ continue
+ }
+ para.push(line)
+ }
+
+ // Mid-stream the answer ends inside the fence it has not closed yet. Emit it
+ // as an open code block: that is what the user is looking at, and it keeps the
+ // ``` out of the prose.
+ if (code) blocks.push({ kind: "code", lang: code.lang, text: code.body.join("\n"), open: true })
+ flushPara()
+ return blocks
+}
+
+/* ---- syntax highlighting -------------------------------------------------
+ *
+ * Deliberately approximate, and small. A real grammar per language is what
+ * highlight.js is for, and it is 100 KB+ for the set people actually paste.
+ * Comments, strings, numbers and keywords carry nearly all the readability, so
+ * that is what this does; anything it cannot classify stays plain, which
+ * degrades to "unhighlighted code" rather than to "wrong colours".
+ */
+
+export type Tok = { kind: "plain" | "kw" | "str" | "num" | "com"; text: string }
+
+const KEYWORDS: Record<string, string[]> = {
+ python: "def class return if elif else for while in not and or is None True False import from as with try except finally raise lambda yield global nonlocal pass break continue assert del await async".split(" "),
+ c: "int char void float double long short unsigned signed const static struct union enum typedef return if else for while do switch case break continue sizeof goto extern inline volatile".split(" "),
+ rust: "fn let mut const struct enum impl trait pub use mod match if else for while loop return self Self where async await move ref dyn type unsafe".split(" "),
+ go: "func var const type struct interface package import return if else for range switch case defer go chan map select break continue fallthrough".split(" "),
+ js: "function const let var return if else for while class extends new this import export from default async await try catch finally throw typeof instanceof null undefined true false".split(" "),
+ sh: "if then else elif fi for while do done case esac function return export local readonly set unset echo cd exit".split(" "),
+}
+KEYWORDS.cpp = KEYWORDS.c
+KEYWORDS.h = KEYWORDS.c
+KEYWORDS.typescript = KEYWORDS.js
+KEYWORDS.ts = KEYWORDS.js
+KEYWORDS.tsx = KEYWORDS.js
+KEYWORDS.javascript = KEYWORDS.js
+KEYWORDS.jsx = KEYWORDS.js
+KEYWORDS.py = KEYWORDS.python
+KEYWORDS.bash = KEYWORDS.sh
+KEYWORDS.shell = KEYWORDS.sh
+KEYWORDS.zsh = KEYWORDS.sh
+
+const LINE_COMMENT: Record<string, string> = {
+ python: "#", py: "#", sh: "#", bash: "#", shell: "#", zsh: "#", yaml: "#", yml: "#", toml: "#",
+}
+
+export function highlight(text: string, lang: string): Tok[] {
+ const key = (lang || "").toLowerCase()
+ const words = KEYWORDS[key]
+ const lineComment = LINE_COMMENT[key] ?? "//"
+ const out: Tok[] = []
+ let plain = ""
+ const flush = () => { if (plain) { out.push({ kind: "plain", text: plain }); plain = "" } }
+
+ let i = 0
+ while (i < text.length) {
+ const rest = text.slice(i)
+
+ if (rest.startsWith(lineComment) || (lineComment === "//" && rest.startsWith("/*"))) {
+ const end = rest.startsWith("/*")
+ ? (text.indexOf("*/", i + 2) < 0 ? text.length : text.indexOf("*/", i + 2) + 2)
+ : (text.indexOf("\n", i) < 0 ? text.length : text.indexOf("\n", i))
+ flush(); out.push({ kind: "com", text: text.slice(i, end) }); i = end; continue
+ }
+
+ const q = text[i]
+ if (q === '"' || q === "'" || q === "`") {
+ let j = i + 1
+ while (j < text.length && text[j] !== q) { if (text[j] === "\\") j++; j++ }
+ // Unterminated string: stop at the newline rather than painting the rest
+ // of the block. Mid-stream code is full of these.
+ const nl = text.indexOf("\n", i)
+ const end = j < text.length ? j + 1 : (nl < 0 ? text.length : nl)
+ flush(); out.push({ kind: "str", text: text.slice(i, end) }); i = end; continue
+ }
+
+ if (/[0-9]/.test(q) && !/[A-Za-z_]/.test(text[i - 1] || "")) {
+ let j = i
+ while (j < text.length && /[0-9a-fA-FxXoObB._]/.test(text[j])) j++
+ flush(); out.push({ kind: "num", text: text.slice(i, j) }); i = j; continue
+ }
+
+ if (words && /[A-Za-z_]/.test(q)) {
+ let j = i
+ while (j < text.length && /[A-Za-z0-9_]/.test(text[j])) j++
+ const word = text.slice(i, j)
+ if (words.includes(word)) { flush(); out.push({ kind: "kw", text: word }); i = j; continue }
+ plain += word; i = j; continue
+ }
+
+ plain += q; i++
+ }
+ flush()
+ return out
+}