okami.mom/strata

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

Niko1221Merge f-no-llama-server: the packaged app loads only through the Strata engine; a llama-server on PATH or in STRATA_LLAMA_SERVER is never started (Load and autostart)f5ef26889

main
12.8 KiB356 linesraw
1/**
2 * Model library.
3 *
4 * With the real engine on, the app downloads models from the Models screen of the native engine, not from this list (see install). Loading
5 * starts a real engine process through the supervisor — no model files, no process, no load.
6 */
7import { existsSync, rmSync, statSync } from 'node:fs';
8import { join } from 'node:path';
9
10import { CONTEXT_TOKENS, VARIANTS, downloadUrl, footprint, localModels, refreshLocalCatalog, variant } from './catalog.mjs';
11
12/**
13 * Design-iteration mode.
14 *
15 * Strata is being iterated on as a product surface, so by default the model
16 * library is simulated: downloads animate, loads stage, nothing is fetched and
17 * no process is spawned. Set STRATA_REAL_ENGINE=1 to use the real path
18 * (Hugging Face download + supervised llama.cpp engine).
19 */
20export const REAL = process.env.STRATA_REAL_ENGINE === '1';
21import { MODELS_DIR, diskFreeGb, get as getStore, update } from './store.mjs';
22import * as supervisor from './supervisor.mjs';
23import { EventHub, nowIso, round, uid } from './util.mjs';
24import { locateModelFile } from './model-files.mjs';
25
26/** In-memory runtime state that never needs persisting. */
27const runtime = new Map(); // id -> { state, progress, error }
28const downloads = new Map(); // id -> AbortController
29
30let hubRef = null;
31
32export function pathFor(v) {
33  if (v.local) return v.local.path;
34  return locateModelFile(MODELS_DIR, v) ?? join(MODELS_DIR, v.id, v.source.file);
35}
36
37export function isOnDisk(id) {
38  const v = variant(id);
39  if (!v) return false;
40  if (v.local) return localModels.ready(v);
41  // In design mode "installed" is a state file entry, not a file on disk.
42  if (!REAL && getStore().installed?.[id]?.simulated) return true;
43  return !!locateModelFile(MODELS_DIR, v);
44}
45
46export function diskUsage(id) {
47  const v = variant(id);
48  if (!v) return 0;
49  if (v.local) return v.local.files.reduce((n, f) => n + f.bytes, 0) / 1024 ** 3;
50  if (!existsSync(pathFor(v))) return REAL ? 0 : v.diskGb; // simulated installs keep the catalog size
51  return statSync(pathFor(v)).size / 1024 ** 3;
52}
53
54export function init(hub) {
55  hubRef = hub;
56  supervisor.init(hub);
57  if (!REAL) {
58    const previous = getStore();
59    const old = Object.keys(previous.installed ?? {}).filter(id => !id.startsWith('local-') && !VARIANTS.some(v=>v.id===id));
60    if (old.length) {
61      const balanced=VARIANTS.find(v=>v.quant==='Q4_K_M').id;
62      update({installed:{...previous.installed,[balanced]:{installedAt:nowIso(),simulated:true}},
63        ...(old.includes(previous.loaded)?{loaded:balanced}:{}),...(old.includes(previous.current)?{current:balanced}: {})});
64    }
65  }
66
67  runtime.clear();
68  for (const v of VARIANTS) {
69    runtime.set(v.id, { state: isOnDisk(v.id) ? 'installed' : 'available' });
70  }
71
72  // Trust the filesystem over the JSON state file.
73  const s = getStore();
74  const installed = { ...(s.installed ?? {}) };
75  for (const id of Object.keys(installed)) if (!VARIANTS.some(v => v.id === id)) delete installed[id];
76  for (const v of VARIANTS) {
77    if (isOnDisk(v.id) && !installed[v.id]) installed[v.id] = { installedAt: nowIso() };
78    if (!isOnDisk(v.id) && installed[v.id]) delete installed[v.id];
79  }
80  const patch = { installed };
81  if (s.loaded && !isOnDisk(s.loaded)) patch.loaded = null;
82  if (s.current && !isOnDisk(s.current)) patch.current = null;
83
84  // Files on disk are the source of truth for "current", so a state file that
85  // disagrees with the filesystem heals itself.
86  const onDisk = VARIANTS.filter((v) => isOnDisk(v.id));
87  if (!REAL && !patch.current && !s.current && onDisk.length) {   // design mode only: in the real mode this made an imported GGUF the remembered model
88    patch.current = (onDisk.find((v) => v.tier === 'starter') ?? onDisk[0]).id;
89  }
90  update(patch);
91}
92
93export function library() {
94  const s = getStore();
95  const usedGb = VARIANTS.reduce((sum, v) => sum + (isOnDisk(v.id) ? diskUsage(v.id) : 0), 0);
96  const engine = supervisor.status();
97  const activeDownloads = [...runtime.values()].filter((r) => r.state === 'downloading').length;
98
99  return {
100    mode: REAL ? 'real' : 'simulated',
101    current: s.current,
102    loaded: REAL ? (engine.running ? engine.modelId : null) : s.loaded,
103    variants: VARIANTS.map((v) => {
104      const entry = runtime.get(v.id) ?? { state: 'available' };
105      const onDisk = isOnDisk(v.id);
106      const loading = REAL ? engine.status === 'starting' && engine.modelId === v.id : entry.state === 'loading';
107      const isLoaded = REAL ? engine.running && engine.modelId === v.id : s.loaded === v.id;
108      const state = loading ? 'loading' : entry.state === 'error' ? 'error' : onDisk ? (isLoaded ? 'loaded' : 'installed') : v.local ? 'error' : entry.state;
109      return {
110        ...v,
111        catalog: {
112          family: v.family.startsWith('Qwen3-Coder') ? 'Qwen Coder' : 'Qwen',
113          version: v.family,
114          purpose: v.family.includes('Coder') ? 'Coding-focused instruction model' : 'General text and conversation',
115          capabilities: v.family.includes('Coder') ? ['Text', 'Code'] : ['Text'],
116          agentApproved: false,
117          balancedRank: v.role === 'best-fit' ? 1 : v.tier === 'starter' ? 10 : 5,
118          review: 'Capability review pending',
119        },
120        diskGb: onDisk ? round(diskUsage(v.id), 2) : v.diskGb,
121        state,
122        progress: entry.progress,
123        error: v.local && !onDisk ? 'The local file is missing or has changed. Use a local model again to reconnect it.' : entry.error,
124        installedAt: v.local ? onDisk ? v.importedAt : undefined : s.installed?.[v.id]?.installedAt,
125        downloadUrl: downloadUrl(v),
126      };
127    }),
128    downloads: { active: activeDownloads, queued: 0, totalGbToday: round(usedGb, 2) },
129    disk: { modelsDir: MODELS_DIR, usedGb: round(usedGb, 2), freeGb: round(diskFreeGb(MODELS_DIR), 0) },
130    engine: { status: engine.status, binary: engine.binary, port: engine.port, modelId: engine.modelId },
131  };
132}
133
134function emit() {
135  hubRef?.send('models', library());
136}
137
138/* ---------------------------------------------------------------- download --- */
139
140/**
141 * With the real engine on, models come from the Models screen of the native engine (its installer pins every file by hash). This
142 * starter list names files by name only and has no hash, so it is never downloaded: the route refuses before any request is made.
143 */
144export const LIST_DOWNLOAD_REFUSED = "The app downloads models from the Models screen of the native engine, not from this list.";
145
146export async function install(id) {
147  const v = variant(id);
148  if (!v) throw new Error(`Unknown model ${id}`);
149  if (v.local) throw new Error('Local models are not downloaded. Choose their GGUF file again to reconnect them.');
150  if (isOnDisk(id)) {
151    const s = getStore();
152    update({ installed: { ...(s.installed ?? {}), [id]: s.installed?.[id] ?? { installedAt: nowIso() } }, current: s.current ?? id });
153    emit();
154    return library();
155  }
156  if (downloads.has(id)) return library();
157
158  if (!REAL) return simulateInstall(v);
159  throw Object.assign(new Error(LIST_DOWNLOAD_REFUSED), { status: 409 });
160}
161
162export function cancel(id) {
163  const download = downloads.get(id);
164  download?.abort();
165  // Real jobs retain their guard until their finally block has settled.
166  if (download) return library();
167  runtime.set(id, { state: 'available' });
168  emit();
169  return library();
170}
171
172export function remove(id) {
173  const v = variant(id);
174  if (!v) return library();
175  const current = library();
176  if (current.loaded === id || current.variants.find(row => row.id === id)?.state === 'loading') throw new Error('Unload this model before deleting its files.');
177  if (v.local) {
178    localModels.remove(id); refreshLocalCatalog(); runtime.delete(id);
179    const s = getStore(), installed = { ...s.installed }; delete installed[id];
180    update({ installed, current: s.current === id ? null : s.current });
181    emit(); return library();
182  }
183  cancel(id);
184  try {
185    const file = pathFor(v);
186    // Existing folders may contain unrelated weights. Delete only this variant's file.
187    if (existsSync(file)) rmSync(file, { force: true });
188  } catch (err) {
189    hubRef?.send('log', { level: 'warn', message: `Could not delete ${v.family} ${v.quant}: ${err.message}`, at: nowIso() });
190    throw new Error(`Could not delete model files: ${err.message}`);
191  }
192  const s = getStore();
193  const installed = { ...(s.installed ?? {}) };
194  delete installed[id];
195  update({
196    installed,
197    loaded: s.loaded === id ? null : s.loaded,
198    current: s.current === id ? null : s.current,
199  });
200  runtime.set(id, { state: 'available' });
201  emit();
202  return library();
203}
204
205/* -------------------------------------------------------------------- load --- */
206
207export async function load(id, hooks = {}) {
208  const v = variant(id);
209  if (!v) throw new Error(`Unknown model ${id}`);
210  if (!isOnDisk(id)) throw new Error(`${v.label} is not downloaded yet`);
211
212  const s = getStore();
213  const port = Number(s.expert?.['server.port'] ?? 8080);
214  const hardware = hooks.hardware;
215  const config = hooks.config;
216
217  if (!REAL) return simulateLoad(v, hooks);
218
219  runtime.set(id, { state: 'loading', progress: { pct: 10, mbps: 0, etaSec: 0, stage: 'Starting engine' } });
220  emit();
221  await hooks.onPhase?.('loading', id);
222
223  try {
224    await supervisor.restart({
225      modelId: id,
226      modelPath: pathFor(v),
227      port,
228      config: { ...config, layerCount: v.layerCount },
229      hardware,
230    });
231  } catch (err) {
232    runtime.set(id, { state: 'error', error: err.message });
233    update({ loaded: null });
234    emit();
235    throw err;
236  }
237
238  update({ loaded: id, current: id });
239  runtime.set(id, { state: 'loaded' });
240  emit();
241  await hooks.onPhase?.('ready', id);
242
243  return library();
244}
245
246export async function unload(hooks = {}) {
247  if (!REAL) {
248    update({ loaded: null });
249    const s = getStore();
250    if (s.current && runtime.has(s.current)) runtime.set(s.current, { state: 'installed' });
251    emit();
252    await hooks.onPhase?.('idle', null);
253    return library();
254  }
255  await supervisor.stop();
256  update({ loaded: null });
257  const s = getStore();
258  if (s.current && runtime.has(s.current)) runtime.set(s.current, { state: 'installed' });
259  emit();
260  await hooks.onPhase?.('idle', null);
261  return library();
262}
263
264/* ------------------------------------------------------- simulated (design) --- */
265
266function simulateInstall(v) {
267  const totalSec = 10; // Preview timing is independent of fictional file sizes.
268  const startedAt = Date.now();
269  runtime.set(v.id, {
270    state: 'downloading',
271    progress: { pct: 0, mbps: 140, etaSec: totalSec, stage: `Fetching ${v.source.file}` },
272  });
273  emit();
274
275  const tick = setInterval(() => {
276    const elapsed = (Date.now() - startedAt) / 1000;
277    const pct = Math.min(100, (elapsed / totalSec) * 100);
278    const entry = runtime.get(v.id);
279    if (!entry || entry.state !== 'downloading') {
280      clearInterval(tick);
281      return;
282    }
283    runtime.set(v.id, {
284      state: 'downloading',
285      progress: {
286        pct,
287        mbps: 120 + Math.sin(elapsed * 2.2) * 28,
288        etaSec: Math.max(0, totalSec - elapsed),
289        stage: pct < 55 ? `Fetching ${v.source.file}` : pct < 88 ? 'Verifying shard hashes' : 'Finalising files',
290      },
291    });
292    emit();
293
294    if (pct >= 100) {
295      clearInterval(tick);
296      const s = getStore();
297      update({
298        installed: { ...(s.installed ?? {}), [v.id]: { installedAt: nowIso(), simulated: true } },
299        current: s.current ?? v.id,
300      });
301      runtime.set(v.id, { state: 'installed' });
302      hubRef?.send('log', { level: 'info', message: `${v.label} ready (simulated)`, at: nowIso() });
303      emit();
304    }
305  }, 280);
306
307  hubRef?.send('log', { level: 'info', message: `Downloading ${v.label} (simulated)`, at: nowIso() });
308  return library();
309}
310
311async function simulateLoad(v, hooks) {
312  runtime.set(v.id, { state: 'loading', progress: { pct: 12, mbps: 0, etaSec: 3, stage: 'Mapping weights into memory' } });
313  emit();
314  await hooks.onPhase?.('loading', v.id);
315
316  for (const pct of [38, 64, 86, 100]) {
317    await new Promise((r) => setTimeout(r, 420));
318    runtime.set(v.id, {
319      state: 'loading',
320      progress: { pct, mbps: 0, etaSec: Math.max(0, (100 - pct) / 30), stage: pct < 70 ? 'Mapping weights into memory' : 'Warming expert cache' },
321    });
322    emit();
323  }
324
325  update({ loaded: v.id, current: v.id });
326  runtime.set(v.id, { state: 'loaded' });
327  emit();
328  await hooks.onPhase?.('ready', v.id);
329  return library();
330}
331
332export function loadedVariant() {
333  const engine = supervisor.status();
334  const id = REAL ? (engine.running ? engine.modelId : null) : getStore().loaded;
335  return id ? variant(id) : null;
336}
337
338export function runtimeState(id) {
339  return runtime.get(id)?.state ?? 'available';
340}
341
342export function directoryBusy() {
343  return downloads.size > 0 || [...runtime.values()].some(r => ['loading', 'downloading'].includes(r.state)) || supervisor.status().status === 'starting';
344}
345
346export function newDownloadId() {
347  return uid('dl');
348}
349
350export { footprint, CONTEXT_TOKENS };
351
352export function localModelAdded() {
353  refreshLocalCatalog();
354  emit();
355  return library();
356}