pi-splash-server 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,17 +65,26 @@ In Pi:
65
65
  /splash status and the next step
66
66
  /splash use switch to a Splash server started outside Pi
67
67
  /splash bench [--long] measure speed and memory use on the running server
68
+ /splash bench share open a prefilled GitHub issue with the last bench report
68
69
  /splash stop stop the server
69
70
  /splash log last lines of the server log
70
71
  /splash install put the runtime's install command into the editor
71
72
  /splash update same for a newer runtime release
72
73
  ```
73
74
 
74
- To start a different model, run `/splash stop` first.
75
+ While you type `/splash start`, Pi suggests the measured Qwen3.8-27B quants
76
+ (type part of a name, like `q5` or `iq3`, to filter) with size,
77
+ which one is recommended for which memory, what is already downloaded, and
78
+ how each trades closeness to bf16 against speed (numbers in
79
+ [quants.md](https://github.com/paperniuk/splash/blob/m1/docs/quants.md)). To
80
+ start a different model, run `/splash stop` first. Models from the list start
81
+ with `--language-only` (no vision weights); the memory flags in the table below
82
+ apply only to the model recommended for your Mac.
75
83
 
76
84
  `start` and `use` switch the session to the Splash model; `/model` switches
77
- back, the server keeps running. The first start downloads the model (the
78
- status bar shows what, how much and how fast). Loading takes about one to two
85
+ back, the server keeps running. When files are missing, `start` says how much
86
+ it will download and how much disk is free, and asks first; the status bar
87
+ then shows what, how much and how fast. Loading takes about one to two
79
88
  minutes; the first start also calibrates the Neural Engine on M1/M2. The
80
89
  server outlives Pi, so the next Pi session finds it ready.
81
90
 
@@ -91,8 +100,13 @@ are, unless the first message is a few words long.
91
100
  `/splash bench` measures prompt processing, cache reuse, decode speed and memory
92
101
  use for any model started with `/splash start <repo or repo:QUANT>`. Close other
93
102
  heavy apps and allow a few minutes, or longer with `--long` for a 32K prompt
94
- if the context allows it. We welcome results as
95
- [issues in this repo](https://github.com/sady4850/pi-splash-server/issues).
103
+ if the context allows it.
104
+
105
+ To share the result, run `/splash bench share`. It opens a
106
+ [bench report issue](https://github.com/sady4850/pi-splash-server/issues/new?template=bench.yml)
107
+ with the report filled in; nothing is sent until you press Submit. The report
108
+ has the chip, memory, macOS, runtime, model, server flags (paths and keys
109
+ removed) and the numbers.
96
110
 
97
111
  ## What it picks
98
112
 
@@ -0,0 +1,14 @@
1
+ {
2
+ "source": "https://github.com/paperniuk/splash/blob/m1/docs/quants.md",
3
+ "measured": "KL to bf16 on wiki and chat text; decode time on M1 Pro relative to MLX 4-bit (percent, + is slower)",
4
+ "models": [
5
+ { "family": "Qwen3.8-27B", "quant": "GPTQ 4-bit", "model": "mlx-community/Qwen3.8-27B-GPTQ-4bit", "weightsGB": 15.13, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0399, "klChat": 0.1002, "decodePct": -0.2 },
6
+ { "family": "Qwen3.8-27B", "quant": "MLX 4-bit", "model": "mlx-community/Qwen3.8-27B-4bit", "weightsGB": 15.13, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0562, "klChat": 0.1906, "decodePct": 0 },
7
+ { "family": "Qwen3.8-27B", "quant": "Q4_0", "model": "unsloth/Qwen3.8-27B-GGUF:Q4_0", "weightsGB": 16.06, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0325, "klChat": 0.1412, "decodePct": 5.9 },
8
+ { "family": "Qwen3.8-27B", "quant": "UD-Q4_K_M", "model": "unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M", "weightsGB": 16.46, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0144, "klChat": 0.0831, "decodePct": 11.1 },
9
+ { "family": "Qwen3.8-27B", "quant": "UD-Q5_K_S", "model": "unsloth/Qwen3.8-27B-GGUF:UD-Q5_K_S", "weightsGB": 18.67, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0065, "klChat": 0.0574, "decodePct": 20.2 },
10
+ { "family": "Qwen3.8-27B", "quant": "SLQ EAR98-Q5_K_S", "model": "kaitchup/Qwen3.8-27B-SLQ-GGUF:EAR98-Q5_K_S", "weightsGB": 18.88, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0104, "klChat": 0.0486, "decodePct": 19.7 },
11
+ { "family": "Qwen3.8-27B", "quant": "GSQ IQ3_S", "model": "ISTA-DASLab/Qwen3.8-27B-GSQ-RCO-GGUF:IQ3_S", "weightsGB": 11.77, "draft": "incoai/Qwen3.8-27B-DFlash2", "klWiki": 0.0573, "klChat": 0.2121, "decodePct": 18.2 },
12
+ { "family": "Ternary-Bonsai-2-27B", "quant": "PQ2_0", "model": "prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0", "weightsGB": 7, "draft": "incoai/Qwen3.8-27B-DFlash2", "needs": "needs wired-limit sysctl" }
13
+ ]
14
+ }
@@ -1,8 +1,10 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { readFileSync } from "node:fs";
2
+ import { execFile } from "node:child_process";
3
+ import { readdirSync, readFileSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { runBench } from "../src/bench.ts";
5
- import { benchReport } from "../src/bench-report.ts";
6
+ import { benchReport, shareUrl } from "../src/bench-report.ts";
7
+ import { loadCatalog, startCompletions } from "../src/catalog.ts";
6
8
  import { detectMac, macosWarning, runtimeFor } from "../src/mac.ts";
7
9
  import { DRAFT_GB, loadEntries, recommend, diskWarnings, isDownloaded } from "../src/recommend.ts";
8
10
  import { bytes, bytesOnDisk, downloadLabel, downloadLines, downloadNotice, gb, planDownload } from "../src/download.ts";
@@ -142,12 +144,36 @@ export default async function (pi: ExtensionAPI) {
142
144
  ctx.ui.notify("No model given and none recommended for this Mac.", "error");
143
145
  return;
144
146
  }
145
- const flags = c.flags ?? (chosen === pick?.model ? pick.flags : []);
147
+ const flags = c.flags ?? (chosen === pick?.model ? pick.flags : loadCatalog().some((m) => m.model === chosen) ? ["--language-only"] : []);
148
+ if (!(await confirmDownload(chosen, flags, ctx))) return ctx.ui.notify("Not started.", "info");
146
149
  const pid = start({ launcher: l.path, model: chosen, flags, port: p, keepAwake: c.keepAwake ?? true, stopWithPid: c.stopOnExit ? process.pid : undefined });
147
150
  ctx.ui.notify(`Starting ${[chosen, ...flags].join(" ")}. Progress in the status bar; Pi stays usable. Log: ${logPath(p)}`, "info");
148
151
  follow(p, pid, chosen, ctx, flags);
149
152
  }
150
153
 
154
+ function draftFor(model: string) {
155
+ return loadEntries().find((e) => e.model === model)?.draft ?? loadCatalog().find((m) => m.model === model)?.draft;
156
+ }
157
+
158
+ async function confirmDownload(model: string, flags: string[], ctx: any) {
159
+ const mac = detectMac();
160
+ const entry = loadCatalog().find((m) => m.model === model);
161
+ const name = entry ? `${entry.family} ${entry.quant}` : model;
162
+ const free = (downloadGB: number) => [
163
+ `${mac.freeDiskGB.toFixed(1)} GB free on disk, about ${Math.max(0, mac.freeDiskGB - downloadGB).toFixed(1)} GB left after. Progress shows in the status bar; Pi stays usable.`,
164
+ ...diskWarnings(mac, downloadGB).map((w) => `Warning: ${w}`)].join("\n");
165
+ const plan = await planDownload(model, draftFor(model), flags.includes("--language-only")).catch(() => null);
166
+ if (plan) {
167
+ const missing = bytes(plan.flatMap((r) => r.missing));
168
+ const parts = plan.map((r) => `${r.draft ? "Draft" : "Model"} ${r.repo}${r.draft || !model.includes(":") ? "" : `:${model.split(":")[1]}`}: ${r.missing.length ? gb(bytes(r.missing)) : "already downloaded"}`);
169
+ return !missing || ctx.ui.confirm(`Download ${name}, ${gb(missing)}?`,
170
+ `From Hugging Face into ~/.cache/huggingface/hub:\n${parts.map((x) => ` ${x}`).join("\n")}\n${free(missing / 1e9)}`);
171
+ }
172
+ if (isDownloaded(model)) return true;
173
+ const size = entry?.weightsGB;
174
+ return ctx.ui.confirm(`Download ${name}?`, `${model}${size ? `, about ${(size + DRAFT_GB).toFixed(1)} GB with the draft` : ""} from Hugging Face into ~/.cache/huggingface/hub (Hugging Face not reachable now to check sizes).\n${free(size ? size + DRAFT_GB : 0)}`);
175
+ }
176
+
151
177
  function starting(p: number) {
152
178
  const record = readRecord(p);
153
179
  const phase = describe(record);
@@ -170,7 +196,7 @@ export default async function (pi: ExtensionAPI) {
170
196
  let progress: ReturnType<typeof downloadProgress> | null = null;
171
197
  try {
172
198
  if (model) {
173
- const draft = loadEntries().find((e) => e.model === model)?.draft;
199
+ const draft = draftFor(model);
174
200
  const f = flags ?? config().flags ?? recommend(detectMac()).pick?.flags ?? [];
175
201
  const plan = await planDownload(model, draft, f.includes("--language-only")).catch(() => null);
176
202
  const missing = plan ? bytes(plan.flatMap((r) => r.missing)) : null;
@@ -207,13 +233,15 @@ export default async function (pi: ExtensionAPI) {
207
233
  }
208
234
 
209
235
  let bench: { abort: AbortController; done: Promise<void> } | null = null;
236
+ let mac: ReturnType<typeof detectMac> | undefined;
210
237
 
211
238
  async function benchmark(long: boolean, ctx: any, signal: AbortSignal) {
212
239
  const p = port();
213
240
  const progress = (text: string) => ctx.ui.setStatus("splash", `splash: bench ${text}`);
214
241
  try {
215
242
  const { result, filename } = await runBench(p, long, signal, launcher, progress);
216
- ctx.ui.notify(`${benchReport(result)}\nJSON: ~/.pi/agent/splash/${filename}`, result.error ? "error" : "info");
243
+ const share = result.error ? "" : "\nShare: /splash bench share opens a prefilled GitHub issue, you check it and submit";
244
+ ctx.ui.notify(`${benchReport(result)}\nJSON: ~/.pi/agent/splash/${filename}${share}`, result.error ? "error" : "info");
217
245
  } catch (e) {
218
246
  ctx.ui.notify(`Splash bench: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`, "error");
219
247
  } finally {
@@ -222,6 +250,16 @@ export default async function (pi: ExtensionAPI) {
222
250
  }
223
251
  }
224
252
 
253
+ function shareCmd(ctx: any) {
254
+ const latest = readdirSync(STATE_DIR).filter((f) => /^bench-.*\.json$/.test(f)).sort().pop();
255
+ if (!latest) return ctx.ui.notify("No bench results yet. Run /splash bench first.", "error");
256
+ const url = shareUrl(JSON.parse(readFileSync(join(STATE_DIR, latest), "utf8")));
257
+ execFile("/usr/bin/open", [url], (e) => {
258
+ if (e) ctx.ui.notify(`Could not open the browser. Open this link:\n${url}`, "error");
259
+ else ctx.ui.notify(`Opened a prefilled GitHub issue for ${latest}. Check it and press Submit.`, "info");
260
+ });
261
+ }
262
+
225
263
  async function stopCmd(ctx: any) {
226
264
  bench?.abort.abort();
227
265
  const p = port();
@@ -294,9 +332,15 @@ export default async function (pi: ExtensionAPI) {
294
332
  });
295
333
 
296
334
  pi.registerCommand("splash", {
297
- description: "Local Splash server: status, doctor, start [model], bench [--long], stop, use, log, install, update",
335
+ description: "Local Splash server: status, doctor, start [model], bench [--long | share], stop, use, log, install, update",
298
336
  getArgumentCompletions: (prefix: string) => {
299
- const items = ["doctor", "start", "bench", "bench --long", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
337
+ const start = /^\s*start(?:\s+(\S*))?$/.exec(prefix);
338
+ if (start) {
339
+ mac ??= detectMac();
340
+ const items = startCompletions(start[1] ?? "", loadCatalog(), recommend(mac).pick, (m) => isDownloaded(m));
341
+ return items.length ? items : null;
342
+ }
343
+ const items = ["doctor", "start", "bench", "bench --long", "bench share", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s === "start" ? "start " : s, label: s }));
300
344
  return items.length ? items : null;
301
345
  },
302
346
  handler: async (args: string, ctx: any) => {
@@ -309,7 +353,8 @@ export default async function (pi: ExtensionAPI) {
309
353
  case "start":
310
354
  return startCmd(rest[0], ctx);
311
355
  case "bench": {
312
- if (rest.length && !(rest.length === 1 && rest[0] === "--long")) return ctx.ui.notify("Usage: /splash bench [--long]", "error");
356
+ if (rest.length === 1 && rest[0] === "share") return shareCmd(ctx);
357
+ if (rest.length && !(rest.length === 1 && rest[0] === "--long")) return ctx.ui.notify("Usage: /splash bench [--long | share]", "error");
313
358
  if (bench) return ctx.ui.notify("A Splash bench is already running.", "info");
314
359
  const abort = new AbortController();
315
360
  bench = { abort, done: benchmark(rest[0] === "--long", ctx, abort.signal) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-splash-server",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Run a local Splash server from Pi, with the model and flags picked for your Mac (M1/M2 via splash-m1)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -8,28 +8,58 @@ export function stats(values: number[]) {
8
8
  return { median, min: sorted[0], max: sorted[sorted.length - 1] };
9
9
  }
10
10
 
11
- function cell(values: (number | null | undefined)[], digits: number, scale = 1): string {
12
- const numbers = values.filter((v): v is number => v != null);
11
+ function present(values: (number | null | undefined)[]) {
12
+ return values.filter((v): v is number => v != null && Number.isFinite(v));
13
+ }
14
+
15
+ function median(values: (number | null | undefined)[]) {
16
+ return stats(present(values))?.median ?? null;
17
+ }
18
+
19
+ const fixed = (n: number | null, digits: number) => n == null ? "-" : n.toFixed(digits);
20
+
21
+ function spread(values: (number | null | undefined)[], digits: number) {
22
+ const numbers = present(values);
13
23
  const range = stats(numbers);
14
- if (!range) return "-";
15
- const format = (n: number) => (n * scale).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: digits });
16
- const median = format(range.median);
17
- return numbers.length > 1 && range.min !== range.max ? `${median} (${format(range.min)}-${format(range.max)})` : median;
18
- }
19
-
20
- function row(test: BenchRequest["test"], runs: BenchRequest[]) {
21
- const decode = test === "code" || test === "prose";
22
- const hits = runs.flatMap((r, i) => (r.cachedTokens ?? 0) > 0 ? [i + 1] : []);
23
- const cached = cell(runs.map(r => r.cachedTokens), 1);
24
- const columns = [
25
- test, cell(runs.map(r => decode ? r.completionTokens : r.promptTokens), 1),
26
- decode ? "-" : cell(runs.map(r => r.ttftMs), 2, 0.001),
27
- test.startsWith("prefill") ? cell(runs.map(r => r.timings.prompt_per_second), 1) : "-",
28
- decode ? cell(runs.map(r => r.timings.predicted_per_second), 1) : "-",
29
- decode ? cell(runs.map(r => r.draftAcceptance), 1, 100) : "-",
30
- test.startsWith("prefill") && hits.length ? `${cached} cache hit #${hits.join(",#")}` : cached,
31
- ];
32
- return `| ${columns.join(" | ")} |`;
24
+ if (numbers.length < 2 || !range) return "";
25
+ return `${numbers.length} runs: ${range.min.toFixed(digits)}-${range.max.toFixed(digits)}`;
26
+ }
27
+
28
+ const labels: Record<BenchRequest["test"], string> = {
29
+ "warm-up": "Warm-up", "prefill 1K": "Prefill 1K", "prefill 8K": "Prefill 8K", "prefill 32K": "Prefill 32K",
30
+ "replay 8K": "Replay 8K", code: "Decode code", prose: "Decode prose",
31
+ };
32
+
33
+ function row(test: BenchRequest["test"], runs: BenchRequest[]): string[] {
34
+ const label = labels[test];
35
+ const tokens = (values: number[]) => `${Math.round(median(values) ?? 0)} tok`;
36
+ if (test === "code" || test === "prose") {
37
+ const speed = runs.map(r => r.timings.predicted_per_second);
38
+ const accepted = median(runs.map(r => r.draftAcceptance));
39
+ const tail = [tokens(runs.map(r => r.completionTokens)), spread(speed, 1)].filter(Boolean).join(", ");
40
+ return [label, fixed(median(speed), 1), "tok/s", "draft", accepted == null ? "-" : `${Math.round(accepted * 100)}%`, tail];
41
+ }
42
+ const ttft = `${fixed(median(runs.map(r => r.ttftMs / 1000)), 2)} s`;
43
+ const prompt = tokens(runs.map(r => r.promptTokens));
44
+ if (test === "replay 8K") {
45
+ const cached = Math.round(median(runs.map(r => r.cachedTokens)) ?? 0);
46
+ return [label, "", "", "TTFT", ttft, `${cached} of ${prompt} cached`];
47
+ }
48
+ const speed = runs.map(r => r.timings.prompt_per_second);
49
+ const hits = runs.flatMap((r, i) => (r.cachedTokens ?? 0) > 0 ? [`#${i + 1}`] : []);
50
+ const tail = [prompt, spread(speed, 1), hits.length && `cache hit in run ${hits.join(", ")}`].filter(Boolean).join(", ");
51
+ return [label, fixed(median(speed), 1), "tok/s", "TTFT", ttft, tail];
52
+ }
53
+
54
+ function align(rows: string[][], right: number[]) {
55
+ const widths = rows[0].map((_, c) => Math.max(...rows.map(r => r[c].length)));
56
+ const gaps = ["", " ", " ", " ", " ", " "];
57
+ return rows.map(r => r.map((cell, c) => gaps[c] + (right.includes(c) ? cell.padStart(widths[c]) : cell.padEnd(widths[c])))
58
+ .join("").trimEnd());
59
+ }
60
+
61
+ function contextLabel(tokens: number) {
62
+ return tokens % 1024 === 0 ? `${tokens / 1024}K` : tokens.toLocaleString("en-US");
33
63
  }
34
64
 
35
65
  export function benchReport(result: BenchResult): string {
@@ -39,20 +69,39 @@ export function benchReport(result: BenchResult): string {
39
69
  env.power && `on ${env.power}`, env.lowPower != null && `Low Power Mode ${env.lowPower ? "on" : "off"}`,
40
70
  env.thermalWarning && `thermal warning ${env.thermalWarning}`,
41
71
  ].filter(Boolean);
72
+ const header: [string, string][] = [
73
+ ["Mac:", mac.join(", ")],
74
+ ["Runtime:", `${env.runtime} ${env.runtimeVersion ?? "unknown version"}`],
75
+ ["Model:", `${env.model}, ${contextLabel(env.context)} context`],
76
+ [env.flagsSource === "start" ? "Flags:" : "Server process flags:", env.flags === null ? "unavailable" : env.flags || "(none)"],
77
+ ];
78
+ const width = Math.max(...header.map(([key]) => key.length)) + 1;
79
+
80
+ const tests = Array.from(new Set(requests.map(r => r.test)), test => row(test, requests.filter(r => r.test === test)));
42
81
  const seconds = Math.round(result.durationMs / 1000);
43
82
  const memory = [];
44
- if (before.swapGB != null || after.swapGB != null) memory.push(`Swap: ${before.swapGB?.toFixed(1) ?? "?"} -> ${after.swapGB?.toFixed(1) ?? "?"} GB.`);
45
- if (before.freePercent != null || after.freePercent != null) memory.push(`Free memory: ${before.freePercent ?? "?"}% -> ${after.freePercent ?? "?"}%.`);
46
- memory.push(`Took ${Math.floor(seconds / 60)} min ${seconds % 60} s.`);
83
+ if (before.swapGB != null || after.swapGB != null) memory.push(`swap ${before.swapGB?.toFixed(1) ?? "?"} -> ${after.swapGB?.toFixed(1) ?? "?"} GB`);
84
+ if (before.freePercent != null || after.freePercent != null) memory.push(`free ${before.freePercent ?? "?"}% -> ${after.freePercent ?? "?"}%`);
47
85
 
48
86
  return [
49
- `pi-splash-server bench v${result.benchVersion} (pi-splash-server ${env.packageVersion})`,
50
- `Mac: ${mac.join(", ")}`, `Runtime: ${env.runtime} ${env.runtimeVersion ?? "unknown version"}`,
51
- `Model: ${env.model}, ${env.context.toLocaleString("en-US")} context`, `${env.flagsSource === "start" ? "Flags" : "Server process flags"}: ${env.flags === null ? "unavailable" : env.flags || "(none)"}`,
52
- "", "Median (min-max) across repeats.", "",
53
- "| test | tokens | TTFT s | prefill tok/s | decode tok/s | draft accepted % | cached |",
54
- "| --- | --- | --- | --- | --- | --- | --- |",
55
- ...Array.from(new Set(requests.map(r => r.test)), test => row(test, requests.filter(r => r.test === test))),
56
- "", ...[result.note, result.error && `Stopped: ${result.error}`].filter(Boolean), memory.join(" "),
87
+ `pi-splash-server ${env.packageVersion}, bench v${result.benchVersion}`,
88
+ ...header.map(([key, value]) => key.padEnd(width) + value),
89
+ "",
90
+ ...(tests.length ? align(tests, [1, 4]) : []),
91
+ "",
92
+ ...[result.note, result.error && `Stopped: ${result.error}`].filter(Boolean),
93
+ `${memory.length ? `Memory: ${memory.join(", ")}. ` : ""}Took ${Math.floor(seconds / 60)} min ${seconds % 60} s.`,
57
94
  ].join("\n");
58
95
  }
96
+
97
+ export const ISSUES_URL = "https://github.com/sady4850/pi-splash-server/issues/new";
98
+
99
+ export function shareUrl(result: BenchResult): string {
100
+ const { chip, memoryGB, model } = result.environment;
101
+ const params = new URLSearchParams({
102
+ template: "bench.yml",
103
+ title: `Bench: ${chip} ${memoryGB} GB, ${model.split("/").pop()}`,
104
+ report: benchReport(result),
105
+ });
106
+ return `${ISSUES_URL}?${params}`;
107
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { readFileSync } from "node:fs";
2
+ import type { Entry } from "./recommend.ts";
3
+
4
+ export type CatalogModel = {
5
+ family: string; quant: string; model: string; weightsGB: number;
6
+ klWiki?: number; klChat?: number; decodePct?: number; needs?: string; draft?: string;
7
+ };
8
+
9
+ export function loadCatalog(): CatalogModel[] {
10
+ return JSON.parse(readFileSync(new URL("../data/models.json", import.meta.url), "utf8")).models;
11
+ }
12
+
13
+ const signed = (n: number, unit: string) => `${n > 0 ? "+" : "-"}${Math.abs(n).toFixed(unit === "%" ? 0 : 1)}${unit}`;
14
+
15
+ function kl(m: CatalogModel, base: CatalogModel | undefined) {
16
+ if (m.klWiki == null || m.klChat == null) return "bf16 closeness not measured";
17
+ if (!base || base.klWiki == null || base.klChat == null) return `KL wiki ${m.klWiki}, chat ${m.klChat}`;
18
+ const change = (a: number, b: number) => {
19
+ if (a / b >= 2) return `×${(a / b).toFixed(1)}`;
20
+ const pct = Math.round((a / b - 1) * 100);
21
+ return pct ? signed(pct, "%") : "same";
22
+ };
23
+ return `KL wiki ${change(m.klWiki, base.klWiki)}, chat ${change(m.klChat, base.klChat)}`;
24
+ }
25
+
26
+ function decode(m: CatalogModel, base: CatalogModel | undefined) {
27
+ if (m.decodePct == null || !base || base.decodePct == null) return null;
28
+ const pct = Math.round(((1 + m.decodePct / 100) / (1 + base.decodePct / 100) - 1) * 100);
29
+ if (Math.abs(pct) < 2) return "decode same";
30
+ return `decode ${Math.abs(pct)}% ${pct > 0 ? "slower" : "faster"}`;
31
+ }
32
+
33
+ export function startCompletions(query: string, catalog: CatalogModel[], pick: Entry | null, downloaded: (model: string) => boolean) {
34
+ const q = query.trim().toLowerCase();
35
+ const base = catalog.find((m) => m.model === pick?.model);
36
+ const family = base?.family ?? catalog[0]?.family;
37
+ const rank = (m: CatalogModel) => (m === base ? [0, 0] : m.family !== family ? [3, m.weightsGB]
38
+ : base && m.weightsGB > base.weightsGB ? [1, m.weightsGB] : [2, -m.weightsGB]);
39
+ return catalog
40
+ .filter((m) => `${m.model} ${m.family} ${m.quant}`.toLowerCase().includes(q))
41
+ .sort((a, b) => rank(a)[0] - rank(b)[0] || a.family.localeCompare(b.family) || rank(a)[1] - rank(b)[1])
42
+ .map((m) => {
43
+ const parts = m === base
44
+ ? ["recommended", downloaded(m.model) ? "downloaded" : "needs download", `${m.weightsGB.toFixed(1)} GB`, "others compared to this", m.needs]
45
+ : [downloaded(m.model) ? "downloaded" : "needs download",
46
+ !base ? `${m.weightsGB.toFixed(1)} GB` : Math.abs(m.weightsGB - base.weightsGB) < 0.05 ? "same size" : signed(m.weightsGB - base.weightsGB, " GB"),
47
+ kl(m, base), decode(m, base), m.needs];
48
+ return { value: `start ${m.model}`, label: `${m.family} · ${m.quant}`, description: parts.filter(Boolean).join(" · ") };
49
+ });
50
+ }