okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f5ef26889
main
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 () { 39if ( process . env . STRATA_FORCE_DEMO === '1' && process . env . STRATA_PACKAGED !== '1' ) return false ; 40if ( process . env . STRATA_REAL_ENGINE === '1' ) return true ; 41return process . env . STRATA_PACKAGED === '1' ; 42} 43 44/** Where the Strata API worker is, if it was named explicitly. */ 45function strataUrl () { 46const raw = process . env . STRATA_SERVER_URL ?. trim (); 47if ( ! raw ) return STRATA_DEFAULT_URL ; 48return 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 ) { 60try { 61const res = await fetch ( ` ${ baseUrl . replace ( / \/v1$ / , '' )} /v1/status` , { signal :AbortSignal . timeout ( 900 ) }); 62if ( ! res . ok ) return null ; 63const status = await res . json (). catch (() => null ); 64if ( ! status || typeof status !== 'object' ) return null ; 65if ( status . service !== 'strata' ) return null ; 66const models = await fetch ( ` ${ baseUrl } /models` , { signal :AbortSignal . timeout ( 900 ) }) 67. then (( r ) => ( r . ok ?r . json () :null )) 68. catch (() => null ); 69return { 70kind :'strata' , 71name :'Strata engine' , 72 baseUrl, 73models :( models ?. data ?? []). map (( m ) => m . id ). filter ( Boolean ), 74modelId :status . model ?? null , 75context :status . context ?. native ?? null , 76loaded :status . loaded === true , 77dialects :status . dialects ?? [], 78}; 79} catch { 80return 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. 86const strata = await probeStrata ( strataUrl ()); 87if ( strata ) { 88backend = strata ; 89checkedAt = Date . now (); 90return backend ; 91} 92 93if ( 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 98if ( supervisor . isRunning ()) { 99const status = supervisor . status (); 100backend = { 101kind :'engine' , 102name :'Strata engine · llama.cpp' , 103baseUrl :`http://127.0.0.1: ${ status . port } /v1` , 104models :status . modelId ?[ status . modelId ] :[], 105}; 106checkedAt = Date . now (); 107return backend ; 108} 109 110if ( ! force && backend && backend . kind !== 'engine' && Date . now () - checkedAt < 20_000 ) return backend ; 111 112for ( const c of CANDIDATES ) { 113try { 114const res = await fetch ( ` ${ c . url } /models` , { signal :AbortSignal . timeout ( 700 ) }); 115if ( res . ok ) { 116const data = await res . json (). catch (() => ({})); 117backend = { 118kind :'openai-compatible' , 119name :c . name , 120baseUrl :c . url , 121models :( data ?. data ?? []). map (( m ) => m . id ), 122}; 123checkedAt = Date . now (); 124return backend ; 125} 126} catch { 127/* try the next candidate */ 128} 129} 130 131if ( requiresRealEngine ()) { 132backend = { 133kind :'unavailable' , 134name :'No Strata engine' , 135baseUrl :null , 136models :[], 137error : 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}; 141checkedAt = Date . now (); 142return backend ; 143} 144 145backend = { 146kind :'demo' , 147name :'Strata demo engine' , 148baseUrl :null , 149models :[], 150binary :null , 151// Every demo frame is labelled for the UI; nothing here may be recorded as a real result. 152simulated :true , 153}; 154checkedAt = Date . now (); 155return backend ; 156} 157 158export function currentBackend () { 159if ( supervisor . isRunning ()) { 160const status = supervisor . status (); 161return { 162kind :'engine' , 163name :'Strata engine · llama.cpp' , 164baseUrl :`http://127.0.0.1: ${ status . port } /v1` , 165models :status . modelId ?[ status . modelId ] :[], 166}; 167} 168return backend ; 169} 170 171/* ------------------------------------------------------------------- utils --- */ 172 173const CHUNK_MS = 26 ; 174 175function tokenize ( text ) { 176const out = []; 177const words = text . split ( / ( \s + ) / ); 178let buffer = '' ; 179for ( const w of words ) { 180buffer += w ; 181if ( buffer . length >= 3 || / \n / . test ( w )) { 182out . push ( buffer ); 183buffer = '' ; 184} 185} 186if ( buffer ) out . push ( buffer ); 187return out ; 188} 189 190export function estimateTokens ( text ) { 191return 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= [] }) { 199const be = await detectBackend (); 200 201if ( be . kind === 'strata' ) { 202return proxyCompletion ({ 203baseUrl :be . baseUrl , 204 message, 205 history, 206 systemPrompt, 207 onFrame, 208 signal, 209supervised :false , 210 engine, 211modelId :be . modelId || 'strata' , 212}); 213} 214 215if ( be . kind === 'engine' || be . kind === 'openai-compatible' ) { 216return proxyCompletion ({ 217baseUrl :be . baseUrl , 218 message, 219 history, 220 systemPrompt, 221 onFrame, 222 signal, 223supervised :be . kind === 'engine' , 224 engine, 225}); 226} 227 228if ( be . kind === 'unavailable' ) { 229// Fail loudly and specifically. This is a real, non-simulated error path. 230throw new Error ( be . error ?? 'No Strata engine is available.' ); 231} 232 233return 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= {} }) { 239const started = Date . now (); 240engine ?. beginReading ( 0 , engine . variantId ); 241const 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 247const defaults = getStore (). expert ?? {}; 248const 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' ])} :{}) }; 249const res = await fetch ( ` ${ baseUrl } /chat/completions` , { 250method :'POST' , 251headers :{ 'content-type' :'application/json' , ...( authorization ?{ authorization :`Bearer ${ authorization } ` } :supervised && getStore (). serving ?. apiKey ?{ authorization :`Bearer ${ getStore (). serving . apiKey } ` } :{}) }, 252 signal, 253body :JSON . stringify ({ 254model :modelId , 255stream :true , 256stream_options :{ include_usage :true }, 257 ...sampling , 258 ...extra , 259 messages, 260}), 261}); 262 263if ( ! res . ok || ! res . body ) { 264const detail = await res . text (). catch (() => '' ); 265throw new Error ( `Engine responded ${ res . status } ${ detail ? `: ${ detail . slice ( 0 , 200 )} ` : '' } ` ); 266} 267 268onFrame ({ type :'start' , demo :false }); 269 270const reader = res . body . getReader (); 271const decoder = new TextDecoder (); 272let buffer = '' ; 273let out = null ; 274let promptTokens = null ; 275let cachedTokens = null ; 276let firstTokenAt = null ; 277let streaming = true ; 278let writing = false ; 279let 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 282answer over the whole wall time. The engine's own numbers replace it when the answer is done. */ 283let chunks = 0 , chars = 0 , lastStats = 0 ; 284const 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 ; 285const 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 287const metricsTicker = supervised 288 ?setInterval (() => { 289void supervisor . pollMetrics (). then (( m ) => { 290if ( streaming && m . source === 'engine' && m . outputTps > 0 ) { 291onFrame ({ type :'stats' , tokensOut :out , tps :m . outputTps , promptTps :m . promptTps , source :'engine' }); 292} 293}). catch (() => {}); 294}, 900 ) 295 :null ; 296 297try { 298for (;;) { 299const { done, value} = await reader . read (); 300buffer += done ?decoder . decode () + '\n' :decoder . decode ( value , { stream :true }); 301const lines = buffer . split ( '\n' ); 302buffer = lines . pop () ?? '' ; 303 304for ( const line of lines ) { 305const trimmed = line . trim (); 306if ( ! trimmed . startsWith ( 'data:' )) continue ; 307const payload = trimmed . slice ( 5 ). trim (); 308if ( payload === '[DONE]' ) continue ; 309let parsed ; 310try { 311parsed = JSON . parse ( payload ); 312} catch { 313continue ; 314} 315if ( parsed . error ) throw new Error ( parsed . error . message ?? 'Inference failed.' ); 316if ( parsed . strata_mcp ) onFrame ({ type :'native-tool' , event :parsed . strata_mcp }); 317if ( parsed . timings ) timings = parsed . timings ; 318if ( parsed . choices ?.[ 0 ]?. finish_reason ) finishReason = parsed . choices [ 0 ]. finish_reason ; 319 320if ( parsed . usage ) { 321if ( Number . isFinite ( parsed . usage . prompt_tokens )) promptTokens = parsed . usage . prompt_tokens ; 322if ( Number . isFinite ( parsed . usage . completion_tokens )) out = parsed . usage . completion_tokens ; 323if ( Number . isFinite ( parsed . usage . prompt_tokens_details ?. cached_tokens )) cachedTokens = parsed . usage . prompt_tokens_details . cached_tokens ; 324} 325 326const delta = parsed . choices ?.[ 0 ]?. delta ; 327if ( ! delta ) continue ; 328 329// Qwen3-style thinking models stream reasoning separately. 330if ( delta . reasoning_content ) { 331if ( firstTokenAt === null ) engine ?. beginThinking (); 332if ( firstTokenAt === null ) firstTokenAt = Date . now (); 333chunks ++ ; chars += delta . reasoning_content . length ; 334onFrame ({ type :'reasoning' , text :delta . reasoning_content }); 335liveStats (); 336} 337if ( delta . content ) { 338if ( ! writing ) { engine ?. beginGenerating (); writing = true ; } 339if ( firstTokenAt === null ) firstTokenAt = Date . now (); 340chunks ++ ; chars += delta . content . length ; 341onFrame ({ type :'delta' , text :delta . content }); 342liveStats (); 343} 344} 345if ( done ) break ; 346} 347} finally { 348streaming = false ; 349if ( metricsTicker ) clearInterval ( metricsTicker ); 350reader . releaseLock (); 351} 352 353signal ?. throwIfAborted (); 354const durationMs = Date . now () - started ; 355const decodeMs = firstTokenAt ?Date . now () - firstTokenAt :durationMs ; 356const tps = Number . isFinite ( timings ?. predicted_per_second ) ?timings . predicted_per_second :out !== null && decodeMs > 0 ?Number (( out / ( decodeMs / 1000 )). toFixed ( 1 )) :null ; 357const usageSource = promptTokens !== null && out !== null ?'reported' :'unavailable' ; 358 359const 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 }; 360onFrame ({ type :'done' , ...result , demo :false }); 361return result ; 362} 363 364/* --------------------------------------------------------------- demo path --- */ 365 366const wantsPreviewExamples = message => / preview examples | website. * (?: markdown | ) | (?: markdown | ) . * 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 ) { 373const p = prompt . toLowerCase (); 374const lead = `Running on ${ variantLabel } . ` ; 375if ( 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 377if ( / readme | repo | project | summar / . test ( p )) { 378return ` ${ 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 395if ( / kv cache | cache | context / . test ( p )) { 396return ` ${ 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 408return ` ${ 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 ) { 430if ( ! candidates . length ) return null ; 431return ( 432candidates . find (( c ) => / ^readme\.md$ / i . test ( c )) ?? 433candidates . find (( c ) => / readme / i . test ( c )) ?? 434candidates . find (( c ) => / \.md$ / i . test ( c )) ?? 435candidates [ 0 ] 436); 437} 438 439/** Which tools the demo engine would reach for, given the prompt. */ 440function proposeTools ( message , candidates = []) { 441const p = message . toLowerCase (); 442const tools = []; 443if ( / readme | read the | open | file | repo | workspace | docs ? \b / . test ( p )) { 444const path = pickReadable ( candidates ); 445if ( path ) { 446tools . push ({ 447id :'read_file' , 448name :'Read file' , 449args :{ path}, 450preview :path , 451effect :'Reads a file inside the workspace. Nothing leaves this computer.' , 452scope :'read' , 453}); 454} 455} 456if ( / run | test | build | lint | install | command / . test ( p )) { 457tools . push ({ 458id :'run_command' , 459name :'Run command' , 460args :{ command :'npm test -- --runInBand' }, 461preview :'npm test -- --runInBand' , 462effect :'Runs a shell command in the workspace and returns the output.' , 463scope :'write' , 464}); 465} 466if ( / edit | change | fix | refactor | write | update the / . test ( p )) { 467tools . push ({ 468id :'write_file' , 469name :'Edit file' , 470args :{ path :'src/app/App.tsx' , change :'apply the requested change' }, 471preview :'src/app/App.tsx · 1 hunk' , 472effect :'Writes to a file inside the workspace. A diff is shown first.' , 473scope :'write' , 474}); 475} 476return tools . slice ( 0 , 2 ); 477} 478 479async function demoCompletion ({ message, modelLabel, onFrame, signal, engine, candidates= [] }) { 480const variety = modelLabel ?? 'the loaded model' ; 481const promptTokens = estimateTokens ( message ); 482 483onFrame ({ 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. 487for ( const tool of wantsPreviewExamples ( message ) ?[] :proposeTools ( message , candidates )) { 488onFrame ({ type :'tool' , tool}); 489} 490await engine . beginReading ( promptTokens , engine . variantId ); 491 492const step = Math . max ( 1 , Math . round ( promptTokens / 14 )); 493for ( let done = 0 ; done <= promptTokens ; done += step ) { 494signal ?. throwIfAborted (); 495engine . progressReading ( Math . min ( done , promptTokens )); 496await sleep ( CHUNK_MS * 2 ); 497} 498engine . progressReading ( promptTokens ); 499await sleep ( 220 ); 500signal ?. throwIfAborted (); 501 502engine . beginGenerating (); 503const chunks = tokenize ( demoAnswer ( message , variety )); 504const started = Date . now (); 505let emitted = 0 ; 506 507for ( const chunk of chunks ) { 508signal ?. throwIfAborted (); 509onFrame ({ type :'delta' , text :chunk }); 510emitted += estimateTokens ( chunk ); 511if ( emitted % 3 === 0 ) { 512const seconds = Math . max ( 0.001 , ( Date . now () - started ) / 1000 ); 513onFrame ({ type :'stats' , tokensOut :emitted , tps :Number (( emitted / seconds ). toFixed ( 1 )) }); 514} 515await sleep ( CHUNK_MS ); 516} 517 518const durationMs = Date . now () - started ; 519const tps = Number (( emitted / Math . max ( 0.001 , durationMs / 1000 )). toFixed ( 1 )); 520signal ?. throwIfAborted (); 521if ( wantsPreviewExamples ( message )) onFrame ({ type :'artifacts' , artifacts :previewExamples }); 522onFrame ({ type :'done' , tokensIn :promptTokens , tokensOut :emitted , tps, durationMs, demo :true , usageSource :'demo' }); 523return { 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 }) { 532if ( ! settled ) return 'unpacking the bundled engine… (about a minute the first time)' ; 533if ( backend ?. kind !== 'unavailable' || ! engine ) return backend ?. name ?? 'No Strata engine' ; 534if ( engine . usable ) return `Strata engine ${ engine . engine ?. version ? ' ' + engine . engine . version : '' } is installed; no model is loaded yet` ; 535return engine . notice ?`No Strata engine for this PC. ${ engine . notice } ` :backend . name ; 536}