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
9.2 KiB268 linesraw
1/**
2 * Engine supervisor (what is left of it): the engine status the Monitor and the engine page read, its log ring buffer, the parser of the
3 * engine's Prometheus metrics, and the translation of the tuning configuration into flags for the command preview.
4 *
5 * It starts nothing: the llama.cpp `llama-server` it used to find and start is gone (see start() below). Models run on the Strata engine.
6 */
7import { CONTEXT_TOKENS } from './catalog.mjs';
8
9const LOG_LIMIT = 400;
10
11const state = {
12  status: 'stopped', // stopped | starting | running | stopping | error
13  binary: null,
14  binarySource: null,
15  pid: null,
16  port: 8080,
17  modelId: null,
18  modelPath: null,
19  args: [],
20  command: '',
21  startedAt: null,
22  error: null,
23  logs: [],
24  metrics: {
25    source: 'none',
26    promptTokens: 0,
27    predictedTokens: 0,
28    promptTps: 0,
29    outputTps: 0,
30    kvUsage: 0,
31    kvTokens: 0,
32    requestsProcessing: 0,
33    requestsDeferred: 0,
34    sampledAt: null,
35  },
36};
37
38let child = null;
39let pollTimer = null;
40let hubRef = null;
41let mcpAt=0,mcpStatus=null,mcpPending=false;
42
43export function init(hub) {
44  hubRef = hub;
45}
46
47/* --------------------------------------------------------------- arguments --- */
48
49const KV_TYPES = { INT8: 'q8_0', FP16: 'f16', Q8_0: 'q8_0', Q4_0: 'q4_0' };
50
51/**
52 * Turn the tuning configuration into a real llama-server command line.
53 * Exported so the UI can show exactly what will run.
54 */
55export function buildArgs({ modelPath, config, hardware, port = state.port }) {
56  const beginner = config.beginner ?? {};
57  const params = new Map((config.expert ?? []).map((p) => [p.id, p.value]));
58  const num = (id, fallback) => {
59    const v = Number(params.get(id));
60    return Number.isFinite(v) ? v : fallback;
61  };
62  const ctxLabel = beginner.contextLength === 'recommended' ? '128K' : String(beginner.contextLength).toUpperCase();
63  const ctx = CONTEXT_TOKENS[ctxLabel.toLowerCase()] ?? 32768;
64
65  const args = [
66    '-m', modelPath,
67    '--host', '127.0.0.1',
68    '--port', String(port),
69    '-c', String(ctx),
70    '--metrics',
71    '--slots',
72    '--jinja',
73    '--no-webui',
74  ];
75
76  // GPU offload — on unified memory "all layers" is the right default.
77  const split = String(params.get('gpu.layers') ?? 'Automatic');
78  const ngl = split === 'CPU only' ? 0 : split === 'Quarter' ? Math.max(1, Math.round(Number(config.layerCount ?? 48) / 4)) : split === 'Half' ? Math.max(1, Math.round(Number(config.layerCount ?? 48) / 2)) : 999;
79  args.push('-ngl', String(ngl));
80
81  const threads = num('perf.threads', Math.max(4, (hardware?.cpu?.cores ?? 8) - 2));
82  args.push('-t', String(threads));
83
84  const kv = KV_TYPES[String(params.get('ctx.kvMode') ?? 'INT8')] ?? 'q8_0';
85  args.push('-ctk', kv, '-ctv', kv);
86
87  const batch = num('perf.batch', 2048);
88  args.push('-b', String(batch), '-ub', String(Math.max(128, Math.min(512, Math.round(batch / 4)))));
89
90  if (params.get('perf.flashAttn') === false) args.push('-fa', 'off');
91  else args.push('-fa', 'on');
92
93  if (params.get('mem.mmap') === false) args.push('--no-mmap');
94  if (params.get('mem.lock') === true) args.push('--mlock');
95
96  const parallel = Math.max(1, num('server.parallel', 1));
97  args.push('-np', String(parallel));
98
99  // Sampling defaults applied to every request by the server.
100  args.push(
101    '--temp', String(params.get('sample.temp') ?? 0.6),
102    '--top-p', String(params.get('sample.topP') ?? 0.95),
103    '--top-k', String(params.get('sample.topK') ?? 40),
104    '--repeat-penalty', String(params.get('sample.repeat') ?? 1.05),
105  );
106  const seed = Number(params.get('sample.seed') ?? -1);
107  if (seed >= 0) args.push('--seed', String(seed));
108
109  if (config.serving?.apiKey) args.push('--api-key', config.serving.apiKey);
110
111  return args;
112}
113
114export function describeCommand() {
115  return [state.binary, ...state.args].filter(Boolean).join(' ');
116}
117
118/* ---------------------------------------------------------------- lifecycle --- */
119
120function log(stream, line) {
121  const entry = { at: new Date().toISOString(), stream, line };
122  state.logs.push(entry);
123  if (state.logs.length > LOG_LIMIT) state.logs.shift();
124  hubRef?.send('engine-log', entry);
125}
126
127export function logs(limit = 200) {
128  return state.logs.slice(-limit);
129}
130
131/**
132 * The app host starts no inference process of its own: models run on the Strata engine (native control). This used to look for a llama.cpp
133 * `llama-server` (STRATA_LLAMA_SERVER, <models>/../engine, /opt/homebrew/bin, /usr/local/bin, PATH) and start it; a packaged app with
134 * STRATA_REAL_ENGINE=1 did so for an imported GGUF, also at start-up (0.2.14). start() now refuses, and nothing in this file spawns a process.
135 */
136export async function start() {
137  state.status = 'error';
138  state.error = 'Strata runs models on its own engine only.';
139  hubRef?.send('engine-status', status());
140  throw new Error(state.error);
141}
142
143export async function stop() {
144  if (!child) {
145    state.status = 'stopped';
146    state.pid = null;
147    stopPolling();
148    hubRef?.send('engine-status', status());
149    return status();
150  }
151  state.status = 'stopping';
152  hubRef?.send('engine-status', status());
153  const proc = child;
154  proc.kill('SIGTERM');
155  const exited = await Promise.race([
156    new Promise((r) => proc.once('exit', () => r(true))),
157    new Promise((r) => setTimeout(() => r(false), 4000)),
158  ]);
159  if (!exited) {
160    log('supervisor', 'engine ignored SIGTERM — killing');
161    proc.kill('SIGKILL');
162  }
163  child = null;
164  state.status = 'stopped';
165  state.pid = null;
166  state.startedAt = null;
167  stopPolling();
168  hubRef?.send('engine-status', status());
169  return status();
170}
171
172export async function restart(opts) {
173  await stop();
174  await new Promise((r) => setTimeout(r, 400));
175  return start(opts);
176}
177
178/* ------------------------------------------------------------------ metrics --- */
179
180function startPolling() {
181  stopPolling();
182  pollTimer = setInterval(() => void pollMetrics(), 1000);
183  pollTimer.unref?.();
184  void pollMetrics();
185}
186
187function stopPolling() {
188  if (pollTimer) clearInterval(pollTimer);
189  pollTimer = null;
190}
191
192function parsePrometheus(text) {
193  const out = {};
194  for (const line of text.split('\n')) {
195    if (!line || line.startsWith('#')) continue;
196    const match = /^([a-zA-Z0-9_:]+)(\{[^}]*\})?\s+([0-9.eE+-]+)$/.exec(line.trim());
197    if (!match) continue;
198    out[match[1]] = Number(match[3]);
199  }
200  return out;
201}
202
203/** Original Strata serves JSON; llama.cpp serves Prometheus. Preserve the original dashboard facts. */
204export function parseEngineMetrics(text) {
205  if(text.trim().startsWith('{')) {
206    const dashboard=JSON.parse(text);
207    if(!dashboard.engine||!dashboard.live)throw new Error('Unrecognized engine metrics');
208    const live=dashboard.live;
209    return {source:'engine',dashboard,promptTokens:live.prompt_tokens??0,predictedTokens:live.generated??0,promptTps:live.prefill_tok_s_mean??0,outputTps:live.tok_s??0,kvUsage:0,kvTokens:0,requestsProcessing:live.running??(['reading','generating'].includes(live.state)?1:0),requestsDeferred:live.queued??0};
210  }
211  const m=parsePrometheus(text);
212  if(!Object.keys(m).some(key=>/prompt_tokens|tokens_predicted|predicted_tokens|kv_cache|requests_processing/.test(key)))throw new Error('Unrecognized engine metrics');
213  const p=name=>m[`llamacpp:${name}`]??m[name]??0;
214  return {source:'engine',promptTokens:p('prompt_tokens_total'),predictedTokens:p('tokens_predicted_total'),promptTps:p('prompt_tokens_seconds'),outputTps:p('predicted_tokens_seconds'),kvUsage:p('kv_cache_usage_ratio'),kvTokens:p('kv_cache_tokens'),requestsProcessing:p('requests_processing'),requestsDeferred:p('requests_deferred')};
215}
216
217export async function pollMetrics() {
218  if (state.status !== 'running') return state.metrics;
219  try {
220    const res = await fetch(`http://127.0.0.1:${state.port}/metrics${state.metrics.dashboard?'?requests=all':''}`, {
221      signal: AbortSignal.timeout(1500),
222      headers: state.apiKey ? { authorization: `Bearer ${state.apiKey}` } : undefined,
223    });
224    if (!res.ok) throw new Error(String(res.status));
225    state.metrics = { ...parseEngineMetrics(await res.text()), sampledAt: new Date().toISOString() };
226    if(state.metrics.dashboard) {
227      state.metrics.dashboard.mcp=mcpStatus;
228      if(!mcpPending&&Date.now()-mcpAt>10000) {
229        mcpPending=true;mcpAt=Date.now();
230        void fetch(`http://127.0.0.1:${state.port}/mcp`,{signal:AbortSignal.timeout(1500),headers:state.apiKey?{authorization:`Bearer ${state.apiKey}`}:undefined})
231          .then(async response=>{mcpStatus=response.ok?await response.json():null;})
232          .catch(()=>{mcpStatus=null;}).finally(()=>{mcpPending=false;});
233      }
234    }
235  } catch {
236    state.metrics = { ...state.metrics, source: 'unavailable', sampledAt: new Date().toISOString() };
237  }
238  return state.metrics;
239}
240
241/* ------------------------------------------------------------------- status --- */
242
243export function status() {
244  const binary = state.binary ? { path: state.binary, source: state.binarySource } : null;
245  return {
246    status: state.status,
247    running: state.status === 'running',
248    binary,
249    pid: state.pid,
250    port: state.port,
251    modelId: state.modelId,
252    modelPath: state.modelPath,
253    startedAt: state.startedAt,
254    error: state.error,
255    args: state.args,
256    command: state.command,
257    metrics: state.metrics,
258    logCount: state.logs.length,
259  };
260}
261
262export function currentPort() {
263  return state.port;
264}
265
266export function isRunning() {
267  return state.status === 'running';
268}