okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-s3: Control bundled in the installer, local engine components, no runtime acquisitionbe885026f

main
6.1 KiB200 linesraw
1/**
2 * Engine installer.
3 *
4 * Strata ships no binaries: it fetches the llama.cpp release build that matches
5 * this platform into $STRATA_HOME/engine, so "Install inference engine" in the
6 * first-run wizard is a real step rather than a progress bar that lies.
7 */
8import { createWriteStream, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs';
9import { join } from 'node:path';
10import { Readable } from 'node:stream';
11import { pipeline } from 'node:stream/promises';
12import { exec } from './util.mjs';
13import { HOME } from './store.mjs';
14import { tarBinary } from './platform-paths.mjs';
15import { nowIso } from './util.mjs';
16import { require as requireAcquisition } from './acquisition.mjs';
17
18const ENGINE_DIR = join(HOME, 'engine');
19const RELEASES = 'https://api.github.com/repos/ggml-org/llama.cpp/releases?per_page=8';
20
21const state = {
22  status: 'idle', // idle | checking | downloading | extracting | done | error
23  pct: 0,
24  mbps: 0,
25  stage: '',
26  asset: null,
27  version: null,
28  error: null,
29  installedPath: null,
30};
31
32let hubRef = null;
33let running = null;
34
35export function init(hub) {
36  hubRef = hub;
37}
38
39export function status() {
40  return { ...state, engineDir: ENGINE_DIR };
41}
42
43function emit() {
44  hubRef?.send('engine-install', status());
45}
46
47/** Which release asset belongs on this machine. */
48function assetMatcher() {
49  const { platform, arch } = process;
50  if (platform === 'darwin') {
51    return {
52      test: (name) => /macos/i.test(name) && (arch === 'arm64' ? /arm64/i.test(name) : /x64|x86_64/i.test(name)) && /\.tar\.gz$/.test(name),
53      ext: 'tar.gz',
54    };
55  }
56  if (platform === 'linux') {
57    return {
58      test: (name) => /ubuntu|linux/i.test(name) && (arch === 'arm64' ? /arm64|aarch64/i.test(name) : /x64|x86_64/i.test(name)) && /\.tar\.gz$/.test(name),
59      ext: 'tar.gz',
60    };
61  }
62  return {
63    test: (name) => /win/i.test(name) && /x64|x86_64/i.test(name) && /\.zip$/.test(name),
64    ext: 'zip',
65  };
66}
67
68export async function findRelease() {
69  requireAcquisition('The llama.cpp engine');
70  state.status = 'checking';
71  state.stage = 'Looking up the current llama.cpp build';
72  emit();
73
74  const res = await fetch(RELEASES, { headers: { accept: 'application/vnd.github+json' }, signal: AbortSignal.timeout(15000) });
75  if (!res.ok) throw new Error(`GitHub responded ${res.status}`);
76  const releases = await res.json();
77  const matcher = assetMatcher();
78
79  for (const release of releases) {
80    const asset = (release.assets ?? []).find((a) => matcher.test(a.name));
81    if (asset) return { asset, version: release.tag_name, ext: matcher.ext };
82  }
83  throw new Error('No matching llama.cpp build found for this platform');
84}
85
86export async function install({ force = false } = {}) {
87  requireAcquisition('The llama.cpp engine');
88  if (running) return running;
89
90  running = (async () => {
91    try {
92      const found = await findRelease();
93      state.asset = found.asset.name;
94      state.version = found.version;
95
96      if (!force) {
97        const existing = findInstalledBinary();
98        if (existing) {
99          state.status = 'done';
100          state.pct = 100;
101          state.stage = `Already installed (${found.version})`;
102          state.installedPath = existing;
103          emit();
104          return status();
105        }
106      }
107
108      mkdirSync(ENGINE_DIR, { recursive: true });
109      const archive = join(ENGINE_DIR, found.asset.name);
110
111      state.status = 'downloading';
112      state.stage = `Downloading ${found.asset.name}`;
113      state.pct = 0;
114      emit();
115
116      const dl = await fetch(found.asset.browser_download_url, { redirect: 'follow', signal: AbortSignal.timeout(600_000) });
117      if (!dl.ok || !dl.body) throw new Error(`Download failed (${dl.status})`);
118
119      const total = Number(dl.headers.get('content-length')) || found.asset.size || 1;
120      const startedAt = Date.now();
121      let received = 0;
122      let last = 0;
123
124      const progress = new ReadableStream({
125        start(controller) {
126          const reader = dl.body.getReader();
127          void (async () => {
128            try {
129              for (;;) {
130                const { done, value } = await reader.read();
131                if (done) break;
132                received += value.byteLength;
133                controller.enqueue(value);
134                const now = Date.now();
135                if (now - last > 250) {
136                  last = now;
137                  const seconds = (now - startedAt) / 1000;
138                  const mbps = received / 1024 ** 2 / Math.max(seconds, 0.001);
139                  state.pct = Math.min(99, (received / total) * 100);
140                  state.mbps = mbps;
141                  state.stage = `Downloading ${found.asset.name}`;
142                  emit();
143                }
144              }
145              controller.close();
146            } catch (err) {
147              controller.error(err);
148            }
149          })();
150        },
151      });
152
153      await pipeline(Readable.fromWeb(progress), createWriteStream(archive));
154
155      state.status = 'extracting';
156      state.pct = 100;
157      state.stage = 'Unpacking the engine';
158      emit();
159
160      await exec(tarBinary(), ['-xf', archive, '-C', ENGINE_DIR], { timeout: 180_000 });
161      rmSync(archive, { force: true });
162
163      const binary = findInstalledBinary();
164      if (!binary) throw new Error('Engine unpacked but no llama-server binary was found');
165
166      state.status = 'done';
167      state.stage = `llama.cpp ${found.version} ready`;
168      state.installedPath = binary;
169      state.error = null;
170      hubRef?.send('log', { level: 'info', message: `Engine installed: ${binary}`, at: nowIso() });
171      emit();
172      return status();
173    } catch (err) {
174      state.status = 'error';
175      state.error = err.message;
176      state.stage = 'Engine install failed';
177      emit();
178      throw err;
179    } finally {
180      running = null;
181    }
182  })();
183
184  return running;
185}
186
187export function findInstalledBinary() {
188  if (!existsSync(ENGINE_DIR)) return null;
189  try {
190    for (const entry of readdirSync(ENGINE_DIR)) {
191      const dir = join(ENGINE_DIR, entry);
192      if (!statSync(dir).isDirectory()) continue;
193      const candidate = join(dir, 'llama-server');
194      if (existsSync(candidate)) return candidate;
195    }
196  } catch {
197    /* ignore */
198  }
199  return null;
200}