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
21.3 KiB536 linesraw
1/**
2 * Inference bridge.
3 *
4 * Preference order:
5 *   1. the Strata engine — the C++ engine behind Strata's own Python API worker. This is the
6 *      product's inference path and is tried first. `STRATA_SERVER_URL` names it explicitly;
7 *      otherwise the Strata worker's default loopback address is probed.
8 *   2. the engine Strata supervises itself (llama.cpp), when one is configured
9 *   3. a *different* OpenAI-compatible server already running on localhost, but only when it
10 *      identifies itself as one; a host that merely answers a port is not adopted silently
11 *   4. a clearly-labelled demo engine — **development only**. A packaged or `STRATA_REAL_ENGINE=1`
12 *      run never reaches this branch: it raises a typed error instead, so no simulated answer can
13 *      enter a production success path.
14 */
15import * as supervisor from './supervisor.mjs';
16import { get as getStore } from './store.mjs';
17import { which } from './util.mjs';
18
19/** Where Strata's own API worker listens by default (`serve/server.py`, `--port 8095`). */
20const STRATA_DEFAULT_URL = 'http://127.0.0.1:8095/v1';
21
22const CANDIDATES = [
23  { name: 'llama.cpp', url: 'http://127.0.0.1:8080/v1' },
24  { name: 'Ollama', url: 'http://127.0.0.1:11434/v1' },
25  { name: 'LM Studio', url: 'http://127.0.0.1:1234/v1' },
26];
27
28let backend = null;
29let checkedAt = 0;
30
31/**
32 * True when this process must not simulate inference.
33 *
34 * Packaged builds are always real. `STRATA_REAL_ENGINE` can force it either way for development,
35 * but it can never turn a packaged build back into demo mode — that is the guarantee acceptance
36 * checklist row U12 asks for ("no success path using demo responses/metrics").
37 */
38export function requiresRealEngine() {
39  if (process.env.STRATA_FORCE_DEMO === '1' && process.env.STRATA_PACKAGED !== '1') return false;
40  if (process.env.STRATA_REAL_ENGINE === '1') return true;
41  return process.env.STRATA_PACKAGED === '1';
42}
43
44/** Where the Strata API worker is, if it was named explicitly. */
45function strataUrl() {
46  const raw = process.env.STRATA_SERVER_URL?.trim();
47  if (!raw) return STRATA_DEFAULT_URL;
48  return raw.replace(/\/+$/, '').endsWith('/v1') ? raw.replace(/\/+$/, '') : `${raw.replace(/\/+$/, '')}/v1`;
49}
50
51/**
52 * Probe a loopback endpoint and confirm it really is a Strata worker.
53 *
54 * A bare OpenAI-compatible listener is not enough: Strata's worker answers `/v1/status` with its
55 * own shape (it carries `service: "strata"` and the reported context). Adopting an unrelated
56 * server because it happens to hold the port is exactly the silent substitution the architecture
57 * forbids, so the identity check is required.
58 */
59async function probeStrata(baseUrl) {
60  try {
61    const res = await fetch(`${baseUrl.replace(/\/v1$/, '')}/v1/status`, { signal: AbortSignal.timeout(900) });
62    if (!res.ok) return null;
63    const status = await res.json().catch(() => null);
64    if (!status || typeof status !== 'object') return null;
65    if (status.service !== 'strata') return null;
66    const models = await fetch(`${baseUrl}/models`, { signal: AbortSignal.timeout(900) })
67      .then((r) => (r.ok ? r.json() : null))
68      .catch(() => null);
69    return {
70      kind: 'strata',
71      name: 'Strata engine',
72      baseUrl,
73      models: (models?.data ?? []).map((m) => m.id).filter(Boolean),
74      modelId: status.model ?? null,
75      context: status.context?.native ?? null,
76      loaded: status.loaded === true,
77      dialects: status.dialects ?? [],
78    };
79  } catch {
80    return null;
81  }
82}
83
84export async function detectBackend({ force = false } = {}) {
85  // 1. Strata's own engine, always first: it is the product's inference path.
86  const strata = await probeStrata(strataUrl());
87  if (strata) {
88    backend = strata;
89    checkedAt = Date.now();
90    return backend;
91  }
92
93  if (requiresRealEngine() && !supervisor.isRunning()) {
94    // No simulation is permitted here. Try the supervisor and the identified candidates below,
95    // and if none is a real engine the caller gets a typed error rather than invented tokens.
96  }
97
98  if (supervisor.isRunning()) {
99    const status = supervisor.status();
100    backend = {
101      kind: 'engine',
102      name: 'Strata engine · llama.cpp',
103      baseUrl: `http://127.0.0.1:${status.port}/v1`,
104      models: status.modelId ? [status.modelId] : [],
105    };
106    checkedAt = Date.now();
107    return backend;
108  }
109
110  if (!force && backend && backend.kind !== 'engine' && Date.now() - checkedAt < 20_000) return backend;
111
112  for (const c of CANDIDATES) {
113    try {
114      const res = await fetch(`${c.url}/models`, { signal: AbortSignal.timeout(700) });
115      if (res.ok) {
116        const data = await res.json().catch(() => ({}));
117        backend = {
118          kind: 'openai-compatible',
119          name: c.name,
120          baseUrl: c.url,
121          models: (data?.data ?? []).map((m) => m.id),
122        };
123        checkedAt = Date.now();
124        return backend;
125      }
126    } catch {
127      /* try the next candidate */
128    }
129  }
130
131  if (requiresRealEngine()) {
132    backend = {
133      kind: 'unavailable',
134      name: 'No Strata engine',
135      baseUrl: null,
136      models: [],
137      error:
138        `No Strata engine answered at ${strataUrl()} and no supervised engine is running. ` +
139        'Start Strata (or load a model) and retry. Simulated output is disabled in this build.',
140    };
141    checkedAt = Date.now();
142    return backend;
143  }
144
145  backend = {
146    kind: 'demo',
147    name: 'Strata demo engine',
148    baseUrl: null,
149    models: [],
150    binary: null,
151    // Every demo frame is labelled for the UI; nothing here may be recorded as a real result.
152    simulated: true,
153  };
154  checkedAt = Date.now();
155  return backend;
156}
157
158export function currentBackend() {
159  if (supervisor.isRunning()) {
160    const status = supervisor.status();
161    return {
162      kind: 'engine',
163      name: 'Strata engine · llama.cpp',
164      baseUrl: `http://127.0.0.1:${status.port}/v1`,
165      models: status.modelId ? [status.modelId] : [],
166    };
167  }
168  return backend;
169}
170
171/* ------------------------------------------------------------------- utils --- */
172
173const CHUNK_MS = 26;
174
175function tokenize(text) {
176  const out = [];
177  const words = text.split(/(\s+)/);
178  let buffer = '';
179  for (const w of words) {
180    buffer += w;
181    if (buffer.length >= 3 || /\n/.test(w)) {
182      out.push(buffer);
183      buffer = '';
184    }
185  }
186  if (buffer) out.push(buffer);
187  return out;
188}
189
190export function estimateTokens(text) {
191  return Math.max(1, Math.round(text.length / 3.8));
192}
193
194const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
195
196/* -------------------------------------------------------------- the stream --- */
197
198export async function streamChat({ message, history = [], systemPrompt = '', modelLabel, onFrame, signal, engine, candidates = [] }) {
199  const be = await detectBackend();
200
201  if (be.kind === 'strata') {
202    return proxyCompletion({
203      baseUrl: be.baseUrl,
204      message,
205      history,
206      systemPrompt,
207      onFrame,
208      signal,
209      supervised: false,
210      engine,
211      modelId: be.modelId || 'strata',
212    });
213  }
214
215  if (be.kind === 'engine' || be.kind === 'openai-compatible') {
216    return proxyCompletion({
217      baseUrl: be.baseUrl,
218      message,
219      history,
220      systemPrompt,
221      onFrame,
222      signal,
223      supervised: be.kind === 'engine',
224      engine,
225    });
226  }
227
228  if (be.kind === 'unavailable') {
229    // Fail loudly and specifically. This is a real, non-simulated error path.
230    throw new Error(be.error ?? 'No Strata engine is available.');
231  }
232
233  return demoCompletion({ message, modelLabel, onFrame, signal, engine, candidates });
234}
235
236/* --------------------------------------------------------- real engine path --- */
237
238export async function proxyCompletion({ baseUrl, message, history = [], systemPrompt = '', onFrame, signal, supervised = false, engine,modelId='local',authorization,images=[],extra={} }) {
239  const started = Date.now();
240  engine?.beginReading(0, engine.variantId);
241  const messages = [
242    ...(systemPrompt ? [{ role: 'system', content: systemPrompt }] : []),
243    ...history.filter((m) => ['system', 'user', 'assistant'].includes(m.role)).map((m) => ({ role: m.role, content: m.content })),
244    { role: 'user', content:images.length?[{type:'text',text:message},...images.map(i=>({type:'image_url',image_url:{url:i.url}}))]:message },
245  ];
246
247  const defaults = getStore().expert ?? {};
248  const sampling = { temperature: defaults['sample.temp'] ?? 0.6, top_p: defaults['sample.topP'] ?? 0.95, top_k: defaults['sample.topK'] ?? 40, repeat_penalty: defaults['sample.repeat'] ?? 1.05, seed: defaults['sample.seed'] ?? -1, experimental_speed_projection: defaults['sample.speedProjection'] ?? true, ...(Number(defaults['sample.maxTokens']) > 0 ? {max_tokens: Number(defaults['sample.maxTokens'])} : {}) };
249  const res = await fetch(`${baseUrl}/chat/completions`, {
250    method: 'POST',
251    headers: { 'content-type': 'application/json', ...(authorization?{authorization:`Bearer ${authorization}`} :supervised && getStore().serving?.apiKey ? { authorization: `Bearer ${getStore().serving.apiKey}` } : {}) },
252    signal,
253    body: JSON.stringify({
254      model: modelId,
255      stream: true,
256      stream_options: { include_usage: true },
257      ...sampling,
258      ...extra,
259      messages,
260    }),
261  });
262
263  if (!res.ok || !res.body) {
264    const detail = await res.text().catch(() => '');
265    throw new Error(`Engine responded ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`);
266  }
267
268  onFrame({ type: 'start', demo: false });
269
270  const reader = res.body.getReader();
271  const decoder = new TextDecoder();
272  let buffer = '';
273  let out = null;
274  let promptTokens = null;
275  let cachedTokens = null;
276  let firstTokenAt = null;
277  let streaming = true;
278  let writing = false;
279  let timings=null,finishReason=null;
280  /* The speed shown while it streams is the decode speed of everything generated, reasoning included, from the first token: tokens
281     (one per streamed chunk, or characters / 4 when the server batches) over the time since the first token, never the visible
282     answer over the whole wall time. The engine's own numbers replace it when the answer is done. */
283  let chunks=0,chars=0,lastStats=0;
284  const liveStats=()=>{if(supervised||firstTokenAt===null)return;const now=Date.now();if(now-lastStats<400)return;const seconds=(now-firstTokenAt)/1000;if(seconds<.5)return;lastStats=now;
285   const tokens=chars/Math.max(1,chunks)<8?chunks:Math.ceil(chars/4);onFrame({type:'stats',tokensOut:tokens,tps:Number((tokens/seconds).toFixed(1)),source:'stream'});};
286
287  const metricsTicker = supervised
288    ? setInterval(() => {
289        void supervisor.pollMetrics().then((m) => {
290          if (streaming && m.source === 'engine' && m.outputTps > 0) {
291            onFrame({ type: 'stats', tokensOut: out, tps: m.outputTps, promptTps: m.promptTps, source: 'engine' });
292          }
293        }).catch(() => {});
294      }, 900)
295    : null;
296
297  try {
298    for (;;) {
299      const { done, value } = await reader.read();
300      buffer += done ? decoder.decode() + '\n' : decoder.decode(value, { stream: true });
301      const lines = buffer.split('\n');
302      buffer = lines.pop() ?? '';
303
304      for (const line of lines) {
305        const trimmed = line.trim();
306        if (!trimmed.startsWith('data:')) continue;
307        const payload = trimmed.slice(5).trim();
308        if (payload === '[DONE]') continue;
309        let parsed;
310        try {
311          parsed = JSON.parse(payload);
312        } catch {
313          continue;
314        }
315        if (parsed.error) throw new Error(parsed.error.message ?? 'Inference failed.');
316        if(parsed.strata_mcp)onFrame({type:'native-tool',event:parsed.strata_mcp});
317        if(parsed.timings)timings=parsed.timings;
318        if(parsed.choices?.[0]?.finish_reason)finishReason=parsed.choices[0].finish_reason;
319
320        if (parsed.usage) {
321          if (Number.isFinite(parsed.usage.prompt_tokens)) promptTokens = parsed.usage.prompt_tokens;
322          if (Number.isFinite(parsed.usage.completion_tokens)) out = parsed.usage.completion_tokens;
323          if (Number.isFinite(parsed.usage.prompt_tokens_details?.cached_tokens)) cachedTokens = parsed.usage.prompt_tokens_details.cached_tokens;
324        }
325
326        const delta = parsed.choices?.[0]?.delta;
327        if (!delta) continue;
328
329        // Qwen3-style thinking models stream reasoning separately.
330        if (delta.reasoning_content) {
331          if (firstTokenAt === null) engine?.beginThinking();
332          if (firstTokenAt === null) firstTokenAt = Date.now();
333          chunks++; chars+=delta.reasoning_content.length;
334          onFrame({ type: 'reasoning', text: delta.reasoning_content });
335          liveStats();
336        }
337        if (delta.content) {
338          if (!writing) { engine?.beginGenerating(); writing = true; }
339          if (firstTokenAt === null) firstTokenAt = Date.now();
340          chunks++; chars+=delta.content.length;
341          onFrame({ type: 'delta', text: delta.content });
342          liveStats();
343        }
344      }
345      if (done) break;
346    }
347  } finally {
348    streaming = false;
349    if (metricsTicker) clearInterval(metricsTicker);
350    reader.releaseLock();
351  }
352
353  signal?.throwIfAborted();
354  const durationMs = Date.now() - started;
355  const decodeMs = firstTokenAt ? Date.now() - firstTokenAt : durationMs;
356  const tps = Number.isFinite(timings?.predicted_per_second)?timings.predicted_per_second:out !== null && decodeMs > 0 ? Number((out / (decodeMs / 1000)).toFixed(1)) : null;
357  const usageSource = promptTokens !== null && out !== null ? 'reported' : 'unavailable';
358
359  const result = { tokensIn: promptTokens, tokensOut: out, cachedTokens, tps, promptTps:Number.isFinite(timings?.prompt_per_second)?timings.prompt_per_second:null,hitRate:Number.isFinite(timings?.hit_rate)?timings.hit_rate:null,pcieShare:Number.isFinite(timings?.pcie_share)?timings.pcie_share:null,finishReason,durationMs, usageSource, ttftMs: firstTokenAt === null ? null : firstTokenAt - started };
360  onFrame({ type: 'done', ...result, demo: false });
361  return result;
362}
363
364/* --------------------------------------------------------------- demo path --- */
365
366const wantsPreviewExamples = message => /preview examples|website.*(?:markdown|pdf)|(?:markdown|pdf).*website/i.test(message);
367const previewExamples = [
368  { id:'sample-website', kind:'website', title:'Fieldnotes — website', url:'/examples/fieldnotes.html', demo:true },
369  { id:'sample-markdown', kind:'markdown', title:'project-brief.md', url:'/examples/project-brief.md', demo:true },
370  { id:'sample-pdf', kind:'pdf', title:'project-brief.pdf', url:'/examples/project-brief.pdf', demo:true },
371];
372function demoAnswer(prompt, variantLabel) {
373  const p = prompt.toLowerCase();
374  const lead = `Running on ${variantLabel}. `;
375  if (wantsPreviewExamples(prompt)) return 'Here are three example outputs for a small project called Fieldnotes. Open the website, Markdown brief or PDF below to review it beside our conversation. These are built-in preview examples.';
376
377  if (/readme|repo|project|summar/.test(p)) {
378    return `${lead}Here is the short version of what that file is telling you.
379
380**What it is** — a local inference app: one model, one engine, tuned to the machine it runs on.
381
382**The important parts**
383- The engine host detects your hardware before anything downloads.
384- Models are suggested by memory class. Fit and memory figures are estimates.
385- Prompt reading and generation appear separately. This demo uses simulated values.
386
387**What I would do next**
3881. Check the \`Models\` tab and confirm the recommended variant matches your RAM class.
3892. Open \`Monitor\` while a long prompt runs and watch prompt throughput — that is usually the bottleneck, not generation.
3903. If replies feel slow, lower the context length in \`Engine tuning\` before changing sampling values.
391
392Ask me about any specific section and I will go deeper.`;
393  }
394
395  if (/kv cache|cache|context/.test(p)) {
396    return `${lead}Think of the KV cache as the model's short-term memory for the conversation.
397
398Every token you send gets turned into a key and a value vector, and those vectors are kept so the model does not have to re-read the whole prompt on every new token. That is why the first token is slow and the rest are fast.
399
400**Why it matters on your machine**
401- Cache size scales with **context length × layers × head width**.
402- At INT8 the cache is roughly half the size of FP16, at a small quality cost.
403- A 32K context can easily cost more memory than the model weights on a small machine.
404
405If memory is tight, cut context length first — it is the single biggest lever.`;
406  }
407
408  return `${lead}Short answer first, then the reasoning.
409
410**Short answer** — yes, and the useful part is *where* the cost lands. On a single local model the trade is almost always memory against latency.
411
412**What I would check on this machine**
4131. Monitor separates prompt reading from answer generation.
4142. Each reading identifies its source, including simulated or unavailable values.
4153. Context describes how much text the model can consider; it is not a quality score.
416
417This is a demo response. Real answers require a connected inference engine.`;
418}
419
420/**
421 * Picks a file that is actually in the workspace.
422 *
423 * The demo used to propose reading `README.md` on every machine, including ones
424 * with no README at the root. A proposal naming a file that does not exist is a
425 * bad demonstration and, worse, an approval that grants access to nothing.
426 *
427 * @param candidates relative paths the host found in the workspace.
428 */
429function pickReadable(candidates) {
430  if (!candidates.length) return null;
431  return (
432    candidates.find((c) => /^readme\.md$/i.test(c)) ??
433    candidates.find((c) => /readme/i.test(c)) ??
434    candidates.find((c) => /\.md$/i.test(c)) ??
435    candidates[0]
436  );
437}
438
439/** Which tools the demo engine would reach for, given the prompt. */
440function proposeTools(message, candidates = []) {
441  const p = message.toLowerCase();
442  const tools = [];
443  if (/readme|read the|open |file|repo|workspace|docs?\b/.test(p)) {
444    const path = pickReadable(candidates);
445    if (path) {
446      tools.push({
447        id: 'read_file',
448        name: 'Read file',
449        args: { path },
450        preview: path,
451        effect: 'Reads a file inside the workspace. Nothing leaves this computer.',
452        scope: 'read',
453      });
454    }
455  }
456  if (/run|test|build|lint|install|command/.test(p)) {
457    tools.push({
458      id: 'run_command',
459      name: 'Run command',
460      args: { command: 'npm test -- --runInBand' },
461      preview: 'npm test -- --runInBand',
462      effect: 'Runs a shell command in the workspace and returns the output.',
463      scope: 'write',
464    });
465  }
466  if (/edit|change|fix|refactor|write|update the/.test(p)) {
467    tools.push({
468      id: 'write_file',
469      name: 'Edit file',
470      args: { path: 'src/app/App.tsx', change: 'apply the requested change' },
471      preview: 'src/app/App.tsx · 1 hunk',
472      effect: 'Writes to a file inside the workspace. A diff is shown first.',
473      scope: 'write',
474    });
475  }
476  return tools.slice(0, 2);
477}
478
479async function demoCompletion({ message, modelLabel, onFrame, signal, engine, candidates = [] }) {
480  const variety = modelLabel ?? 'the loaded model';
481  const promptTokens = estimateTokens(message);
482
483  onFrame({ type: 'start', demo: true, backend: 'demo', promptTokens });
484
485  // Propose tool calls before answering — this is how a local agent behaves,
486  // and it is the flow the approval card exists for.
487  for (const tool of wantsPreviewExamples(message) ? [] : proposeTools(message, candidates)) {
488    onFrame({ type: 'tool', tool });
489  }
490  await engine.beginReading(promptTokens, engine.variantId);
491
492  const step = Math.max(1, Math.round(promptTokens / 14));
493  for (let done = 0; done <= promptTokens; done += step) {
494    signal?.throwIfAborted();
495    engine.progressReading(Math.min(done, promptTokens));
496    await sleep(CHUNK_MS * 2);
497  }
498  engine.progressReading(promptTokens);
499  await sleep(220);
500  signal?.throwIfAborted();
501
502  engine.beginGenerating();
503  const chunks = tokenize(demoAnswer(message, variety));
504  const started = Date.now();
505  let emitted = 0;
506
507  for (const chunk of chunks) {
508    signal?.throwIfAborted();
509    onFrame({ type: 'delta', text: chunk });
510    emitted += estimateTokens(chunk);
511    if (emitted % 3 === 0) {
512      const seconds = Math.max(0.001, (Date.now() - started) / 1000);
513      onFrame({ type: 'stats', tokensOut: emitted, tps: Number((emitted / seconds).toFixed(1)) });
514    }
515    await sleep(CHUNK_MS);
516  }
517
518  const durationMs = Date.now() - started;
519  const tps = Number((emitted / Math.max(0.001, durationMs / 1000)).toFixed(1));
520  signal?.throwIfAborted();
521  if (wantsPreviewExamples(message)) onFrame({ type: 'artifacts', artifacts: previewExamples });
522  onFrame({ type: 'done', tokensIn: promptTokens, tokensOut: emitted, tps, durationMs, demo: true, usageSource: 'demo' });
523  return { tokensIn: promptTokens, tokensOut: emitted, durationMs, tps, usageSource: 'demo' };
524}
525
526/**
527 * The start-up line "inference · ...". The worker that serves a model is only running once a model is loaded, so on a restart nothing answers
528 * at the worker's address even though the engine is installed and usable; the line says that instead of "No Strata engine".
529 * `engine` is Control's answer (null when there is no Control, as in a source checkout).
530 */
531export function inferenceLine({ backend, engine = null, settled = true }) {
532  if (!settled) return 'unpacking the bundled engine… (about a minute the first time)';
533  if (backend?.kind !== 'unavailable' || !engine) return backend?.name ?? 'No Strata engine';
534  if (engine.usable) return `Strata engine${engine.engine?.version ? ' ' + engine.engine.version : ''} is installed; no model is loaded yet`;
535  return engine.notice ? `No Strata engine for this PC. ${engine.notice}` : backend.name;
536}