pi-splash-server 0.1.0 → 0.1.2

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
@@ -60,16 +60,19 @@ Update with `pi update`. To try it without installing:
60
60
  In Pi:
61
61
 
62
62
  ```text
63
- /splash doctor chip, memory, disk, runtime, recommended model and flags, what is left to download
64
- /splash start start the recommended model in the background and switch to it
65
- /splash status and the next step
66
- /splash use switch to a Splash server started outside Pi
67
- /splash stop stop the server
68
- /splash log last lines of the server log
69
- /splash install put the runtime's install command into the editor
70
- /splash update same for a newer runtime release
63
+ /splash doctor chip, memory, disk, runtime, recommended model and flags, what is left to download
64
+ /splash start [model] start the recommended model, or any repo or repo:QUANT, in the background and switch to it
65
+ /splash status and the next step
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 stop stop the server
69
+ /splash log last lines of the server log
70
+ /splash install put the runtime's install command into the editor
71
+ /splash update same for a newer runtime release
71
72
  ```
72
73
 
74
+ To start a different model, run `/splash stop` first.
75
+
73
76
  `start` and `use` switch the session to the Splash model; `/model` switches
74
77
  back, the server keeps running. The first start downloads the model (the
75
78
  status bar shows what, how much and how fast). Loading takes about one to two
@@ -83,6 +86,14 @@ comes in about 1 s instead of about 10 s on an M1 Pro. Splash 1.7.3 would not
83
86
  keep such a state for a system prompt and tools under 2,048 tokens, as Pi's
84
87
  are, unless the first message is a few words long.
85
88
 
89
+ ## Measure your Mac
90
+
91
+ `/splash bench` measures prompt processing, cache reuse, decode speed and memory
92
+ use for any model started with `/splash start <repo or repo:QUANT>`. Close other
93
+ 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).
96
+
86
97
  ## What it picks
87
98
 
88
99
  Qwen3.8-27B, by memory:
@@ -96,8 +107,8 @@ Qwen3.8-27B, by memory:
96
107
  | 16 GB | `prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0` | `--language-only` |
97
108
 
98
109
  `/splash doctor` shows the evidence for each pick (measured on which Mac, or
99
- not yet). The table lives in `data/recommendations.json`; reports from 16, 24
100
- and 64 GB Macs are welcome.
110
+ not yet). The table lives in `data/recommendations.json`. Reports from
111
+ `/splash bench` on 16, 24 and 64 GB Macs are welcome.
101
112
 
102
113
  ## Settings
103
114
 
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,8 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { runBench } from "../src/bench.ts";
5
+ import { benchReport } from "../src/bench-report.ts";
4
6
  import { detectMac, macosWarning, runtimeFor } from "../src/mac.ts";
5
7
  import { DRAFT_GB, loadEntries, recommend, diskWarnings, isDownloaded } from "../src/recommend.ts";
6
8
  import { bytes, bytesOnDisk, downloadLabel, downloadLines, downloadNotice, gb, planDownload } from "../src/download.ts";
@@ -9,7 +11,7 @@ import { providerConfig, providerName } from "../src/provider.ts";
9
11
  import { countTokens, headKey, needsWarm, opensSession, readWarmed, warm, writeWarmed } from "../src/prewarm.ts";
10
12
  import {
11
13
  DEFAULT_PORT, STATE_DIR, describe, findLauncher, latestRelease, launcherVersion, logPath, probe, readRecord,
12
- start, startedByUs, stop, versionOf, waitReady,
14
+ type ServedModel, servesModel, start, startedByUs, stop, versionOf, waitReady,
13
15
  } from "../src/server.ts";
14
16
 
15
17
  type Config = { port?: number; model?: string; flags?: string[]; stopOnExit?: boolean; keepAwake?: boolean; launcher?: string };
@@ -34,9 +36,8 @@ export default async function (pi: ExtensionAPI) {
34
36
  const atLoad = await probe(port());
35
37
  if (atLoad) pi.registerProvider(providerName(port()), providerConfig(port(), atLoad) as any);
36
38
 
37
- async function register(ctx: any, switchTo: boolean) {
38
- const p = port();
39
- const served = await probe(p);
39
+ async function register(ctx: any, switchTo: boolean, p = port(), known?: ServedModel) {
40
+ const served = known ?? await probe(p);
40
41
  if (!served) return null;
41
42
  pi.registerProvider(providerName(p), providerConfig(p, served) as any);
42
43
  if (switchTo) {
@@ -56,7 +57,7 @@ export default async function (pi: ExtensionAPI) {
56
57
  const mac = detectMac();
57
58
  const { runtime, pick, smaller } = recommend(mac);
58
59
  const l = launcher();
59
- const installed = l.path ? versionOf(launcherVersion(l.path)) : null;
60
+ const installed = l.path ? versionOf(await launcherVersion(l.path)) : null;
60
61
  const [latest, plan] = await Promise.all([
61
62
  l.path ? latestRelease(l.name) : Promise.resolve(null),
62
63
  pick ? planDownload(pick.model, pick.draft, pick.flags.includes("--language-only")).catch((e: Error) => e) : Promise.resolve(null),
@@ -104,19 +105,29 @@ export default async function (pi: ExtensionAPI) {
104
105
 
105
106
  async function startCmd(model: string | undefined, ctx: any) {
106
107
  const p = port();
107
- if (await probe(p)) {
108
- await register(ctx, true);
108
+ const served = await probe(p);
109
+ if (served) {
110
+ if (model && !servesModel(model, served.ids)) {
111
+ ctx.ui.notify(`Port ${p} serves ${served.id}, not ${model}. Switch to what runs: /splash use. Or /splash stop, then /splash start ${model}.`, "error");
112
+ return;
113
+ }
114
+ await register(ctx, true, p, served);
109
115
  ctx.ui.notify(`Splash already serves on port ${p}; using it.`, "info");
110
116
  return;
111
117
  }
112
- if (following) {
113
- ctx.ui.notify(`Already following the start on port ${p}: ${describe(readRecord(p))}.`, "info");
114
- return;
115
- }
116
118
  const running = starting(p);
117
- if (running) {
118
- ctx.ui.notify(`Splash is already starting on port ${p} (${describe(running)}); following it in the status bar.`, "info");
119
- follow(p, running.pid, ownedModel(p), ctx);
119
+ if (following || running) {
120
+ const loading = model && running && !startedByUs(p, running) ? undefined : ownedModel(p);
121
+ if (model && (!loading || !servesModel(model, [loading]))) {
122
+ ctx.ui.notify(`Port ${p} is starting ${loading ?? "an unknown model"}. Switch when ready: /splash use. Or /splash stop, then /splash start ${model}.`, "error");
123
+ return;
124
+ }
125
+ if (following) {
126
+ ctx.ui.notify(`Already following the start on port ${p}: ${describe(readRecord(p))}.`, "info");
127
+ } else if (running) {
128
+ ctx.ui.notify(`Splash is already starting on port ${p} (${describe(running)}); following it in the status bar.`, "info");
129
+ follow(p, running.pid, loading, ctx);
130
+ }
120
131
  return;
121
132
  }
122
133
  const l = launcher();
@@ -145,7 +156,8 @@ export default async function (pi: ExtensionAPI) {
145
156
 
146
157
  function ownedModel(p: number): string | undefined {
147
158
  try {
148
- return JSON.parse(readFileSync(join(STATE_DIR, `owned-${p}.json`), "utf8")).model;
159
+ const { model } = JSON.parse(readFileSync(join(STATE_DIR, `owned-${p}.json`), "utf8"));
160
+ return typeof model === "string" ? model : undefined;
149
161
  } catch {
150
162
  return undefined;
151
163
  }
@@ -194,7 +206,24 @@ export default async function (pi: ExtensionAPI) {
194
206
  ctx?.ui.setStatus("splash", undefined);
195
207
  }
196
208
 
209
+ let bench: { abort: AbortController; done: Promise<void> } | null = null;
210
+
211
+ async function benchmark(long: boolean, ctx: any, signal: AbortSignal) {
212
+ const p = port();
213
+ const progress = (text: string) => ctx.ui.setStatus("splash", `splash: bench ${text}`);
214
+ try {
215
+ 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");
217
+ } catch (e) {
218
+ ctx.ui.notify(`Splash bench: ${signal.aborted ? "aborted" : e instanceof Error ? e.message : String(e)}`, "error");
219
+ } finally {
220
+ bench = null;
221
+ ctx.ui.setStatus("splash", undefined);
222
+ }
223
+ }
224
+
197
225
  async function stopCmd(ctx: any) {
226
+ bench?.abort.abort();
198
227
  const p = port();
199
228
  const record = readRecord(p);
200
229
  if (!record || describe(record) === "not running") {
@@ -221,7 +250,7 @@ export default async function (pi: ExtensionAPI) {
221
250
  }
222
251
  const l = launcher();
223
252
  if (!l.path) return offer(INSTALL[runtime], `Install ${runtime}`, ctx);
224
- const installed = versionOf(launcherVersion(l.path));
253
+ const installed = versionOf(await launcherVersion(l.path));
225
254
  if (!update) {
226
255
  ctx.ui.notify(`${l.name} ${installed ?? "?"} is installed (${l.path}). Newer release: /splash update`, "info");
227
256
  return;
@@ -242,7 +271,11 @@ export default async function (pi: ExtensionAPI) {
242
271
  if (running && startedByUs(p, running)) follow(p, running.pid, ownedModel(p), ctx);
243
272
  });
244
273
 
245
- pi.on("session_shutdown", async () => unfollow());
274
+ pi.on("session_shutdown", async () => {
275
+ unfollow();
276
+ bench?.abort.abort();
277
+ await bench?.done;
278
+ });
246
279
 
247
280
  pi.on("before_provider_request", async (event: any, ctx: any) => {
248
281
  const p = port();
@@ -255,15 +288,15 @@ export default async function (pi: ExtensionAPI) {
255
288
  warmed.add(key);
256
289
  writeWarmed(STATE_DIR, p, pid, warmed);
257
290
  if (!needsWarm(await countTokens(p, event.payload, process.env.SPLASH_API_KEY))) return;
258
- ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
291
+ if (!bench) ctx.ui.setStatus("splash", "splash: caching the system prompt for new sessions");
259
292
  await warm(p, event.payload, process.env.SPLASH_API_KEY);
260
- ctx.ui.setStatus("splash", undefined);
293
+ if (!bench) ctx.ui.setStatus("splash", undefined);
261
294
  });
262
295
 
263
296
  pi.registerCommand("splash", {
264
- description: "Local Splash server: status, doctor, start [model], stop, use, log, install, update",
297
+ description: "Local Splash server: status, doctor, start [model], bench [--long], stop, use, log, install, update",
265
298
  getArgumentCompletions: (prefix: string) => {
266
- const items = ["doctor", "start", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
299
+ const items = ["doctor", "start", "bench", "bench --long", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
267
300
  return items.length ? items : null;
268
301
  },
269
302
  handler: async (args: string, ctx: any) => {
@@ -275,6 +308,13 @@ export default async function (pi: ExtensionAPI) {
275
308
  return ctx.ui.notify((await doctor()).join("\n"), "info");
276
309
  case "start":
277
310
  return startCmd(rest[0], ctx);
311
+ case "bench": {
312
+ if (rest.length && !(rest.length === 1 && rest[0] === "--long")) return ctx.ui.notify("Usage: /splash bench [--long]", "error");
313
+ if (bench) return ctx.ui.notify("A Splash bench is already running.", "info");
314
+ const abort = new AbortController();
315
+ bench = { abort, done: benchmark(rest[0] === "--long", ctx, abort.signal) };
316
+ return;
317
+ }
278
318
  case "stop":
279
319
  return stopCmd(ctx);
280
320
  case "use": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-splash-server",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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,58 @@
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 cell(values: (number | null | undefined)[], digits: number, scale = 1): string {
12
+ const numbers = values.filter((v): v is number => v != null);
13
+ 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(" | ")} |`;
33
+ }
34
+
35
+ export function benchReport(result: BenchResult): string {
36
+ const { environment: env, requests, before, after } = result;
37
+ const mac = [
38
+ env.chip, env.gpuCores && `${env.gpuCores}-core GPU`, `${env.memoryGB} GB`, `macOS ${env.macos}`,
39
+ env.power && `on ${env.power}`, env.lowPower != null && `Low Power Mode ${env.lowPower ? "on" : "off"}`,
40
+ env.thermalWarning && `thermal warning ${env.thermalWarning}`,
41
+ ].filter(Boolean);
42
+ const seconds = Math.round(result.durationMs / 1000);
43
+ 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.`);
47
+
48
+ 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(" "),
57
+ ].join("\n");
58
+ }
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");
@@ -15,6 +16,7 @@ export type Record = {
15
16
  failure?: { kind?: string; message?: string };
16
17
  };
17
18
  export type ServedModel = { id: string; context: number; inputModalities: string[]; laterSystem: boolean };
19
+ type ListedModel = ServedModel & { ids: string[] };
18
20
 
19
21
  export function findLauncher(name: string): string | null {
20
22
  try {
@@ -24,12 +26,8 @@ export function findLauncher(name: string): string | null {
24
26
  }
25
27
  }
26
28
 
27
- export function launcherVersion(path: string): string {
28
- try {
29
- return execFileSync(path, ["--version"], { encoding: "utf8", timeout: 10000 }).trim();
30
- } catch {
31
- return "";
32
- }
29
+ export function launcherVersion(path: string): Promise<string> {
30
+ return commandOutput(path, ["--version"], 10000);
33
31
  }
34
32
 
35
33
  export const RELEASES: { [runtime: string]: string } = { "splash-m1": "paperniuk/splash", splash: "incoai/splash" };
@@ -79,19 +77,29 @@ export function describe(record: Record | null): string {
79
77
 
80
78
  const base = (port: number) => `http://127.0.0.1:${port}`;
81
79
 
82
- async function getJSON(url: string, timeoutMs = 2000): Promise<any> {
80
+ async function getJSON(url: string, abort?: AbortSignal): Promise<any> {
83
81
  try {
84
- 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
+ });
85
87
  return r.ok ? await r.json() : null;
86
88
  } catch {
87
89
  return null;
88
90
  }
89
91
  }
90
92
 
91
- export function parseModels(listing: any): Omit<ServedModel, "laterSystem"> | null {
92
- const m = listing?.data?.[0];
93
+ export function servesModel(requested: string, served: string[]): boolean {
94
+ return served.some((id) => id.toLowerCase() === requested.toLowerCase());
95
+ }
96
+
97
+ export function parseModels(listing: any): Omit<ListedModel, "laterSystem"> | null {
98
+ if (!Array.isArray(listing?.data)) return null;
99
+ const m = listing.data[0];
93
100
  if (!m || m.owned_by !== "splash" || !Number.isInteger(m.context_length) || m.context_length <= 0) return null;
94
- return { id: m.id, context: m.context_length, inputModalities: m.input_modalities ?? ["text"] };
101
+ const ids = listing.data.map((entry: any) => entry?.id).filter((id: unknown) => typeof id === "string");
102
+ return { id: m.id, ids, context: m.context_length, inputModalities: m.input_modalities ?? ["text"] };
95
103
  }
96
104
 
97
105
  export function parseLaterSystem(status: any): boolean {
@@ -100,10 +108,12 @@ export function parseLaterSystem(status: any): boolean {
100
108
  return outcomes.every((o) => o === "native" || o === "patched");
101
109
  }
102
110
 
103
- export async function probe(port: number): Promise<ServedModel | null> {
104
- 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));
105
113
  if (!model) return null;
106
- 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) };
107
117
  }
108
118
 
109
119
  export type StartOptions = { launcher: string; model: string; flags: string[]; port: number; keepAwake: boolean; stopWithPid?: number };
@@ -120,7 +130,7 @@ export function start(o: StartOptions): number {
120
130
  const env = { ...process.env, ...(o.stopWithPid ? { SPLASH_APP_PID: String(o.stopWithPid) } : {}) };
121
131
  const child = spawn(cmd, rest, { detached: true, stdio: ["ignore", out, out], env });
122
132
  child.unref();
123
- 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() }));
124
134
  return child.pid!;
125
135
  }
126
136
 
@@ -132,6 +142,15 @@ export function ownedPid(port: number): number | null {
132
142
  }
133
143
  }
134
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
+
135
154
  export function parentPid(pid: number): number | null {
136
155
  try {
137
156
  const out = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim();
@@ -185,7 +204,8 @@ export async function waitReady(port: number, signal: AbortSignal, onPhase: (tex
185
204
  if (record?.phase === "ready" && (await probe(port))) return record;
186
205
  if (record?.phase === "failed") return record;
187
206
  const pid = ownedPid(port);
188
- 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;
189
209
  await new Promise((r) => setTimeout(r, 1000));
190
210
  }
191
211
  return null;