okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
22a3d7068
main
1/** Serving surface: API keys, access policy, and the request log. */ 2import { randomBytes } from 'node:crypto' ; 3import os from 'node:os' ; 4import { get as getStore , update } from './store.mjs' ; 5import { nowIso , round , sameSecret , uid } from './util.mjs' ; 6 7const requests = []; 8const MAX_REQUESTS = 60 ; 9const cancellations = new Map (); 10let revision = Date . now (); 11 12let hubRef = null ; 13let tunnel = { status :'idle' , mode :null , url :null , error :null , installed :false , originUrl :null }; 14export function setTunnel ( value ) { tunnel = value ; emit (); } 15const tunnelActive = () => [ 'starting' , 'connected' , 'stopping' ]. includes ( tunnel . status ); 16let sharing = { active :false , url :null }; 17export function setSharing ( value ) { sharing = value ; emit (); } 18let port = 8080 ; 19let running = false ; 20let bindHost = '127.0.0.1' ; 21const isLocal = () => [ '127.0.0.1' , 'localhost' , '::1' ]. includes ( bindHost ); 22 23export function init ( hub , opts = {}) { 24hubRef = hub ; 25port = opts . port ?? port ; 26running = true ; 27bindHost = opts . host ?? '127.0.0.1' ; 28} 29 30export function baseUrl () { 31const host = isLocal () ?'127.0.0.1' :localIp (); 32return `http:// ${ host } : ${ port } /v1` ; 33} 34 35export function state () { 36const s = getStore (); 37const active = requests . filter (( r ) => r . state === 'generating' || r . state === 'queued' ); 38return { 39 revision, 40 running, 41baseUrl :sharing . active ?sharing . url :baseUrl (), 42// The address on this computer, the one the app's own port serves, kept apart from the sharing address (#4798). 43localUrl :baseUrl (), 44 sharing, 45 tunnel, 46 port, 47endpoints :{ openai :'/chat/completions' , anthropic :'/messages' , models :'/models' }, 48access :{ 49otherDevices :! isLocal () || sharing . active || tunnelActive (), 50apiKeySet :!! s . serving ?. apiKey , 51apiKeyHint :s . serving ?. apiKey ?`Ends in ${ s . serving . apiKey . slice ( - 4 )} ` :null , 52allowOrigin :'*' , 53}, 54stats :{ 55running :active . filter (( r ) => r . state === 'generating' ). length , 56waiting :active . filter (( r ) => r . state === 'queued' ). length , 57completed :requests . filter (( r ) => r . state === 'done' ). length , 58failed :requests . filter (( r ) => r . state === 'error' ). length , 59tokensOut :requests . reduce (( sum , r ) => sum + ( r . tokensOut || 0 ), 0 ), 60}, 61requests :[ ...requests ]. reverse (), 62pauseServing :!! s . serving ?. pauseServing , 63}; 64} 65 66function emit () { 67revision = Math . max ( Date . now (), revision + 1 ); 68hubRef ?. send ( 'serving' , state ()); 69} 70 71export function patch ( body ) { 72const s = getStore (); 73const serving = { ...( s . serving ?? {}) }; 74if ( typeof body . otherDevices === 'boolean' && body . otherDevices !== ! isLocal ()) throw new Error ( 'Change the host listen address and restart to update network access.' ); 75// The key is optional (owner decision, 0.2.2): removing it while sharing or the tunnel runs is allowed; the app warns in plain words (local-share.mjs, cloudflare.mjs). 76if ( body . apiKey === null ) serving . apiKey = null ; 77else if ( typeof body . apiKey === 'string' && body . apiKey . trim ()) serving . apiKey = body . apiKey . trim (); 78else if ( body . generateKey ) serving . apiKey = `sk-strata- ${ randomBytes ( 12 ). toString ( 'hex' )} ` ; 79if ( typeof body . pauseServing === 'boolean' ) serving . pauseServing = body . pauseServing ; 80update ({ serving}); 81emit (); 82return state (); 83} 84 85export function authorized ( req ) { 86const key = getStore (). serving ?. apiKey ; 87if ( ! key ) return true ; 88const header = req . headers ?. authorization ; 89const bearer = typeof header === 'string' && header . startsWith ( 'Bearer ' ) ?header . slice ( 7 ) :'' ; 90const alt = req . headers ?.[ 'x-api-key' ]; 91// #4535: constant time over fixed-length digests, and both headers are always compared so the time does not show which one was sent. 92const viaBearer = sameSecret ( bearer , key ); 93const viaHeader = sameSecret ( alt , key ); 94return viaBearer || viaHeader ; 95} 96 97export function open ({ client, endpoint, tokensIn= null , model, instanceId, gpuIds, cancel}) { 98const entry = { 99id :uid ( 'req' ), 100at :nowIso (), 101 client, 102 endpoint, 103state :'queued' , 104 tokensIn, 105tokensOut :null , 106durationMs :0 , 107model :model ?? 'local' , 108 instanceId, gpuIds, 109cancellable :typeof cancel === 'function' , 110cancelRequested :false , 111usageSource :'unavailable' , 112}; 113if ( entry . cancellable ) cancellations . set ( entry . id , cancel ); 114requests . push ( entry ); 115if ( requests . length > MAX_REQUESTS ) { 116const oldestCompleted = requests . findIndex ( r => ! [ 'generating' , 'queued' ]. includes ( r . state )); 117if ( oldestCompleted >= 0 ) requests . splice ( oldestCompleted , 1 ); 118} 119emit (); 120return entry ; 121} 122 123export function mark ( id , patchObj ) { 124const entry = requests . find (( r ) => r . id === id ); 125if ( ! entry ) return ; 126Object . assign ( entry , patchObj ); 127emit (); 128return entry ; 129} 130 131export function finish ( id , { tokensOut, durationMs, error}) { 132const entry = requests . find (( r ) => r . id === id ); 133if ( ! entry ) return ; 134entry . state = error ?'error' :'done' ; 135entry . tokensOut = tokensOut ?? entry . tokensOut ; 136entry . durationMs = durationMs ?? entry . durationMs ; 137if ( error ) entry . error = error ; 138entry . cancellable = false ; 139cancellations . delete ( id ); 140emit (); 141} 142 143export function cancel ( id ) { 144const entry = requests . find (( r ) => r . id === id ); 145if ( ! entry ) throw new Error ( 'This request is no longer retained.' ); 146if ( ! [ 'generating' , 'queued' ]. includes ( entry . state )) return state (); 147const abort = cancellations . get ( id ); 148if ( ! abort ) throw new Error ( 'This request cannot be cancelled by this host.' ); 149if ( ! entry . cancelRequested ) { entry . cancelRequested = true ; abort (); } 150emit (); 151return state (); 152} 153 154export function rateSample () { 155const done = requests . filter (( r ) => r . state === 'done' && r . tokensOut > 0 ); 156if ( ! done . length ) return 0 ; 157const tps = done . filter (( r ) => r . tps > 0 ). map (( r ) => r . tps ); // answer speeds (decode time), not tokens over the whole request 158if ( ! tps . length ) return 0 ; 159return round ( tps . reduce (( a , b ) => a + b , 0 ) / tps . length , 1 ); 160} 161 162function localIp () { 163try { 164const nets = os . networkInterfaces (); 165for ( const list of Object . values ( nets )) { 166for ( const net of list ?? []) { 167if ( net . family === 'IPv4' && ! net . internal ) return net . address ; 168} 169} 170} catch { 171/* fall through */ 172} 173return '127.0.0.1' ; 174}