okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
64b48c0d0
main
1import { userError } from './format' ; 2/** Thin HTTP client for the Strata host. Zero deps, works in browser and Electron renderer. */ 3 4const BASE = ( globalThis as { __STRATA_HOST__ ?:string }). __STRATA_HOST__ ?? '' ; 5 6export class ApiError extends Error { 7constructor ( 8message :string , 9readonly status :number , 10readonly body ?:unknown , 11) { 12super ( userError ( message )); 13this . name = 'ApiError' ; 14} 15} 16 17async function request < T > ( method :string , path :string , body ?:unknown , signal ?:AbortSignal ) :Promise < T > { 18const res = await fetch ( ` ${ BASE } ${ path } ` , { 19 method, 20 signal, 21headers :body === undefined ?undefined :{ 'content-type' :'application/json' }, 22body :body === undefined ?undefined :JSON . stringify ( body ), 23}); 24const text = await res . text (); 25const data = text ?( JSON . parse ( text ) as unknown ) :undefined ; 26if ( ! res . ok ) { 27const message = 28( data as { error ?:string } | undefined )?. error ?? `Request failed ( ${ res . status } ${ res . statusText } )` ; 29throw new ApiError ( message , res . status , data ); 30} 31return data as T ; 32} 33 34export const api = { 35get :< T > ( path :string , signal ?:AbortSignal ) => request < T >( 'GET' , path , undefined , signal ), 36post :< T > ( path :string , body ?:unknown ) => request < T >( 'POST' , path , body ), 37patch :< T > ( path :string , body ?:unknown ) => request < T >( 'PATCH' , path , body ), 38put :< T > ( path :string , body ?:unknown ) => request < T >( 'PUT' , path , body ), 39del :< T > ( path :string ) => request < T >( 'DELETE' , path ), 40}; 41 42export interface StreamEvent { 43event :string ; 44data :Record < string , unknown >; 45} 46 47/** Subscribe to the host event stream. Returns an unsubscribe function. */ 48export function onEvent ( handler :( e :StreamEvent ) => void , onStatus ?:( s :'live' | 'offline' ) => void ) { 49let source :EventSource ; 50let seenAt = Date . now (); 51const names = [ 'engine' , 'monitor' , 'models' , 'native' , 'image-models' , 'runtime' , 'providers' , 'serving' , 'download' , 'log' , 'setup' , 'skills' , 'task' , 'goal' , 'timeskip' , 'plan' , 'queue' , 'chats' ]; 52const connect = () => { 53source ?. close (); 54seenAt = Date . now (); 55source = new EventSource ( ` ${ BASE } /api/events` ); 56for ( const name of names ) { 57source . addEventListener ( name , (( ev :MessageEvent ) => { 58seenAt = Date . now (); 59try { handler ({ event :name , data :JSON . parse ( ev . data ) as Record < string , unknown > }); } 60catch { /* Ignore malformed frames without losing valid state. */ } 61}) as EventListener ); 62} 63source . addEventListener ( 'open' , () => { seenAt = Date . now (); onStatus ?.( 'live' ); }); 64source . addEventListener ( 'error' , () => onStatus ?.( 'offline' )); 65source . addEventListener ( 'message' , ev => { 66seenAt = Date . now (); 67try { handler ({ event :'message' , data :JSON . parse (( ev as MessageEvent ). data ) as Record < string , unknown > }); } 68catch { /* Ignore malformed frames. */ } 69}); 70}; 71connect (); 72// The host sends monitor frames each second. Some proxies leave a dead SSE 73// socket open, so silence must also invalidate readings and retry the stream. 74const watchdog = setInterval (() => { 75if ( Date . now () - seenAt <= 10000 ) return ; 76onStatus ?.( 'offline' ); 77connect (); 78}, 5000 ); 79return () => { clearInterval ( watchdog ); source . close (); }; 80} 81 82/** POST a JSON body and consume an NDJSON/SSE-ish stream of JSON frames. */ 83export async function streamPost ( 84path :string , 85body :unknown , 86onFrame :( frame :Record < string , unknown >) => void , 87signal ?:AbortSignal , 88) :Promise < void > { 89const res = await fetch ( ` ${ BASE } ${ path } ` , { 90method :'POST' , 91headers :{ 'content-type' :'application/json' }, 92body :JSON . stringify ( body ), 93 signal, 94}); 95if ( ! res . ok || ! res . body ) { 96const text = await res . text (). catch (() => '' ); 97throw new ApiError ( text || `Stream failed ( ${ res . status } )` , res . status ); 98} 99const reader = res . body . getReader (); 100const decoder = new TextDecoder (); 101let buffer = '' ; 102for (;;) { 103const { done, value} = await reader . read (); 104if ( done ) break ; 105buffer += decoder . decode ( value , { stream :true }); 106let idx :number ; 107while (( idx = buffer . indexOf ( '\n' )) >= 0 ) { 108const line = buffer . slice ( 0 , idx ). trim (); 109buffer = buffer . slice ( idx + 1 ); 110if ( ! line ) continue ; 111try { 112onFrame ( JSON . parse ( line ) as Record < string , unknown >); 113} catch { 114/* ignore partial frame */ 115} 116} 117} 118if ( buffer . trim ()) { 119try { 120onFrame ( JSON . parse ( buffer . trim ()) as Record < string , unknown >); 121} catch { 122/* ignore */ 123} 124} 125}