pi-splash-server 0.1.1 → 0.1.3

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
@@ -64,6 +64,8 @@ In Pi:
64
64
  /splash start [model] start the recommended model, or any repo or repo:QUANT, in the background and switch to it
65
65
  /splash status and the next step
66
66
  /splash use switch to a Splash server started outside Pi
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
67
69
  /splash stop stop the server
68
70
  /splash log last lines of the server log
69
71
  /splash install put the runtime's install command into the editor
@@ -85,6 +87,19 @@ comes in about 1 s instead of about 10 s on an M1 Pro. Splash 1.7.3 would not
85
87
  keep such a state for a system prompt and tools under 2,048 tokens, as Pi's
86
88
  are, unless the first message is a few words long.
87
89
 
90
+ ## Measure your Mac
91
+
92
+ `/splash bench` measures prompt processing, cache reuse, decode speed and memory
93
+ use for any model started with `/splash start <repo or repo:QUANT>`. Close other
94
+ heavy apps and allow a few minutes, or longer with `--long` for a 32K prompt
95
+ if the context allows it.
96
+
97
+ To share the result, run `/splash bench share`. It opens a
98
+ [bench report issue](https://github.com/sady4850/pi-splash-server/issues/new?template=bench.yml)
99
+ with the report filled in; nothing is sent until you press Submit. The report
100
+ has the chip, memory, macOS, runtime, model, server flags (paths and keys
101
+ removed) and the numbers.
102
+
88
103
  ## What it picks
89
104
 
90
105
  Qwen3.8-27B, by memory:
@@ -98,8 +113,8 @@ Qwen3.8-27B, by memory:
98
113
  | 16 GB | `prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0` | `--language-only` |
99
114
 
100
115
  `/splash doctor` shows the evidence for each pick (measured on which Mac, or
101
- not yet). The table lives in `data/recommendations.json`; reports from 16, 24
102
- and 64 GB Macs are welcome.
116
+ not yet). The table lives in `data/recommendations.json`. Reports from
117
+ `/splash bench` on 16, 24 and 64 GB Macs are welcome.
103
118
 
104
119
  ## Settings
105
120
 
package/data/bench.txt ADDED
@@ -0,0 +1,15 @@
1
+ Field notes from the river survey
2
+
3
+ Each station keeps a notebook beside the gauge. At the start of a shift, the observer reads the water level against the brass mark on the east wall. The mark stays in the same place when the gauge is removed for cleaning. In winter a thin sheet of ice sometimes touches the ruler. The observer records that condition before breaking the ice to take a second reading.
4
+
5
+ The notebook has a pair of columns for each visit. The first column holds the reading exactly as it appeared in the field. The second holds the height relative to the survey datum. If the observer has to repeat a reading, both entries stay on the page. A short explanation beside the entry usually settles the matter when the office prepares its monthly tables.
6
+
7
+ At the end of each week a technician walks the bank between the station and the footbridge. Fallen branches can divert a small stream toward the stilling pool. A branch near the inlet can also make the gauge respond slowly to a rising river. The technician draws a plan of the inlet and writes down the distance from the nearest bridge pier. This makes it possible to find the same obstruction after the water has fallen.
8
+
9
+ Samples travel in glass bottles packed upright in a wooden case. A paper label on the cap carries the station code and the local time. A second label sits inside a clear sleeve on the bottle. When the case reaches the laboratory, the receiving clerk compares the two labels with the dispatch sheet before assigning a shelf. Bottles with a broken seal go on a separate tray for review.
10
+
11
+ The afternoon team checks the recorder clock against the office clock. A difference of a minute matters during a sudden rise because the upstream station may see the crest only a few minutes before the lower station. The team enters the difference in the log. The original series keeps the times shown on the recorder, and the working series carries the corrected times.
12
+
13
+ On quiet days the survey boat follows a line marked by two painted posts. One observer holds the sounding rod while another reads the distance from a tape stretched across the deck. The boat returns along the same line for a second pass. Where the bottom is soft, the rod sinks a little farther on each pass. The observer describes the surface in words as well as reporting a depth.
14
+
15
+ Before filing a chart, the office checks its scale against the first and last soundings. A nearby station can help explain a sudden change, but its readings cannot replace a missing page. Gaps remain visible on the chart. A note in the margin tells the next reader where to look for the original notebook and which part of the river the chart covers.
@@ -1,6 +1,9 @@
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";
5
+ import { runBench } from "../src/bench.ts";
6
+ import { benchReport, shareUrl } from "../src/bench-report.ts";
4
7
  import { detectMac, macosWarning, runtimeFor } from "../src/mac.ts";
5
8
  import { DRAFT_GB, loadEntries, recommend, diskWarnings, isDownloaded } from "../src/recommend.ts";
6
9
  import { bytes, bytesOnDisk, downloadLabel, downloadLines, downloadNotice, gb, planDownload } from "../src/download.ts";
@@ -55,7 +58,7 @@ export default async function (pi: ExtensionAPI) {
55
58
  const mac = detectMac();
56
59
  const { runtime, pick, smaller } = recommend(mac);
57
60
  const l = launcher();
58
- const installed = l.path ? versionOf(launcherVersion(l.path)) : null;
61
+ const installed = l.path ? versionOf(await launcherVersion(l.path)) : null;
59
62
  const [latest, plan] = await Promise.all([
60
63
  l.path ? latestRelease(l.name) : Promise.resolve(null),
61
64
  pick ? planDownload(pick.model, pick.draft, pick.flags.includes("--language-only")).catch((e: Error) => e) : Promise.resolve(null),
@@ -204,7 +207,35 @@ export default async function (pi: ExtensionAPI) {
204
207
  ctx?.ui.setStatus("splash", undefined);
205
208
  }
206
209
 
210
+ let bench: { abort: AbortController; done: Promise<void> } | null = null;
211
+
212
+ async function benchmark(long: boolean, ctx: any, signal: AbortSignal) {
213
+ const p = port();
214
+ const progress = (text: string) => ctx.ui.setStatus("splash", `splash: bench ${text}`);
215
+ try {
216
+ const { result, filename } = await runBench(p, long, signal, launcher, progress);
217
+ const share = result.error ? "" : "\nShare: /splash bench share opens a prefilled GitHub issue, you check it and submit";
218
+ ctx.ui.notify(`${benchReport(result)}\nJSON: ~/.pi/agent/splash/${filename}${share}`, result.error ? "error" : "info");
219
+ } catch (e) {
220
+ ctx.ui.notify(`Splash bench: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`, "error");
221
+ } finally {
222
+ bench = null;
223
+ ctx.ui.setStatus("splash", undefined);
224
+ }
225
+ }
226
+
227
+ function shareCmd(ctx: any) {
228
+ const latest = readdirSync(STATE_DIR).filter((f) => /^bench-.*\.json$/.test(f)).sort().pop();
229
+ if (!latest) return ctx.ui.notify("No bench results yet. Run /splash bench first.", "error");
230
+ const url = shareUrl(JSON.parse(readFileSync(join(STATE_DIR, latest), "utf8")));
231
+ execFile("/usr/bin/open", [url], (e) => {
232
+ if (e) ctx.ui.notify(`Could not open the browser. Open this link:\n${url}`, "error");
233
+ else ctx.ui.notify(`Opened a prefilled GitHub issue for ${latest}. Check it and press Submit.`, "info");
234
+ });
235
+ }
236
+
207
237
  async function stopCmd(ctx: any) {
238
+ bench?.abort.abort();
208
239
  const p = port();
209
240
  const record = readRecord(p);
210
241
  if (!record || describe(record) === "not running") {
@@ -231,7 +262,7 @@ export default async function (pi: ExtensionAPI) {
231
262
  }
232
263
  const l = launcher();
233
264
  if (!l.path) return offer(INSTALL[runtime], `Install ${runtime}`, ctx);
234
- const installed = versionOf(launcherVersion(l.path));
265
+ const installed = versionOf(await launcherVersion(l.path));
235
266
  if (!update) {
236
267
  ctx.ui.notify(`${l.name} ${installed ?? "?"} is installed (${l.path}). Newer release: /splash update`, "info");
237
268
  return;
@@ -252,7 +283,11 @@ export default async function (pi: ExtensionAPI) {
252
283
  if (running && startedByUs(p, running)) follow(p, running.pid, ownedModel(p), ctx);
253
284
  });
254
285
 
255
- pi.on("session_shutdown", async () => unfollow());
286
+ pi.on("session_shutdown", async () => {
287
+ unfollow();
288
+ bench?.abort.abort();
289
+ await bench?.done;
290
+ });
256
291
 
257
292
  pi.on("before_provider_request", async (event: any, ctx: any) => {
258
293
  const p = port();
@@ -265,15 +300,15 @@ export default async function (pi: ExtensionAPI) {
265
300
  warmed.add(key);
266
301
  writeWarmed(STATE_DIR, p, pid, warmed);
267
302
  if (!needsWarm(await countTokens(p, event.payload, process.env.SPLASH_API_KEY))) return;
268
- ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
303
+ if (!bench) ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
269
304
  await warm(p, event.payload, process.env.SPLASH_API_KEY);
270
- ctx.ui.setStatus("splash", undefined);
305
+ if (!bench) ctx.ui.setStatus("splash", undefined);
271
306
  });
272
307
 
273
308
  pi.registerCommand("splash", {
274
- description: "Local Splash server: status, doctor, start [model], stop, use, log, install, update",
309
+ description: "Local Splash server: status, doctor, start [model], bench [--long | share], stop, use, log, install, update",
275
310
  getArgumentCompletions: (prefix: string) => {
276
- const items = ["doctor", "start", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
311
+ const items = ["doctor", "start", "bench", "bench --long", "bench share", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
277
312
  return items.length ? items : null;
278
313
  },
279
314
  handler: async (args: string, ctx: any) => {
@@ -285,6 +320,14 @@ export default async function (pi: ExtensionAPI) {
285
320
  return ctx.ui.notify((await doctor()).join("\n"), "info");
286
321
  case "start":
287
322
  return startCmd(rest[0], ctx);
323
+ case "bench": {
324
+ if (rest.length === 1 && rest[0] === "share") return shareCmd(ctx);
325
+ if (rest.length && !(rest.length === 1 && rest[0] === "--long")) return ctx.ui.notify("Usage: /splash bench [--long | share]", "error");
326
+ if (bench) return ctx.ui.notify("A Splash bench is already running.", "info");
327
+ const abort = new AbortController();
328
+ bench = { abort, done: benchmark(rest[0] === "--long", ctx, abort.signal) };
329
+ return;
330
+ }
288
331
  case "stop":
289
332
  return stopCmd(ctx);
290
333
  case "use": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-splash-server",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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",
@@ -0,0 +1,75 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { commandOutput, detectMac } from "./mac.ts";
3
+ import { launcherVersion, ownedFlags, readRecord, startedByUs, versionOf, type ServedModel } from "./server.ts";
4
+
5
+ export function swapGB(text: string): number | null {
6
+ const match = /\bused\s*=\s*([\d.]+)\s*([KMGT])\b/i.exec(text);
7
+ return match ? Number(match[1]) * 1024 ** ("KMGT".indexOf(match[2].toUpperCase()) - 2) : null;
8
+ }
9
+
10
+ export function freeMemoryPercent(text: string): number | null {
11
+ const match = /system-wide memory free percentage:\s*(\d+)%/i.exec(text);
12
+ return match ? Number(match[1]) : null;
13
+ }
14
+
15
+ function publicModel(id?: string): string | undefined {
16
+ return id && /^[\w-][\w.-]*(?:\/[\w-][\w.-]*)?(?::[\w.-]+)?$/.test(id) ? id : undefined;
17
+ }
18
+
19
+ export function serverFlags(command: string): string | null {
20
+ const serve = /(?:^|\s)(?:serve|-m server\.server)(?:\s+|$)/.exec(command);
21
+ if (!serve) return null;
22
+ const internal = serve[0].includes("server.server");
23
+ const args = command.slice(serve.index + serve[0].length).trim();
24
+ const flags = [];
25
+ for (const arg of args.split(/\s+(?=--?[a-z])/i)) {
26
+ const option = /^(--?[\w-]+)(?:[=\s]+(.*))?$/.exec(arg);
27
+ if (!option) {
28
+ if (arg && !internal) flags.push(publicModel(arg) ?? "[redacted]");
29
+ continue;
30
+ }
31
+ if (option[1] === "--port" || (internal && /^--(?:model|binary|serve-record)$/.test(option[1]))) continue;
32
+ const [, name, value] = option;
33
+ flags.push(name);
34
+ if (value) {
35
+ const privateFlag = /key|token$|password|secret|host|user|path|dir|listen|bind|serial|address|url|header/i.test(name);
36
+ const safe = /^[\w.+:%-]+$/.test(value) || (/^--(?:model|draft-model)$/.test(name) && publicModel(value) === value);
37
+ flags.push(safe && !privateFlag ? value : "[redacted]");
38
+ }
39
+ }
40
+ return flags.join(" ");
41
+ }
42
+
43
+ export async function memorySample() {
44
+ const [swap, free] = await Promise.all([commandOutput("sysctl", ["-n", "vm.swapusage"]), commandOutput("memory_pressure", ["-Q"])]);
45
+ return { swapGB: swapGB(swap), freePercent: freeMemoryPercent(free) };
46
+ }
47
+
48
+ export async function environment(port: number, launcher: { name: string; path: string | null }, served: ServedModel & { instanceModel?: string }) {
49
+ const record = readRecord(port);
50
+ const pid = record?.pid;
51
+ const owned = startedByUs(port, record) ? ownedFlags(port) : null;
52
+ const [display, batt, power, therm, command, version] = await Promise.all([
53
+ commandOutput("system_profiler", ["SPDisplaysDataType"]), commandOutput("pmset", ["-g", "batt"]),
54
+ commandOutput("pmset", ["-g"]), commandOutput("pmset", ["-g", "therm"]),
55
+ pid ? commandOutput("ps", ["-o", "args=", "-p", String(pid)]) : "",
56
+ launcher.path ? launcherVersion(launcher.path) : "",
57
+ ]);
58
+ const { chip, memoryGB, macos } = detectMac();
59
+ const cores = /Total Number of Cores:\s*(\d+)/i.exec(display);
60
+ const low = /^\s*lowpowermode\s+([01])\b/im.exec(power);
61
+ const warning = /\bthermal(?: warning)?\s*level\s*[:=]\s*(\w+)/i.exec(therm)?.[1];
62
+ return {
63
+ packageVersion: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version as string,
64
+ chip, memoryGB, macos, gpuCores: cores ? Number(cores[1]) : undefined,
65
+ power: /'AC Power'/.test(batt) ? "AC" : /'Battery Power'/.test(batt) ? "battery" : undefined,
66
+ lowPower: low ? low[1] === "1" : undefined,
67
+ thermalWarning: warning && !/^(0|none|normal|nominal)$/i.test(warning) ? warning : undefined,
68
+ runtime: launcher.name, runtimeVersion: versionOf(version),
69
+ model: publicModel(served.instanceModel) ?? publicModel(served.id) ?? "[local model]", context: served.context, flags: owned ? serverFlags(["serve", ...owned].join(" ")) : serverFlags(command),
70
+ flagsSource: owned ? "start" : "server process",
71
+ };
72
+ }
73
+
74
+ export type BenchEnvironment = Awaited<ReturnType<typeof environment>>;
75
+ export type MemorySample = Awaited<ReturnType<typeof memorySample>>;
@@ -0,0 +1,107 @@
1
+ import type { BenchRequest, BenchResult } from "./bench.ts";
2
+
3
+ export function stats(values: number[]) {
4
+ if (!values.length) return null;
5
+ const sorted = [...values].sort((a, b) => a - b);
6
+ const middle = Math.floor(sorted.length / 2);
7
+ const median = sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
8
+ return { median, min: sorted[0], max: sorted[sorted.length - 1] };
9
+ }
10
+
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);
23
+ const range = stats(numbers);
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");
63
+ }
64
+
65
+ export function benchReport(result: BenchResult): string {
66
+ const { environment: env, requests, before, after } = result;
67
+ const mac = [
68
+ env.chip, env.gpuCores && `${env.gpuCores}-core GPU`, `${env.memoryGB} GB`, `macOS ${env.macos}`,
69
+ env.power && `on ${env.power}`, env.lowPower != null && `Low Power Mode ${env.lowPower ? "on" : "off"}`,
70
+ env.thermalWarning && `thermal warning ${env.thermalWarning}`,
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)));
81
+ const seconds = Math.round(result.durationMs / 1000);
82
+ const memory = [];
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 ?? "?"}%`);
85
+
86
+ return [
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.`,
94
+ ].join("\n");
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/bench.ts ADDED
@@ -0,0 +1,189 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { environment, memorySample, type BenchEnvironment, type MemorySample } from "./bench-env.ts";
5
+ import { probe, STATE_DIR } from "./server.ts";
6
+
7
+ export const BENCH_VERSION = 1;
8
+
9
+ const code = `Rewrite this TypeScript function with clearer names and add input validation. Answer only with code.
10
+
11
+ function group(a: { day: string; site: string; value: number }[], n: number) {
12
+ const m = new Map<string, number[]>();
13
+ const d = new Map<string, Set<string>>();
14
+ for (const x of a) {
15
+ const k = x.site;
16
+ let v = m.get(k);
17
+ if (!v) {
18
+ v = [];
19
+ m.set(k, v);
20
+ }
21
+ v.push(x.value);
22
+ let s = d.get(k);
23
+ if (!s) {
24
+ s = new Set();
25
+ d.set(k, s);
26
+ }
27
+ s.add(x.day);
28
+ }
29
+ const r = [];
30
+ for (const [k, v] of m) {
31
+ if (v.length < n) continue;
32
+ let t = 0;
33
+ let lo = v[0];
34
+ let hi = v[0];
35
+ for (const x of v) {
36
+ t += x;
37
+ if (x < lo) lo = x;
38
+ if (x > hi) hi = x;
39
+ }
40
+ r.push({
41
+ site: k,
42
+ days: d.get(k)!.size,
43
+ count: v.length,
44
+ mean: t / v.length,
45
+ low: lo,
46
+ high: hi,
47
+ });
48
+ }
49
+ return r.sort((x, y) => y.mean - x.mean);
50
+ }`;
51
+
52
+ const prose = "Explain in about 250 words how a hash map handles collisions. Write plain prose.";
53
+ const nonce = () => `bench ${randomBytes(12).toString("hex")}`;
54
+ const user = (content: string) => ({ role: "user", content });
55
+
56
+ export async function buildPrompt(source: string, prefix: string, target: number, count: (prompt: string) => Promise<number>, limit = target * 1.05) {
57
+ if (!source || limit < target * 0.95) throw new Error(`Could not fit a ${target}-token prompt`);
58
+ let length = target * 4;
59
+ let lower = 0;
60
+ let upper = Infinity;
61
+ for (let i = 0; i < 24; i++) {
62
+ const prompt = prefix + "\n" + source.repeat(Math.ceil(length / source.length)).slice(0, length);
63
+ const tokens = await count(prompt);
64
+ if (!Number.isInteger(tokens) || tokens <= 0) throw new Error("Invalid input_tokens from count_tokens");
65
+ if (tokens >= target * 0.95 && tokens <= Math.min(target * 1.05, limit)) return prompt;
66
+ if (tokens < target * 0.95) lower = length;
67
+ else upper = length;
68
+ if (upper - lower <= 1 || lower >= target * 64) break;
69
+ length = Number.isFinite(upper) ? Math.floor((lower + upper) / 2) : Math.min(length * 2, Math.ceil(length * target / tokens));
70
+ }
71
+ throw new Error(`Could not fit a ${target}-token prompt`);
72
+ }
73
+
74
+ function numericFields(obj: any): Record<string, number> {
75
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([, value]) => Number.isFinite(value))) as Record<string, number>;
76
+ }
77
+
78
+ export function parseMeasurement(response: any) {
79
+ const usage = response?.usage;
80
+ if (!Number.isFinite(usage?.prompt_tokens) || !Number.isFinite(usage?.completion_tokens)) throw new Error("Missing token usage");
81
+ const latency = numericFields(response.metrics?.request_latency);
82
+ const timings = numericFields(response.timings);
83
+ const cached = usage.prompt_tokens_details?.cached_tokens;
84
+ return {
85
+ promptTokens: Number(usage.prompt_tokens), completionTokens: Number(usage.completion_tokens),
86
+ cachedTokens: Number.isFinite(cached) ? Number(cached) : null, ttftMs: latency.ttft_ms ?? latency.wall_ms ?? null,
87
+ timings, latency,
88
+ draftAcceptance: timings.draft_n > 0 && timings.draft_n_accepted != null ? timings.draft_n_accepted / timings.draft_n : null,
89
+ };
90
+ }
91
+
92
+ type Group = "warm-up" | "prefill 1K" | "prefill 8K" | "replay 8K" | "code" | "prose" | "prefill 32K";
93
+ export type BenchRequest = { test: Group } & ReturnType<typeof parseMeasurement>;
94
+ export type BenchResult = {
95
+ benchVersion: number; startedAt: string; durationMs: number; long: boolean; environment: BenchEnvironment;
96
+ before: MemorySample; after: MemorySample; requests: BenchRequest[]; counts: { test: Group; inputTokens: number }[];
97
+ note?: string; error?: string;
98
+ };
99
+
100
+ type Message = { role: string; content: string };
101
+ type Launcher = { name: string; path: string | null };
102
+ type Progress = (step: string) => void;
103
+
104
+ async function workloads(port: number, model: string, signal: AbortSignal, progress: Progress, result: BenchResult) {
105
+ const { context } = result.environment;
106
+ const url = `http://127.0.0.1:${port}/v1/chat/completions`;
107
+ const apiKey = process.env.SPLASH_API_KEY;
108
+ const headers = { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) };
109
+ const base = { model, reasoning_effort: "none", temperature: 0 };
110
+ const source = await readFile(new URL("../data/bench.txt", import.meta.url), "utf8");
111
+ const long = result.long && context >= 32768;
112
+ if (result.long && !long) result.note = `Skipped 32K prefill (${context} context).`;
113
+ let step = 0;
114
+ let test: Group = "warm-up";
115
+
116
+ function begin(group: Group) {
117
+ test = group;
118
+ progress(`${++step}/${long ? 13 : 12} ${test}`);
119
+ }
120
+
121
+ async function post(messages: Message[], maxTokens?: number) {
122
+ const path = maxTokens === undefined ? "/count_tokens" : "";
123
+ const body = maxTokens === undefined ? { ...base, messages } : { ...base, messages, stream: false, max_completion_tokens: maxTokens };
124
+ const response = await fetch(url + path, {
125
+ method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.any([signal, AbortSignal.timeout(30 * 60_000)]),
126
+ });
127
+ if (!response.ok) {
128
+ await response.body?.cancel();
129
+ throw new Error(`${path ? "count_tokens" : "chat/completions"} returned HTTP ${response.status} ${response.statusText}`);
130
+ }
131
+ return response.json();
132
+ }
133
+
134
+ async function measure(messages: Message[], maxTokens: number) {
135
+ result.requests.push({ test, ...parseMeasurement(await post(messages, maxTokens)) });
136
+ }
137
+
138
+ async function prefill(group: Group, target: number) {
139
+ begin(group);
140
+ const prompt = await buildPrompt(source, nonce(), target, async (content) => {
141
+ const { input_tokens } = await post([user(content)]);
142
+ result.counts.push({ test, inputTokens: input_tokens });
143
+ return input_tokens;
144
+ }, context - 1);
145
+ const messages = [user(prompt)];
146
+ await measure(messages, 1);
147
+ return messages;
148
+ }
149
+
150
+ try {
151
+ begin("warm-up");
152
+ await post([user("Hi")], 1);
153
+ for (let i = 0; i < 3; i++) await prefill("prefill 1K", 1024);
154
+ const messages = await prefill("prefill 8K", 8192);
155
+ begin("replay 8K");
156
+ await measure(messages, 1);
157
+ for (const group of ["code", "prose"] as const) {
158
+ for (let i = 0; i < 3; i++) {
159
+ begin(group);
160
+ await measure([{ role: "system", content: nonce() }, user(group === "code" ? code : prose)], 256);
161
+ }
162
+ }
163
+ if (long) await prefill("prefill 32K", 32768);
164
+ } catch (e) {
165
+ result.error = `${test}: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`;
166
+ }
167
+ }
168
+
169
+ export async function runBench(port: number, long: boolean, signal: AbortSignal, launcher: () => Launcher, progress: Progress) {
170
+ const start = new Date();
171
+ progress("checking server");
172
+ const served = await probe(port, signal);
173
+ signal.throwIfAborted();
174
+ if (!served) throw new Error(`No Splash server on port ${port}. Start one: /splash start`);
175
+ progress("collecting environment");
176
+ const env = await environment(port, launcher(), served);
177
+ const before = await memorySample();
178
+ const result: BenchResult = {
179
+ benchVersion: BENCH_VERSION, startedAt: start.toISOString(), durationMs: 0, long,
180
+ environment: env, before, after: before, requests: [], counts: [],
181
+ };
182
+ await workloads(port, served.id, signal, progress, result);
183
+ result.after = await memorySample();
184
+ result.durationMs = Date.now() - start.getTime();
185
+ const filename = `bench-${result.startedAt}.json`;
186
+ await mkdir(STATE_DIR, { recursive: true });
187
+ await writeFile(join(STATE_DIR, filename), JSON.stringify(result, null, 2) + "\n", { mode: 0o600 });
188
+ return { result, filename };
189
+ }
package/src/mac.ts CHANGED
@@ -1,6 +1,17 @@
1
- import { execFileSync } from "node:child_process";
1
+ import { execFile, execFileSync } from "node:child_process";
2
2
  import { statfsSync } from "node:fs";
3
3
  import { homedir, totalmem } from "node:os";
4
+ import { promisify } from "node:util";
5
+
6
+ const exec = promisify(execFile);
7
+
8
+ export async function commandOutput(cmd: string, args: string[], timeout = 5000): Promise<string> {
9
+ try {
10
+ return (await exec(cmd, args, { timeout, encoding: "utf8" })).stdout.trim();
11
+ } catch {
12
+ return "";
13
+ }
14
+ }
4
15
 
5
16
  export type Mac = {
6
17
  chip: string;
package/src/server.ts CHANGED
@@ -2,6 +2,7 @@ import { spawn, execFileSync } from "node:child_process";
2
2
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { commandOutput } from "./mac.ts";
5
6
 
6
7
  export const DEFAULT_PORT = 8000;
7
8
  export const RUNTIME_DIR = join(homedir(), "Library/Application Support/Splash/runtime");
@@ -25,12 +26,8 @@ export function findLauncher(name: string): string | null {
25
26
  }
26
27
  }
27
28
 
28
- export function launcherVersion(path: string): string {
29
- try {
30
- return execFileSync(path, ["--version"], { encoding: "utf8", timeout: 10000 }).trim();
31
- } catch {
32
- return "";
33
- }
29
+ export function launcherVersion(path: string): Promise<string> {
30
+ return commandOutput(path, ["--version"], 10000);
34
31
  }
35
32
 
36
33
  export const RELEASES: { [runtime: string]: string } = { "splash-m1": "paperniuk/splash", splash: "incoai/splash" };
@@ -80,9 +77,13 @@ export function describe(record: Record | null): string {
80
77
 
81
78
  const base = (port: number) => `http://127.0.0.1:${port}`;
82
79
 
83
- async function getJSON(url: string, timeoutMs = 2000): Promise<any> {
80
+ async function getJSON(url: string, abort?: AbortSignal): Promise<any> {
84
81
  try {
85
- const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
82
+ const timeout = AbortSignal.timeout(2000);
83
+ const r = await fetch(url, {
84
+ headers: process.env.SPLASH_API_KEY ? { authorization: `Bearer ${process.env.SPLASH_API_KEY}` } : {},
85
+ signal: abort ? AbortSignal.any([timeout, abort]) : timeout,
86
+ });
86
87
  return r.ok ? await r.json() : null;
87
88
  } catch {
88
89
  return null;
@@ -107,10 +108,12 @@ export function parseLaterSystem(status: any): boolean {
107
108
  return outcomes.every((o) => o === "native" || o === "patched");
108
109
  }
109
110
 
110
- export async function probe(port: number): Promise<ListedModel | null> {
111
- const model = parseModels(await getJSON(`${base(port)}/v1/models`));
111
+ export async function probe(port: number, signal?: AbortSignal): Promise<(ListedModel & { instanceModel?: string }) | null> {
112
+ const model = parseModels(await getJSON(`${base(port)}/v1/models`, signal));
112
113
  if (!model) return null;
113
- return { ...model, laterSystem: parseLaterSystem(await getJSON(`${base(port)}/status`)) };
114
+ const status = await getJSON(`${base(port)}/status`, signal);
115
+ return { ...model, instanceModel: typeof status?.instance?.model === "string" ? status.instance.model : undefined,
116
+ laterSystem: parseLaterSystem(status) };
114
117
  }
115
118
 
116
119
  export type StartOptions = { launcher: string; model: string; flags: string[]; port: number; keepAwake: boolean; stopWithPid?: number };
@@ -127,7 +130,7 @@ export function start(o: StartOptions): number {
127
130
  const env = { ...process.env, ...(o.stopWithPid ? { SPLASH_APP_PID: String(o.stopWithPid) } : {}) };
128
131
  const child = spawn(cmd, rest, { detached: true, stdio: ["ignore", out, out], env });
129
132
  child.unref();
130
- writeFileSync(join(STATE_DIR, `owned-${o.port}.json`), JSON.stringify({ pid: child.pid, model: o.model, started: new Date().toISOString() }));
133
+ writeFileSync(join(STATE_DIR, `owned-${o.port}.json`), JSON.stringify({ pid: child.pid, model: o.model, flags: o.flags, started: new Date().toISOString() }));
131
134
  return child.pid!;
132
135
  }
133
136
 
@@ -139,6 +142,15 @@ export function ownedPid(port: number): number | null {
139
142
  }
140
143
  }
141
144
 
145
+ export function ownedFlags(port: number): string[] | null {
146
+ try {
147
+ const { flags } = JSON.parse(readFileSync(join(STATE_DIR, `owned-${port}.json`), "utf8"));
148
+ return Array.isArray(flags) && flags.every((f) => typeof f === "string") ? flags : null;
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+
142
154
  export function parentPid(pid: number): number | null {
143
155
  try {
144
156
  const out = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim();
@@ -192,7 +204,8 @@ export async function waitReady(port: number, signal: AbortSignal, onPhase: (tex
192
204
  if (record?.phase === "ready" && (await probe(port))) return record;
193
205
  if (record?.phase === "failed") return record;
194
206
  const pid = ownedPid(port);
195
- if (pid && !alive(pid) && Date.now() - t0 > 5000) return record;
207
+ const owner = pid !== null && alive(pid);
208
+ if (!owner && (!record || !alive(record.pid)) && Date.now() - t0 > 5000) return record;
196
209
  await new Promise((r) => setTimeout(r, 1000));
197
210
  }
198
211
  return null;