pi-splash-server 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +124 -2
- package/data/recommendations.json +80 -0
- package/extensions/splash.ts +310 -0
- package/package.json +58 -4
- package/src/download.ts +111 -0
- package/src/mac.ts +47 -0
- package/src/netbytes.ts +100 -0
- package/src/prewarm.ts +80 -0
- package/src/provider.ts +31 -0
- package/src/recommend.ts +55 -0
- package/src/server.ts +214 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sady4850
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,125 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-splash-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run a local [Splash](https://github.com/incoai/splash) server from inside
|
|
4
|
+
[Pi](https://pi.dev), with the model and flags picked for your Mac. On M1/M2 it
|
|
5
|
+
drives [splash-m1](https://github.com/paperniuk/splash), on M3 and newer
|
|
6
|
+
official Splash.
|
|
7
|
+
|
|
8
|
+

|
|
9
|
+
|
|
10
|
+
Splash itself already writes a Pi provider (`splash-m1 pi`), but the server has
|
|
11
|
+
to be started by hand with flags you have to know. This package starts it in
|
|
12
|
+
the background, shows download and load progress in Pi's status bar, and
|
|
13
|
+
switches the session to it when it is ready.
|
|
14
|
+
|
|
15
|
+
## Against plain mlx-lm
|
|
16
|
+
|
|
17
|
+
Ten Pi tasks over a small repository (explain it, find a script, edit the
|
|
18
|
+
README, new sessions, `-c` follow-ups, server restarts), one run each, on an
|
|
19
|
+
M1 Pro 32 GB with the same weights, `mlx-community/Qwen3.8-27B-GPTQ-4bit`,
|
|
20
|
+
thinking on. Splash is splash-m1 1.7.3-m1 started by this package, with its
|
|
21
|
+
DFlash2 draft; mlx-lm is `mlx_lm.server` 0.32.2 started the way
|
|
22
|
+
`@taoc/pi-mlx-models` starts it, with no draft. All answers were right on both.
|
|
23
|
+
|
|
24
|
+
| | Splash | mlx-lm |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| Decode | 24.5 tok/s | 9.3 tok/s |
|
|
27
|
+
| Prompt processing | 91-166 tok/s | 48-55 tok/s |
|
|
28
|
+
| All ten tasks, Pi wall time | 329 s | 1,057 s |
|
|
29
|
+
| First task on a cold server, start included | 125 s | 418 s |
|
|
30
|
+
| First token of a new session on a running server | 0.7-0.8 s | 0.6-1.0 s |
|
|
31
|
+
| Server start until the first token | ~62 s | ~35 s |
|
|
32
|
+
|
|
33
|
+
mlx-lm answers at once and loads the model on the first request; Splash loads,
|
|
34
|
+
warms up and checks its Neural Engine split before it says ready, then wins
|
|
35
|
+
from the first task on. The draft model is a large part of the decode gap and
|
|
36
|
+
exists only on the Splash side.
|
|
37
|
+
|
|
38
|
+
## Requirements
|
|
39
|
+
|
|
40
|
+
- Apple silicon Mac. M1/M2 need macOS 26.4 or newer (splash-m1).
|
|
41
|
+
- The Splash runtime. `/splash install` puts the install command for your
|
|
42
|
+
chip into Pi's editor as a `!!` shell line; you see it and press Enter:
|
|
43
|
+
- M1/M2: `curl -fsSL https://github.com/paperniuk/splash/releases/latest/download/install-m1.sh | sh`
|
|
44
|
+
- M3 and newer: `brew install incoai/tap/splash`
|
|
45
|
+
- Disk for the model: 11-23 GB depending on the tier (weights plus a 3.9 GB
|
|
46
|
+
draft model), and some more for Splash's SSD prompt cache (~25 GB free is
|
|
47
|
+
comfortable).
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pi install npm:pi-splash-server
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Update with `pi update`. To try it without installing:
|
|
56
|
+
`pi -e npm:pi-splash-server`.
|
|
57
|
+
|
|
58
|
+
## Use
|
|
59
|
+
|
|
60
|
+
In Pi:
|
|
61
|
+
|
|
62
|
+
```text
|
|
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 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
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
To start a different model, run `/splash stop` first.
|
|
74
|
+
|
|
75
|
+
`start` and `use` switch the session to the Splash model; `/model` switches
|
|
76
|
+
back, the server keeps running. The first start downloads the model (the
|
|
77
|
+
status bar shows what, how much and how fast). Loading takes about one to two
|
|
78
|
+
minutes; the first start also calibrates the Neural Engine on M1/M2. The
|
|
79
|
+
server outlives Pi, so the next Pi session finds it ready.
|
|
80
|
+
|
|
81
|
+
The first session on a server sends one extra one-token request with Pi's
|
|
82
|
+
system prompt and tools before its own. Splash keeps a state where that
|
|
83
|
+
request ends, so every later new session starts from it: its first token
|
|
84
|
+
comes in about 1 s instead of about 10 s on an M1 Pro. Splash 1.7.3 would not
|
|
85
|
+
keep such a state for a system prompt and tools under 2,048 tokens, as Pi's
|
|
86
|
+
are, unless the first message is a few words long.
|
|
87
|
+
|
|
88
|
+
## What it picks
|
|
89
|
+
|
|
90
|
+
Qwen3.8-27B, by memory:
|
|
91
|
+
|
|
92
|
+
| Memory | Model | Flags |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| 64 GB+ | `unsloth/Qwen3.8-27B-GGUF:UD-Q5_K_S` | |
|
|
95
|
+
| 36 GB+ | `unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M` | |
|
|
96
|
+
| 32 GB | `mlx-community/Qwen3.8-27B-GPTQ-4bit` | `--language-only --max-context 64K --max-memory 21G` |
|
|
97
|
+
| 24 GB | `ISTA-DASLab/Qwen3.8-27B-GSQ-RCO-GGUF:IQ3_S` | `--language-only` |
|
|
98
|
+
| 16 GB | `prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0` | `--language-only` |
|
|
99
|
+
|
|
100
|
+
`/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.
|
|
103
|
+
|
|
104
|
+
## Settings
|
|
105
|
+
|
|
106
|
+
All optional, in `~/.pi/agent/splash/config.json`:
|
|
107
|
+
|
|
108
|
+
| Key | Default | |
|
|
109
|
+
| --- | --- | --- |
|
|
110
|
+
| `port` | `8000` | Server port. The provider is `splash`, or `splash-<port>` on another port. |
|
|
111
|
+
| `model` | recommended | Model to start, e.g. `mlx-community/Qwen3.8-27B-GPTQ-4bit` or `repo:VARIANT` for GGUF. |
|
|
112
|
+
| `flags` | recommended | Extra `serve` flags, replacing the recommended ones. |
|
|
113
|
+
| `stopOnExit` | `false` | Stop the server when Pi exits. |
|
|
114
|
+
| `keepAwake` | `true` | Keep the Mac from idle sleep while the server runs (`caffeinate -i`). |
|
|
115
|
+
| `launcher` | on PATH | Path to `splash-m1` or `splash`. |
|
|
116
|
+
|
|
117
|
+
## omp
|
|
118
|
+
|
|
119
|
+
The extension also loads in [omp](https://github.com/can1357/oh-my-pi):
|
|
120
|
+
`omp plugin install pi-splash-server`. If your omp config already has a
|
|
121
|
+
provider named `splash`, rename it: the extension registers its own `splash`.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
{
|
|
2
|
+
"updated": "2026-11-24",
|
|
3
|
+
"source": "https://github.com/paperniuk/splash/blob/m1/docs/quants.md",
|
|
4
|
+
"entries": [
|
|
5
|
+
{
|
|
6
|
+
"minMemoryGB": 64,
|
|
7
|
+
"runtimes": [
|
|
8
|
+
"splash-m1",
|
|
9
|
+
"splash"
|
|
10
|
+
],
|
|
11
|
+
"model": "unsloth/Qwen3.8-27B-GGUF:UD-Q5_K_S",
|
|
12
|
+
"flags": [],
|
|
13
|
+
"weightsGB": 18.67,
|
|
14
|
+
"evidence": "closeness measured on M1 Pro; speed on M1 Pro and M2 Max",
|
|
15
|
+
"note": "Closest to bf16 of the measured files, about 20% slower decode than MLX 4-bit on M1 Pro.",
|
|
16
|
+
"draft": "incoai/Qwen3.8-27B-DFlash2"
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"minMemoryGB": 36,
|
|
20
|
+
"runtimes": [
|
|
21
|
+
"splash-m1",
|
|
22
|
+
"splash"
|
|
23
|
+
],
|
|
24
|
+
"model": "unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M",
|
|
25
|
+
"flags": [],
|
|
26
|
+
"weightsGB": 16.46,
|
|
27
|
+
"evidence": "closeness measured on M1 Pro; speed on M1 Pro and M2 Max",
|
|
28
|
+
"note": "Closest of the 4-bit files, 1.3 GB more than MLX 4-bit.",
|
|
29
|
+
"draft": "incoai/Qwen3.8-27B-DFlash2"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"minMemoryGB": 32,
|
|
33
|
+
"runtimes": [
|
|
34
|
+
"splash-m1",
|
|
35
|
+
"splash"
|
|
36
|
+
],
|
|
37
|
+
"model": "mlx-community/Qwen3.8-27B-GPTQ-4bit",
|
|
38
|
+
"flags": [
|
|
39
|
+
"--language-only",
|
|
40
|
+
"--max-context",
|
|
41
|
+
"64K",
|
|
42
|
+
"--max-memory",
|
|
43
|
+
"21G"
|
|
44
|
+
],
|
|
45
|
+
"weightsGB": 15.13,
|
|
46
|
+
"evidence": "measured on M1 Pro 32 GB (1.7.1-m1 and 1.7.3-m1), Pi tasks 4/4",
|
|
47
|
+
"note": "MLX 4-bit layout and speed, GPTQ rounding: KL to bf16 29% lower on wiki, 47% on chat.",
|
|
48
|
+
"draft": "incoai/Qwen3.8-27B-DFlash2"
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
"minMemoryGB": 24,
|
|
52
|
+
"runtimes": [
|
|
53
|
+
"splash-m1",
|
|
54
|
+
"splash"
|
|
55
|
+
],
|
|
56
|
+
"model": "ISTA-DASLab/Qwen3.8-27B-GSQ-RCO-GGUF:IQ3_S",
|
|
57
|
+
"flags": [
|
|
58
|
+
"--language-only"
|
|
59
|
+
],
|
|
60
|
+
"weightsGB": 11.77,
|
|
61
|
+
"evidence": "closeness measured; fit on a 24 GB Mac not verified",
|
|
62
|
+
"note": "About as close to bf16 as MLX 4-bit, 3.4 GB smaller, slower.",
|
|
63
|
+
"draft": "incoai/Qwen3.8-27B-DFlash2"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"minMemoryGB": 16,
|
|
67
|
+
"runtimes": [
|
|
68
|
+
"splash-m1"
|
|
69
|
+
],
|
|
70
|
+
"model": "prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0",
|
|
71
|
+
"flags": [
|
|
72
|
+
"--language-only"
|
|
73
|
+
],
|
|
74
|
+
"weightsGB": 7,
|
|
75
|
+
"evidence": "splash-m1 README, run with memory capped to 11 GB",
|
|
76
|
+
"note": "Needs: sudo sysctl iogpu.wired_limit_mb=12288 (resets at reboot).",
|
|
77
|
+
"draft": "incoai/Qwen3.8-27B-DFlash2"
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { detectMac, macosWarning, runtimeFor } from "../src/mac.ts";
|
|
5
|
+
import { DRAFT_GB, loadEntries, recommend, diskWarnings, isDownloaded } from "../src/recommend.ts";
|
|
6
|
+
import { bytes, bytesOnDisk, downloadLabel, downloadLines, downloadNotice, gb, planDownload } from "../src/download.ts";
|
|
7
|
+
import { downloadProgress } from "../src/netbytes.ts";
|
|
8
|
+
import { providerConfig, providerName } from "../src/provider.ts";
|
|
9
|
+
import { countTokens, headKey, needsWarm, opensSession, readWarmed, warm, writeWarmed } from "../src/prewarm.ts";
|
|
10
|
+
import {
|
|
11
|
+
DEFAULT_PORT, STATE_DIR, describe, findLauncher, latestRelease, launcherVersion, logPath, probe, readRecord,
|
|
12
|
+
type ServedModel, servesModel, start, startedByUs, stop, versionOf, waitReady,
|
|
13
|
+
} from "../src/server.ts";
|
|
14
|
+
|
|
15
|
+
type Config = { port?: number; model?: string; flags?: string[]; stopOnExit?: boolean; keepAwake?: boolean; launcher?: string };
|
|
16
|
+
|
|
17
|
+
const INSTALL = {
|
|
18
|
+
"splash-m1": "curl -fsSL https://github.com/paperniuk/splash/releases/latest/download/install-m1.sh | sh",
|
|
19
|
+
splash: "brew install incoai/tap/splash",
|
|
20
|
+
};
|
|
21
|
+
const UPDATE = { ...INSTALL, splash: "brew upgrade incoai/tap/splash" };
|
|
22
|
+
|
|
23
|
+
function config(): Config {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(readFileSync(join(STATE_DIR, "config.json"), "utf8"));
|
|
26
|
+
} catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export default async function (pi: ExtensionAPI) {
|
|
32
|
+
const port = () => config().port ?? DEFAULT_PORT;
|
|
33
|
+
|
|
34
|
+
const atLoad = await probe(port());
|
|
35
|
+
if (atLoad) pi.registerProvider(providerName(port()), providerConfig(port(), atLoad) as any);
|
|
36
|
+
|
|
37
|
+
async function register(ctx: any, switchTo: boolean, p = port(), known?: ServedModel) {
|
|
38
|
+
const served = known ?? await probe(p);
|
|
39
|
+
if (!served) return null;
|
|
40
|
+
pi.registerProvider(providerName(p), providerConfig(p, served) as any);
|
|
41
|
+
if (switchTo) {
|
|
42
|
+
const model = ctx.modelRegistry.find(providerName(p), served.id);
|
|
43
|
+
if (model && !(await pi.setModel(model))) ctx.ui.notify("Could not switch to the Splash model", "error");
|
|
44
|
+
}
|
|
45
|
+
return served;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function launcher(): { name: string; path: string | null } {
|
|
49
|
+
const c = config();
|
|
50
|
+
const name = runtimeFor(detectMac().family) ?? "splash";
|
|
51
|
+
return { name, path: c.launcher ?? findLauncher(name) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function doctor(): Promise<string[]> {
|
|
55
|
+
const mac = detectMac();
|
|
56
|
+
const { runtime, pick, smaller } = recommend(mac);
|
|
57
|
+
const l = launcher();
|
|
58
|
+
const installed = l.path ? versionOf(launcherVersion(l.path)) : null;
|
|
59
|
+
const [latest, plan] = await Promise.all([
|
|
60
|
+
l.path ? latestRelease(l.name) : Promise.resolve(null),
|
|
61
|
+
pick ? planDownload(pick.model, pick.draft, pick.flags.includes("--language-only")).catch((e: Error) => e) : Promise.resolve(null),
|
|
62
|
+
]);
|
|
63
|
+
const lines = [
|
|
64
|
+
`${mac.chip}, ${mac.memoryGB} GB, macOS ${mac.macos}, ${mac.freeDiskGB.toFixed(1)} GB free`,
|
|
65
|
+
!l.path
|
|
66
|
+
? `Runtime: ${runtime ?? "none"} not installed. Install: /splash install`
|
|
67
|
+
: `Runtime: ${l.name} ${installed ?? "?"}${latest === installed ? ", latest" : ""} (${l.path})`,
|
|
68
|
+
];
|
|
69
|
+
if (l.path && latest && latest !== installed) lines.push(` ${latest} is out. Update: /splash update`);
|
|
70
|
+
let downloadGB = 0;
|
|
71
|
+
if (!pick) lines.push("No measured model fits this Mac yet.");
|
|
72
|
+
else {
|
|
73
|
+
lines.push(`Recommended: ${pick.model} ${pick.flags.join(" ")}`.trim());
|
|
74
|
+
lines.push(` ${pick.note}`, ` Evidence: ${pick.evidence}`);
|
|
75
|
+
if (plan instanceof Error || !plan) {
|
|
76
|
+
const have = isDownloaded(pick.model);
|
|
77
|
+
downloadGB = have ? 0 : pick.weightsGB + DRAFT_GB;
|
|
78
|
+
lines.push(` Hugging Face Hub not reachable (${(plan as Error)?.message ?? "no plan"}), so files are not checked.`);
|
|
79
|
+
lines.push(have ? " Model looks downloaded; the draft is not checked." : ` Download: about ${downloadGB.toFixed(1)} GB with the draft.`);
|
|
80
|
+
} else {
|
|
81
|
+
downloadGB = bytes(plan.flatMap((r) => r.missing)) / 1e9;
|
|
82
|
+
lines.push(...downloadLines(plan).map((x) => ` ${x}`));
|
|
83
|
+
}
|
|
84
|
+
if (smaller) lines.push(`Smaller: ${smaller.model} (${smaller.weightsGB} GB)`);
|
|
85
|
+
}
|
|
86
|
+
const macos = macosWarning(runtime, mac.macos);
|
|
87
|
+
for (const w of [...(macos ? [macos] : []), ...diskWarnings(mac, downloadGB)]) lines.push(`Warning: ${w}`);
|
|
88
|
+
return lines;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function status(ctx: any) {
|
|
92
|
+
const p = port();
|
|
93
|
+
const record = readRecord(p);
|
|
94
|
+
const served = await probe(p);
|
|
95
|
+
const lines = [`Port ${p}: ${describe(record)}${record && startedByUs(p, record) ? " (started by pi-splash-server)" : ""}`];
|
|
96
|
+
if (served) lines.push(`Model ${served.id}, ${served.context.toLocaleString()} context tokens`);
|
|
97
|
+
const phase = describe(record);
|
|
98
|
+
if (served && ctx.model?.provider !== providerName(p)) lines.push("Switch to it: /splash use");
|
|
99
|
+
else if (!served && (phase === "not running" || phase.startsWith("failed"))) lines.push("Start one: /splash start");
|
|
100
|
+
else if (served && record && startedByUs(p, record)) lines.push("Stop it: /splash stop");
|
|
101
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function startCmd(model: string | undefined, ctx: any) {
|
|
105
|
+
const p = port();
|
|
106
|
+
const served = await probe(p);
|
|
107
|
+
if (served) {
|
|
108
|
+
if (model && !servesModel(model, served.ids)) {
|
|
109
|
+
ctx.ui.notify(`Port ${p} serves ${served.id}, not ${model}. Switch to what runs: /splash use. Or /splash stop, then /splash start ${model}.`, "error");
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
await register(ctx, true, p, served);
|
|
113
|
+
ctx.ui.notify(`Splash already serves on port ${p}; using it.`, "info");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
const running = starting(p);
|
|
117
|
+
if (following || running) {
|
|
118
|
+
const loading = model && running && !startedByUs(p, running) ? undefined : ownedModel(p);
|
|
119
|
+
if (model && (!loading || !servesModel(model, [loading]))) {
|
|
120
|
+
ctx.ui.notify(`Port ${p} is starting ${loading ?? "an unknown model"}. Switch when ready: /splash use. Or /splash stop, then /splash start ${model}.`, "error");
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (following) {
|
|
124
|
+
ctx.ui.notify(`Already following the start on port ${p}: ${describe(readRecord(p))}.`, "info");
|
|
125
|
+
} else if (running) {
|
|
126
|
+
ctx.ui.notify(`Splash is already starting on port ${p} (${describe(running)}); following it in the status bar.`, "info");
|
|
127
|
+
follow(p, running.pid, loading, ctx);
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const l = launcher();
|
|
132
|
+
if (!l.path) {
|
|
133
|
+
ctx.ui.notify((await doctor()).join("\n"), "error");
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const c = config();
|
|
137
|
+
const { pick } = recommend(detectMac());
|
|
138
|
+
const chosen = model || c.model || pick?.model;
|
|
139
|
+
if (!chosen) {
|
|
140
|
+
ctx.ui.notify("No model given and none recommended for this Mac.", "error");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const flags = c.flags ?? (chosen === pick?.model ? pick.flags : []);
|
|
144
|
+
const pid = start({ launcher: l.path, model: chosen, flags, port: p, keepAwake: c.keepAwake ?? true, stopWithPid: c.stopOnExit ? process.pid : undefined });
|
|
145
|
+
ctx.ui.notify(`Starting ${[chosen, ...flags].join(" ")}. Progress in the status bar; Pi stays usable. Log: ${logPath(p)}`, "info");
|
|
146
|
+
follow(p, pid, chosen, ctx, flags);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function starting(p: number) {
|
|
150
|
+
const record = readRecord(p);
|
|
151
|
+
const phase = describe(record);
|
|
152
|
+
return record && phase !== "not running" && !phase.startsWith("failed") ? record : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function ownedModel(p: number): string | undefined {
|
|
156
|
+
try {
|
|
157
|
+
const { model } = JSON.parse(readFileSync(join(STATE_DIR, `owned-${p}.json`), "utf8"));
|
|
158
|
+
return typeof model === "string" ? model : undefined;
|
|
159
|
+
} catch {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
let following: AbortController | null = null;
|
|
165
|
+
|
|
166
|
+
async function follow(p: number, pid: number, model: string | undefined, ctx: any, flags?: string[]) {
|
|
167
|
+
const abort = (following = new AbortController());
|
|
168
|
+
let progress: ReturnType<typeof downloadProgress> | null = null;
|
|
169
|
+
try {
|
|
170
|
+
if (model) {
|
|
171
|
+
const draft = loadEntries().find((e) => e.model === model)?.draft;
|
|
172
|
+
const f = flags ?? config().flags ?? recommend(detectMac()).pick?.flags ?? [];
|
|
173
|
+
const plan = await planDownload(model, draft, f.includes("--language-only")).catch(() => null);
|
|
174
|
+
const missing = plan ? bytes(plan.flatMap((r) => r.missing)) : null;
|
|
175
|
+
if (abort.signal.aborted) return;
|
|
176
|
+
if (plan && missing) ctx.ui.notify(downloadNotice(plan), "info");
|
|
177
|
+
if (missing !== 0) progress = downloadProgress(pid, missing, plan ? () => bytesOnDisk(plan) : undefined, plan ? downloadLabel(plan) : "");
|
|
178
|
+
} else {
|
|
179
|
+
progress = downloadProgress(pid, null);
|
|
180
|
+
}
|
|
181
|
+
const record = await waitReady(p, abort.signal, (t) => ctx.ui.setStatus("splash", `splash: ${t}`), progress?.text);
|
|
182
|
+
if (abort.signal.aborted) return;
|
|
183
|
+
ctx.ui.setStatus("splash", undefined);
|
|
184
|
+
if (record?.phase === "ready") {
|
|
185
|
+
const served = await register(ctx, true);
|
|
186
|
+
ctx.ui.notify(`Splash ready: ${served?.id}, ${served?.context.toLocaleString()} context tokens (back: /model)`, "info");
|
|
187
|
+
} else {
|
|
188
|
+
ctx.ui.notify(`Splash did not start: ${describe(record)}. Log: ${logPath(p)}`, "error");
|
|
189
|
+
}
|
|
190
|
+
} catch (e: any) {
|
|
191
|
+
try {
|
|
192
|
+
ctx.ui.setStatus("splash", undefined);
|
|
193
|
+
ctx.ui.notify(`Lost track of the Splash start: ${e?.message ?? e}. Log: ${logPath(p)}`, "error");
|
|
194
|
+
} catch {}
|
|
195
|
+
} finally {
|
|
196
|
+
progress?.stop();
|
|
197
|
+
if (following === abort) following = null;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function unfollow(ctx?: any) {
|
|
202
|
+
following?.abort();
|
|
203
|
+
following = null;
|
|
204
|
+
ctx?.ui.setStatus("splash", undefined);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function stopCmd(ctx: any) {
|
|
208
|
+
const p = port();
|
|
209
|
+
const record = readRecord(p);
|
|
210
|
+
if (!record || describe(record) === "not running") {
|
|
211
|
+
ctx.ui.notify("No Splash server running.", "info");
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (!startedByUs(p, record) && !(await ctx.ui.confirm("Stop Splash?", `The server on port ${p} was not started by pi-splash-server.`))) return;
|
|
215
|
+
unfollow(ctx);
|
|
216
|
+
const stopped = await stop(p, record);
|
|
217
|
+
const onIt = stopped && ctx.model?.provider === providerName(p) ? ` The session is still on ${ctx.model.provider}/${ctx.model.id}; switch with /model.` : "";
|
|
218
|
+
ctx.ui.notify(stopped ? `Splash stopped.${onIt}` : "Splash did not stop within 60 s.", "info");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function offer(command: string, what: string, ctx: any) {
|
|
222
|
+
ctx.ui.setEditorText(`!!${command}`);
|
|
223
|
+
ctx.ui.notify(`${what}: the command is in the editor, press Enter to run it (or copy it to a terminal). Then /splash doctor.\n${command}`, "info");
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function installCmd(update: boolean, ctx: any) {
|
|
227
|
+
const runtime = runtimeFor(detectMac().family);
|
|
228
|
+
if (!runtime) {
|
|
229
|
+
ctx.ui.notify("Splash runs on Apple silicon only.", "error");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const l = launcher();
|
|
233
|
+
if (!l.path) return offer(INSTALL[runtime], `Install ${runtime}`, ctx);
|
|
234
|
+
const installed = versionOf(launcherVersion(l.path));
|
|
235
|
+
if (!update) {
|
|
236
|
+
ctx.ui.notify(`${l.name} ${installed ?? "?"} is installed (${l.path}). Newer release: /splash update`, "info");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const latest = await latestRelease(l.name);
|
|
240
|
+
if (latest && latest === installed) {
|
|
241
|
+
ctx.ui.notify(`${l.name} ${installed} is the latest release.`, "info");
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const running = await probe(port());
|
|
245
|
+
offer(UPDATE[l.name as keyof typeof UPDATE], `Update ${l.name} ${installed ?? "?"} to ${latest ?? "the latest release"}${running ? "; restart the server afterwards (/splash stop, /splash start)" : ""}`, ctx);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
249
|
+
if ((await register(ctx, false)) || following) return;
|
|
250
|
+
const p = port();
|
|
251
|
+
const running = starting(p);
|
|
252
|
+
if (running && startedByUs(p, running)) follow(p, running.pid, ownedModel(p), ctx);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
pi.on("session_shutdown", async () => unfollow());
|
|
256
|
+
|
|
257
|
+
pi.on("before_provider_request", async (event: any, ctx: any) => {
|
|
258
|
+
const p = port();
|
|
259
|
+
if (ctx.model?.provider !== providerName(p) || !opensSession(event.payload)) return;
|
|
260
|
+
const pid = readRecord(p)?.pid;
|
|
261
|
+
if (!pid) return;
|
|
262
|
+
const key = headKey(event.payload);
|
|
263
|
+
const warmed = readWarmed(STATE_DIR, p, pid);
|
|
264
|
+
if (warmed.has(key)) return;
|
|
265
|
+
warmed.add(key);
|
|
266
|
+
writeWarmed(STATE_DIR, p, pid, warmed);
|
|
267
|
+
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");
|
|
269
|
+
await warm(p, event.payload, process.env.SPLASH_API_KEY);
|
|
270
|
+
ctx.ui.setStatus("splash", undefined);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
pi.registerCommand("splash", {
|
|
274
|
+
description: "Local Splash server: status, doctor, start [model], stop, use, log, install, update",
|
|
275
|
+
getArgumentCompletions: (prefix: string) => {
|
|
276
|
+
const items = ["doctor", "start", "stop", "use", "log", "install", "update"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s }));
|
|
277
|
+
return items.length ? items : null;
|
|
278
|
+
},
|
|
279
|
+
handler: async (args: string, ctx: any) => {
|
|
280
|
+
const [cmd, ...rest] = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
281
|
+
switch (cmd) {
|
|
282
|
+
case undefined:
|
|
283
|
+
return status(ctx);
|
|
284
|
+
case "doctor":
|
|
285
|
+
return ctx.ui.notify((await doctor()).join("\n"), "info");
|
|
286
|
+
case "start":
|
|
287
|
+
return startCmd(rest[0], ctx);
|
|
288
|
+
case "stop":
|
|
289
|
+
return stopCmd(ctx);
|
|
290
|
+
case "use": {
|
|
291
|
+
const served = await register(ctx, true);
|
|
292
|
+
return ctx.ui.notify(served ? `Using Splash: ${served.id}, ${served.context.toLocaleString()} context tokens (back: /model)` : `No ready Splash server on port ${port()}.`, served ? "info" : "error");
|
|
293
|
+
}
|
|
294
|
+
case "log": {
|
|
295
|
+
let text = "";
|
|
296
|
+
try {
|
|
297
|
+
text = readFileSync(logPath(port()), "utf8").split("\n").slice(-30).join("\n");
|
|
298
|
+
} catch {}
|
|
299
|
+
return ctx.ui.notify(text || "No log yet.", "info");
|
|
300
|
+
}
|
|
301
|
+
case "install":
|
|
302
|
+
return installCmd(false, ctx);
|
|
303
|
+
case "update":
|
|
304
|
+
return installCmd(true, ctx);
|
|
305
|
+
default:
|
|
306
|
+
return ctx.ui.notify(`Unknown: /splash ${cmd}`, "error");
|
|
307
|
+
}
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-splash-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Run a local Splash server from Pi, with the model and flags picked for your Mac (M1/M2 via splash-m1)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/sady4850/pi-splash-server.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/sady4850/pi-splash-server#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/sady4850/pi-splash-server/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"pi-package",
|
|
17
|
+
"omp",
|
|
18
|
+
"oh-my-pi",
|
|
19
|
+
"splash",
|
|
20
|
+
"apple-silicon",
|
|
21
|
+
"local-llm",
|
|
22
|
+
"mlx",
|
|
23
|
+
"gguf"
|
|
24
|
+
],
|
|
25
|
+
"os": [
|
|
26
|
+
"darwin"
|
|
27
|
+
],
|
|
28
|
+
"cpu": [
|
|
29
|
+
"arm64"
|
|
30
|
+
],
|
|
31
|
+
"pi": {
|
|
32
|
+
"extensions": [
|
|
33
|
+
"./extensions/splash.ts"
|
|
34
|
+
],
|
|
35
|
+
"image": "https://raw.githubusercontent.com/sady4850/pi-splash-server/main/media/screenshot.png"
|
|
36
|
+
},
|
|
37
|
+
"omp": {
|
|
38
|
+
"extensions": [
|
|
39
|
+
"./extensions/splash.ts"
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"test": "node --test test/*.test.ts"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"@earendil-works/pi-coding-agent": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"extensions",
|
|
55
|
+
"src",
|
|
56
|
+
"data",
|
|
57
|
+
"README.md",
|
|
58
|
+
"LICENSE"
|
|
59
|
+
]
|
|
60
|
+
}
|
package/src/download.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export type RepoFile = { path: string; size: number; blob: string };
|
|
6
|
+
export type RepoPlan = { repo: string; files: RepoFile[]; missing: RepoFile[]; draft?: boolean };
|
|
7
|
+
|
|
8
|
+
export const HUB = join(homedir(), ".cache/huggingface/hub");
|
|
9
|
+
|
|
10
|
+
async function fetchTree(url: string, timeoutMs: number, tries = 2): Promise<Response> {
|
|
11
|
+
try {
|
|
12
|
+
return await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
13
|
+
} catch (e: any) {
|
|
14
|
+
if (tries > 1) return fetchTree(url, timeoutMs, tries - 1);
|
|
15
|
+
throw new Error(e?.cause?.code ?? (e?.name === "TimeoutError" ? `no answer in ${timeoutMs / 1000} s` : e?.message));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function listRepo(repo: string, timeoutMs = 5000): Promise<RepoFile[]> {
|
|
20
|
+
const r = await fetchTree(`https://huggingface.co/api/models/${repo}/tree/main?recursive=true`, timeoutMs);
|
|
21
|
+
if (!r.ok) throw new Error(`HTTP ${r.status} for ${repo}`);
|
|
22
|
+
const entries: any[] = await r.json();
|
|
23
|
+
return entries
|
|
24
|
+
.filter((e) => e.type === "file")
|
|
25
|
+
.map((e) => ({ path: e.path, size: e.lfs?.size ?? e.size, blob: e.lfs?.oid ?? e.oid }));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const SPLIT = /-\d{5}-of-\d{5}\.gguf$/;
|
|
29
|
+
const isProjector = (path: string) => !path.includes("/") && path.endsWith(".gguf") && /mmproj/i.test(path);
|
|
30
|
+
|
|
31
|
+
export function pickFiles(files: RepoFile[], variant: string | undefined, languageOnly: boolean): RepoFile[] {
|
|
32
|
+
if (!variant) return files.filter((f) => !f.path.includes("/") && f.path.endsWith(".safetensors"));
|
|
33
|
+
const v = variant.toLowerCase();
|
|
34
|
+
const model = files.filter((f) => {
|
|
35
|
+
if (!f.path.endsWith(".gguf") || isProjector(f.path)) return false;
|
|
36
|
+
const name = f.path.replace(SPLIT, "").replace(/\.gguf$/, "").toLowerCase();
|
|
37
|
+
return f.path.includes("/") ? f.path.split("/")[0].toLowerCase() === v : name === v || name.endsWith("-" + v);
|
|
38
|
+
});
|
|
39
|
+
if (languageOnly) return model;
|
|
40
|
+
const projectors = files.filter((f) => isProjector(f.path));
|
|
41
|
+
const projector = ["BF16", "F32", "F16"].map((p) => projectors.find((f) => f.path.toUpperCase().includes(p))).find(Boolean);
|
|
42
|
+
return projector ? [...model, projector] : model;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function missingFiles(repo: string, files: RepoFile[], hub = HUB): RepoFile[] {
|
|
46
|
+
const blobs = join(hub, `models--${repo.replace("/", "--")}`, "blobs");
|
|
47
|
+
return files.filter((f) => {
|
|
48
|
+
try {
|
|
49
|
+
return statSync(join(blobs, f.blob)).size !== f.size;
|
|
50
|
+
} catch {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function planDownload(model: string, draft: string | undefined, languageOnly: boolean, hub = HUB): Promise<RepoPlan[]> {
|
|
57
|
+
const [repo, variant] = model.split(":");
|
|
58
|
+
const wanted: [string, string | undefined][] = [[repo, variant], ...(draft ? [[draft, undefined] as [string, undefined]] : [])];
|
|
59
|
+
return Promise.all(
|
|
60
|
+
wanted.map(async ([r, v], i) => {
|
|
61
|
+
const files = pickFiles(await listRepo(r), v, languageOnly);
|
|
62
|
+
if (!files.length) throw new Error(`no files for ${v ? `${r}:${v}` : r}`);
|
|
63
|
+
return { repo: r, files, missing: missingFiles(r, files, hub), draft: i > 0 };
|
|
64
|
+
}),
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const bytes = (files: RepoFile[]) => files.reduce((s, f) => s + f.size, 0);
|
|
69
|
+
export const gb = (n: number) => `${(n / 1e9).toFixed(1)} GB`;
|
|
70
|
+
|
|
71
|
+
export function downloadLabel(plan: RepoPlan[]): string {
|
|
72
|
+
return plan.filter((r) => r.missing.length).map((r) => (r.draft ? "draft" : "model")).join(" + ");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function downloadNotice(plan: RepoPlan[]): string {
|
|
76
|
+
const missing = plan.filter((r) => r.missing.length);
|
|
77
|
+
return `${gb(bytes(missing.flatMap((r) => r.missing)))} to download: ${missing.map((r) => `${r.draft ? "draft" : "model"} ${r.repo}`).join(", ")}.`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function downloadLines(plan: RepoPlan[]): string[] {
|
|
81
|
+
const missing = plan.flatMap((r) => r.missing);
|
|
82
|
+
if (!missing.length) return [`Downloaded: all ${plan.reduce((n, r) => n + r.files.length, 0)} files in the Hugging Face cache.`];
|
|
83
|
+
return [
|
|
84
|
+
`Download: ${gb(bytes(missing))} of ${gb(bytes(plan.flatMap((r) => r.files)))}`,
|
|
85
|
+
...plan.map((r) => ` ${r.repo}: ${r.missing.length ? `${r.missing.length} of ${r.files.length} files, ${gb(bytes(r.missing))}` : "complete"}`),
|
|
86
|
+
];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function bytesOnDisk(plan: RepoPlan[], hub = HUB): number {
|
|
90
|
+
let total = 0;
|
|
91
|
+
for (const r of plan) {
|
|
92
|
+
const blobs = join(hub, `models--${r.repo.replace("/", "--")}`, "blobs");
|
|
93
|
+
let names: string[] = [];
|
|
94
|
+
try {
|
|
95
|
+
names = readdirSync(blobs);
|
|
96
|
+
} catch {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
for (const f of r.missing) {
|
|
100
|
+
let held = 0;
|
|
101
|
+
for (const n of names) {
|
|
102
|
+
if (n !== f.blob && !n.startsWith(f.blob + ".")) continue;
|
|
103
|
+
try {
|
|
104
|
+
held = Math.max(held, statSync(join(blobs, n)).size);
|
|
105
|
+
} catch {}
|
|
106
|
+
}
|
|
107
|
+
total += Math.min(held, f.size);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return total;
|
|
111
|
+
}
|
package/src/mac.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { statfsSync } from "node:fs";
|
|
3
|
+
import { homedir, totalmem } from "node:os";
|
|
4
|
+
|
|
5
|
+
export type Mac = {
|
|
6
|
+
chip: string;
|
|
7
|
+
family: number | null;
|
|
8
|
+
memoryGB: number;
|
|
9
|
+
freeDiskGB: number;
|
|
10
|
+
macos: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function parseFamily(chip: string): number | null {
|
|
14
|
+
const m = /Apple M(\d+)/.exec(chip);
|
|
15
|
+
return m ? Number(m[1]) : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function runtimeFor(family: number | null): "splash-m1" | "splash" | null {
|
|
19
|
+
if (family === null) return null;
|
|
20
|
+
return family <= 2 ? "splash-m1" : "splash";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function macosWarning(runtime: string | null, version: string): string | null {
|
|
24
|
+
if (runtime !== "splash-m1" || !version) return null;
|
|
25
|
+
const [major, minor = 0] = version.split(".").map(Number);
|
|
26
|
+
return major > 26 || (major === 26 && minor >= 4) ? null : `splash-m1 needs macOS 26.4 or newer; this Mac runs ${version}.`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function run(cmd: string, args: string[]): string {
|
|
30
|
+
try {
|
|
31
|
+
return execFileSync(cmd, args, { encoding: "utf8", timeout: 5000 }).trim();
|
|
32
|
+
} catch {
|
|
33
|
+
return "";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function detectMac(): Mac {
|
|
38
|
+
const chip = run("sysctl", ["-n", "machdep.cpu.brand_string"]) || "unknown";
|
|
39
|
+
const fs = statfsSync(homedir());
|
|
40
|
+
return {
|
|
41
|
+
chip,
|
|
42
|
+
family: parseFamily(chip),
|
|
43
|
+
memoryGB: Math.round(totalmem() / 2 ** 30),
|
|
44
|
+
freeDiskGB: (fs.bavail * fs.bsize) / 1e9,
|
|
45
|
+
macos: run("sw_vers", ["-productVersion"]),
|
|
46
|
+
};
|
|
47
|
+
}
|
package/src/netbytes.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export function descendants(root: number, table = processTable()): Set<number> {
|
|
4
|
+
const tree = new Set([root]);
|
|
5
|
+
for (let grew = true; grew; ) {
|
|
6
|
+
grew = false;
|
|
7
|
+
for (const [pid, ppid] of table) {
|
|
8
|
+
if (tree.has(ppid) && !tree.has(pid)) {
|
|
9
|
+
tree.add(pid);
|
|
10
|
+
grew = true;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return tree;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function processTable(): [number, number][] {
|
|
18
|
+
try {
|
|
19
|
+
return execFileSync("/bin/ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" })
|
|
20
|
+
.trim()
|
|
21
|
+
.split("\n")
|
|
22
|
+
.map((l) => l.trim().split(/\s+/).map(Number) as [number, number]);
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function parseSample(line: string): { pid: number; bytes: number } | null {
|
|
29
|
+
const m = /\.(\d+),(\d+),?$/.exec(line.trim());
|
|
30
|
+
return m ? { pid: Number(m[1]), bytes: Number(m[2]) } : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function samples(output: string): string[][] {
|
|
34
|
+
const out: string[][] = [];
|
|
35
|
+
for (const line of output.split("\n")) {
|
|
36
|
+
if (line.trim() === ",bytes_in,") out.push([]);
|
|
37
|
+
else if (out.length && line.trim()) out[out.length - 1].push(line);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function watchBytesIn(root: number, onTotal: (bytes: number) => void): () => void {
|
|
43
|
+
let total = 0;
|
|
44
|
+
let first = true;
|
|
45
|
+
let stopped = false;
|
|
46
|
+
(async () => {
|
|
47
|
+
while (!stopped) {
|
|
48
|
+
try {
|
|
49
|
+
const tree = descendants(root);
|
|
50
|
+
const out = await new Promise<string>((resolve) =>
|
|
51
|
+
execFile("/usr/bin/nettop", ["-P", "-d", "-L", "2", "-s", "1", "-x", "-J", "bytes_in"], { timeout: 10000 }, (_e, stdout) => resolve(stdout ?? "")),
|
|
52
|
+
);
|
|
53
|
+
if (!out) await new Promise((r) => setTimeout(r, 1000));
|
|
54
|
+
const taken = samples(out);
|
|
55
|
+
for (const sample of first ? taken : taken.slice(-1)) {
|
|
56
|
+
for (const line of sample) {
|
|
57
|
+
const s = parseSample(line);
|
|
58
|
+
if (s && s.bytes > 0 && tree.has(s.pid)) total += s.bytes;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (taken.length) first = false;
|
|
62
|
+
if (!stopped) onTotal(total);
|
|
63
|
+
} catch {
|
|
64
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
})();
|
|
68
|
+
return () => {
|
|
69
|
+
stopped = true;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function progressText(done: number, total: number | null, rate: number, label = ""): string {
|
|
74
|
+
const speed = rate > 0 ? `, ${(rate / 1e6).toFixed(1)} MB/s` : "";
|
|
75
|
+
const what = label ? `downloading ${label}` : "downloading";
|
|
76
|
+
if (!total) return `${what} ${(done / 1e9).toFixed(1)} GB${speed}`;
|
|
77
|
+
const pct = Math.min(99, Math.floor((100 * done) / total));
|
|
78
|
+
const eta = rate > 0 && done < total ? `, ~${Math.ceil((total - done) / rate / 60)} min left` : "";
|
|
79
|
+
return `${what} ${(Math.min(done, total) / 1e9).toFixed(1)} / ${(total / 1e9).toFixed(1)} GB (${pct}%)${speed}${eta}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function downloadProgress(root: number, total: number | null, onDisk: () => number = () => 0, label = "", windowS = 5) {
|
|
83
|
+
const samples: [number, number][] = [];
|
|
84
|
+
let net = 0;
|
|
85
|
+
let seen = false;
|
|
86
|
+
const stop = watchBytesIn(root, (b) => {
|
|
87
|
+
net = b;
|
|
88
|
+
seen = true;
|
|
89
|
+
});
|
|
90
|
+
const text = () => {
|
|
91
|
+
const now = Date.now();
|
|
92
|
+
if (seen) samples.push([now, net]);
|
|
93
|
+
while (samples.length > 2 && now - samples[0][0] > windowS * 1000) samples.shift();
|
|
94
|
+
const [[t0, b0], [t1, b1]] = [samples[0] ?? [now, 0], samples[samples.length - 1] ?? [now, 0]];
|
|
95
|
+
const rate = t1 > t0 ? ((b1 - b0) * 1000) / (t1 - t0) : 0;
|
|
96
|
+
const done = Math.max(net, onDisk());
|
|
97
|
+
return done > 1e6 ? progressText(done, total, rate, label) : null;
|
|
98
|
+
};
|
|
99
|
+
return { text, stop };
|
|
100
|
+
}
|
package/src/prewarm.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export const WARM_TIMEOUT_MS = 180_000;
|
|
6
|
+
export const KEPT_HEAD_TOKENS = 2048;
|
|
7
|
+
const WARM_TAIL_TOKENS = 16;
|
|
8
|
+
|
|
9
|
+
export function needsWarm(warmPromptTokens: number | null): boolean {
|
|
10
|
+
return warmPromptTokens === null || warmPromptTokens - WARM_TAIL_TOKENS < KEPT_HEAD_TOKENS;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function countTokens(port: number, payload: Payload, apiKey?: string): Promise<number | null> {
|
|
14
|
+
try {
|
|
15
|
+
const { stream, max_completion_tokens, ...body } = warmBody(payload);
|
|
16
|
+
const r = await fetch(`http://127.0.0.1:${port}/v1/chat/completions/count_tokens`, {
|
|
17
|
+
method: "POST",
|
|
18
|
+
headers: { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) },
|
|
19
|
+
body: JSON.stringify(body),
|
|
20
|
+
signal: AbortSignal.timeout(10_000),
|
|
21
|
+
});
|
|
22
|
+
const n = r.ok ? (await r.json())?.input_tokens : null;
|
|
23
|
+
return Number.isInteger(n) ? n : null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type Message = { role?: string; content?: unknown };
|
|
30
|
+
type Payload = { messages?: Message[]; tools?: unknown; [key: string]: unknown };
|
|
31
|
+
|
|
32
|
+
export function opensSession(payload: Payload): boolean {
|
|
33
|
+
const m = payload?.messages;
|
|
34
|
+
return Array.isArray(m) && m.length === 2 && m[0]?.role === "system" && m[1]?.role === "user";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function headKey(payload: Payload): string {
|
|
38
|
+
const { messages, stream, stream_options, max_tokens, max_completion_tokens, ...rest } = payload;
|
|
39
|
+
return createHash("sha256").update(JSON.stringify([messages?.[0], rest])).digest("hex").slice(0, 32);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function warmBody(payload: Payload): Payload {
|
|
43
|
+
const { messages, stream, stream_options, max_tokens, ...rest } = payload;
|
|
44
|
+
return { ...rest, messages: [messages![0], { role: "user", content: "." }], stream: false, max_completion_tokens: 1 };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type Warmed = { pid: number; keys: string[] };
|
|
48
|
+
|
|
49
|
+
export function warmedPath(dir: string, port: number) {
|
|
50
|
+
return join(dir, `warmed-${port}.json`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function readWarmed(dir: string, port: number, pid: number): Set<string> {
|
|
54
|
+
try {
|
|
55
|
+
const w: Warmed = JSON.parse(readFileSync(warmedPath(dir, port), "utf8"));
|
|
56
|
+
return new Set(w.pid === pid ? w.keys : []);
|
|
57
|
+
} catch {
|
|
58
|
+
return new Set();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function writeWarmed(dir: string, port: number, pid: number, keys: Set<string>) {
|
|
63
|
+
mkdirSync(dir, { recursive: true });
|
|
64
|
+
writeFileSync(warmedPath(dir, port), JSON.stringify({ pid, keys: [...keys].slice(-64) }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function warm(port: number, payload: Payload, apiKey?: string): Promise<boolean> {
|
|
68
|
+
try {
|
|
69
|
+
const r = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: { "content-type": "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) },
|
|
72
|
+
body: JSON.stringify(warmBody(payload)),
|
|
73
|
+
signal: AbortSignal.timeout(WARM_TIMEOUT_MS),
|
|
74
|
+
});
|
|
75
|
+
await r.text();
|
|
76
|
+
return r.ok;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ServedModel } from "./server.ts";
|
|
2
|
+
import { DEFAULT_PORT } from "./server.ts";
|
|
3
|
+
|
|
4
|
+
export const RESPONSE_TOKENS = 32768;
|
|
5
|
+
|
|
6
|
+
export function providerName(port: number) {
|
|
7
|
+
return port === DEFAULT_PORT ? "splash" : `splash-${port}`;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function providerConfig(port: number, served: ServedModel, env = process.env) {
|
|
11
|
+
const input = served.inputModalities.includes("image") ? ["text", "image"] : ["text"];
|
|
12
|
+
return {
|
|
13
|
+
name: `Splash (local, port ${port})`,
|
|
14
|
+
baseUrl: `http://127.0.0.1:${port}/v1`,
|
|
15
|
+
api: "openai-completions",
|
|
16
|
+
apiKey: env.SPLASH_API_KEY ? "$SPLASH_API_KEY" : "local",
|
|
17
|
+
models: [
|
|
18
|
+
{
|
|
19
|
+
id: served.id,
|
|
20
|
+
name: served.id,
|
|
21
|
+
reasoning: true,
|
|
22
|
+
thinkingLevelMap: { off: "none" },
|
|
23
|
+
input,
|
|
24
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
25
|
+
contextWindow: served.context,
|
|
26
|
+
maxTokens: RESPONSE_TOKENS,
|
|
27
|
+
...(served.laterSystem ? { compat: { supportsMidConvoSystemMessages: true } } : {}),
|
|
28
|
+
},
|
|
29
|
+
],
|
|
30
|
+
};
|
|
31
|
+
}
|
package/src/recommend.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { Mac } from "./mac.ts";
|
|
5
|
+
import { runtimeFor } from "./mac.ts";
|
|
6
|
+
|
|
7
|
+
export type Entry = {
|
|
8
|
+
minMemoryGB: number;
|
|
9
|
+
runtimes: string[];
|
|
10
|
+
model: string;
|
|
11
|
+
flags: string[];
|
|
12
|
+
weightsGB: number;
|
|
13
|
+
draft?: string;
|
|
14
|
+
evidence: string;
|
|
15
|
+
note: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function loadEntries(): Entry[] {
|
|
19
|
+
const url = new URL("../data/recommendations.json", import.meta.url);
|
|
20
|
+
return JSON.parse(readFileSync(url, "utf8")).entries;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function recommend(mac: Pick<Mac, "family" | "memoryGB">, entries = loadEntries()) {
|
|
24
|
+
const runtime = runtimeFor(mac.family);
|
|
25
|
+
const fitting = entries
|
|
26
|
+
.filter((e) => runtime && e.runtimes.includes(runtime) && e.minMemoryGB <= mac.memoryGB)
|
|
27
|
+
.sort((a, b) => b.minMemoryGB - a.minMemoryGB);
|
|
28
|
+
return { runtime, pick: fitting[0] ?? null, smaller: fitting[1] ?? null };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const SPLASH_FREE_GB = 10.7;
|
|
32
|
+
export const DRAFT_GB = 3.85;
|
|
33
|
+
|
|
34
|
+
export function diskWarnings(mac: Pick<Mac, "freeDiskGB">, downloadGB: number): string[] {
|
|
35
|
+
const out: string[] = [];
|
|
36
|
+
const need = downloadGB + SPLASH_FREE_GB;
|
|
37
|
+
if (mac.freeDiskGB < need) {
|
|
38
|
+
out.push(`Free disk ${mac.freeDiskGB.toFixed(1)} GB, need about ${need.toFixed(0)} GB.`);
|
|
39
|
+
}
|
|
40
|
+
const cacheGB = Math.max(0, (mac.freeDiskGB - downloadGB - SPLASH_FREE_GB) / 4);
|
|
41
|
+
if (cacheGB < 4) {
|
|
42
|
+
out.push(`SSD prompt cache will get about ${cacheGB.toFixed(1)} GB: new sessions re-read their prompt more often. Free ~25 GB for a useful cache.`);
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isDownloaded(model: string, hub = join(homedir(), ".cache/huggingface/hub")): boolean {
|
|
48
|
+
const [repo, quant] = model.split(":");
|
|
49
|
+
const snapshots = join(hub, `models--${repo.replace("/", "--")}`, "snapshots");
|
|
50
|
+
if (!existsSync(snapshots)) return false;
|
|
51
|
+
return readdirSync(snapshots).some((rev) => {
|
|
52
|
+
const files = readdirSync(join(snapshots, rev), { recursive: true }).map(String);
|
|
53
|
+
return quant ? files.some((f) => f.endsWith(".gguf") && f.includes(quant)) : files.some((f) => f.endsWith(".safetensors"));
|
|
54
|
+
});
|
|
55
|
+
}
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
2
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_PORT = 8000;
|
|
7
|
+
export const RUNTIME_DIR = join(homedir(), "Library/Application Support/Splash/runtime");
|
|
8
|
+
export const STATE_DIR = join(homedir(), ".pi/agent/splash");
|
|
9
|
+
|
|
10
|
+
export type Phase = "starting" | "loading" | "warming" | "ready" | "recovering" | "failed";
|
|
11
|
+
export type Record = {
|
|
12
|
+
pid: number;
|
|
13
|
+
phase: Phase;
|
|
14
|
+
warmup?: { steps_done: number; steps: number };
|
|
15
|
+
failure?: { kind?: string; message?: string };
|
|
16
|
+
};
|
|
17
|
+
export type ServedModel = { id: string; context: number; inputModalities: string[]; laterSystem: boolean };
|
|
18
|
+
type ListedModel = ServedModel & { ids: string[] };
|
|
19
|
+
|
|
20
|
+
export function findLauncher(name: string): string | null {
|
|
21
|
+
try {
|
|
22
|
+
return execFileSync("/usr/bin/which", [name], { encoding: "utf8" }).trim() || null;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function launcherVersion(path: string): string {
|
|
29
|
+
try {
|
|
30
|
+
return execFileSync(path, ["--version"], { encoding: "utf8", timeout: 10000 }).trim();
|
|
31
|
+
} catch {
|
|
32
|
+
return "";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const RELEASES: { [runtime: string]: string } = { "splash-m1": "paperniuk/splash", splash: "incoai/splash" };
|
|
37
|
+
|
|
38
|
+
export function versionOf(text: string): string | null {
|
|
39
|
+
return /Splash\s+(\S+)/.exec(text)?.[1] ?? null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function latestRelease(runtime: string, timeoutMs = 5000): Promise<string | null> {
|
|
43
|
+
try {
|
|
44
|
+
const r = await fetch(`https://github.com/${RELEASES[runtime]}/releases/latest`, { redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
|
|
45
|
+
return /\/releases\/tag\/([^/?#]+)/.exec(r.headers.get("location") ?? "")?.[1] ?? null;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readRecord(port: number): Record | null {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(readFileSync(join(RUNTIME_DIR, `serve-${port}.json`), "utf8"));
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function alive(pid: number): boolean {
|
|
60
|
+
try {
|
|
61
|
+
process.kill(pid, 0);
|
|
62
|
+
return true;
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function describe(record: Record | null): string {
|
|
69
|
+
if (!record) return "not running";
|
|
70
|
+
if (record.phase !== "failed" && !alive(record.pid)) return "not running";
|
|
71
|
+
switch (record.phase) {
|
|
72
|
+
case "warming":
|
|
73
|
+
return record.warmup ? `warming ${record.warmup.steps_done}/${record.warmup.steps}` : "warming";
|
|
74
|
+
case "failed":
|
|
75
|
+
return `failed: ${record.failure?.message ?? record.failure?.kind ?? "unknown"}`;
|
|
76
|
+
default:
|
|
77
|
+
return record.phase;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const base = (port: number) => `http://127.0.0.1:${port}`;
|
|
82
|
+
|
|
83
|
+
async function getJSON(url: string, timeoutMs = 2000): Promise<any> {
|
|
84
|
+
try {
|
|
85
|
+
const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
86
|
+
return r.ok ? await r.json() : null;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function servesModel(requested: string, served: string[]): boolean {
|
|
93
|
+
return served.some((id) => id.toLowerCase() === requested.toLowerCase());
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function parseModels(listing: any): Omit<ListedModel, "laterSystem"> | null {
|
|
97
|
+
if (!Array.isArray(listing?.data)) return null;
|
|
98
|
+
const m = listing.data[0];
|
|
99
|
+
if (!m || m.owned_by !== "splash" || !Number.isInteger(m.context_length) || m.context_length <= 0) return null;
|
|
100
|
+
const ids = listing.data.map((entry: any) => entry?.id).filter((id: unknown) => typeof id === "string");
|
|
101
|
+
return { id: m.id, ids, context: m.context_length, inputModalities: m.input_modalities ?? ["text"] };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function parseLaterSystem(status: any): boolean {
|
|
105
|
+
const outcome = status?.chat_template?.later_system;
|
|
106
|
+
const outcomes = outcome && typeof outcome === "object" ? Object.values(outcome) : [outcome];
|
|
107
|
+
return outcomes.every((o) => o === "native" || o === "patched");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function probe(port: number): Promise<ListedModel | null> {
|
|
111
|
+
const model = parseModels(await getJSON(`${base(port)}/v1/models`));
|
|
112
|
+
if (!model) return null;
|
|
113
|
+
return { ...model, laterSystem: parseLaterSystem(await getJSON(`${base(port)}/status`)) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export type StartOptions = { launcher: string; model: string; flags: string[]; port: number; keepAwake: boolean; stopWithPid?: number };
|
|
117
|
+
|
|
118
|
+
export function logPath(port: number) {
|
|
119
|
+
return join(STATE_DIR, `serve-${port}.log`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function start(o: StartOptions): number {
|
|
123
|
+
mkdirSync(STATE_DIR, { recursive: true });
|
|
124
|
+
const out = openSync(logPath(o.port), "w");
|
|
125
|
+
const args = [o.launcher, "serve", "--model", o.model, ...o.flags, "--port", String(o.port)];
|
|
126
|
+
const [cmd, ...rest] = o.keepAwake ? ["/usr/bin/caffeinate", "-i", ...args] : args;
|
|
127
|
+
const env = { ...process.env, ...(o.stopWithPid ? { SPLASH_APP_PID: String(o.stopWithPid) } : {}) };
|
|
128
|
+
const child = spawn(cmd, rest, { detached: true, stdio: ["ignore", out, out], env });
|
|
129
|
+
child.unref();
|
|
130
|
+
writeFileSync(join(STATE_DIR, `owned-${o.port}.json`), JSON.stringify({ pid: child.pid, model: o.model, started: new Date().toISOString() }));
|
|
131
|
+
return child.pid!;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function ownedPid(port: number): number | null {
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(readFileSync(join(STATE_DIR, `owned-${port}.json`), "utf8")).pid;
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function parentPid(pid: number): number | null {
|
|
143
|
+
try {
|
|
144
|
+
const out = execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf8" }).trim();
|
|
145
|
+
return out ? Number(out) : null;
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function startedByUs(port: number, record: Record | null, parent = parentPid): boolean {
|
|
152
|
+
const owner = ownedPid(port);
|
|
153
|
+
if (!owner || !record) return false;
|
|
154
|
+
for (let pid: number | null = record.pid, i = 0; pid && pid > 1 && i < 8; pid = parent(pid), i++) {
|
|
155
|
+
if (pid === owner) return true;
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function lastLine(log: string, width = 80): string {
|
|
161
|
+
const line = log.split(/[\r\n]/).map((l) => l.trim()).filter(Boolean).pop() ?? "";
|
|
162
|
+
return line.length > width ? line.slice(0, width - 1) + "…" : line;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function logTail(port: number, bytes = 4096): string {
|
|
166
|
+
try {
|
|
167
|
+
const fd = openSync(logPath(port), "r");
|
|
168
|
+
try {
|
|
169
|
+
const size = fstatSync(fd).size;
|
|
170
|
+
const buf = Buffer.alloc(Math.min(bytes, size));
|
|
171
|
+
readSync(fd, buf, 0, buf.length, size - buf.length);
|
|
172
|
+
return buf.toString("utf8");
|
|
173
|
+
} finally {
|
|
174
|
+
closeSync(fd);
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
return "";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function waitReady(port: number, signal: AbortSignal, onPhase: (text: string) => void, starting?: () => string | null): Promise<Record | null> {
|
|
182
|
+
let last = "";
|
|
183
|
+
const t0 = Date.now();
|
|
184
|
+
while (!signal.aborted) {
|
|
185
|
+
const record = readRecord(port);
|
|
186
|
+
const phase = describe(record);
|
|
187
|
+
const text = phase === "starting" || phase === "not running" ? (starting?.() ?? ["starting", lastLine(logTail(port))].filter(Boolean).join(": ")) : phase;
|
|
188
|
+
if (text !== last) {
|
|
189
|
+
onPhase(text);
|
|
190
|
+
last = text;
|
|
191
|
+
}
|
|
192
|
+
if (record?.phase === "ready" && (await probe(port))) return record;
|
|
193
|
+
if (record?.phase === "failed") return record;
|
|
194
|
+
const pid = ownedPid(port);
|
|
195
|
+
if (pid && !alive(pid) && Date.now() - t0 > 5000) return record;
|
|
196
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function stop(port: number, record: Record): Promise<boolean> {
|
|
202
|
+
try {
|
|
203
|
+
process.kill(record.pid, "SIGINT");
|
|
204
|
+
} catch {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
for (let i = 0; i < 60; i++) {
|
|
208
|
+
if (!alive(record.pid)) break;
|
|
209
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
210
|
+
}
|
|
211
|
+
const gone = !alive(record.pid);
|
|
212
|
+
if (gone && existsSync(join(STATE_DIR, `owned-${port}.json`))) rmSync(join(STATE_DIR, `owned-${port}.json`));
|
|
213
|
+
return gone;
|
|
214
|
+
}
|