okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
1/** Saved API connections. Secrets never leave the host's private credentials file. */ 2import { modelReadsPictures , modelSupportsReasoning } from './vision-probe.mjs' ; 3import { isOpenRouter , OPENROUTER_EFFORTS } from './agent/profile.mjs' ; 4import { existsSync , readFileSync , writeFileSync , renameSync , mkdirSync } from 'node:fs' ; 5import { join } from 'node:path' ; 6import { randomUUID } from 'node:crypto' ; 7import { makePrivate } from './private-file.mjs' ; 8 9export const PROVIDER_CATALOG = [ 10{ id :'openai' , name :'OpenAI' , baseUrl :'https://api.openai.com/v1' , protocol :'openai-responses' }, 11{ id :'anthropic' , name :'Anthropic' , baseUrl :'https://api.anthropic.com/v1' , protocol :'anthropic' }, 12{ id :'deepseek' , name :'DeepSeek' , baseUrl :'https://api.deepseek.com' , protocol :'openai-chat' }, 13{ id :'openrouter' , name :'OpenRouter' , baseUrl :'https://openrouter.ai/api/v1' , protocol :'openai-chat' }, 14{ id :'baseten' , name :'Baseten' , baseUrl :'https://inference.baseten.co/v1' , protocol :'openai-chat' }, 15{ id :'cerebras' , name :'Cerebras' , baseUrl :'https://api.cerebras.ai/v1' , protocol :'openai-chat' }, 16{ id :'fireworks' , name :'Fireworks' , baseUrl :'https://api.fireworks.ai/inference/v1' , protocol :'openai-chat' }, 17{ id :'google' , name :'Google Gemini' , baseUrl :'https://generativelanguage.googleapis.com/v1beta/openai' , protocol :'openai-chat' }, 18{ id :'groq' , name :'Groq' , baseUrl :'https://api.groq.com/openai/v1' , protocol :'openai-chat' }, 19{ id :'huggingface' , name :'Hugging Face' , baseUrl :'https://router.huggingface.co/v1' , protocol :'openai-chat' }, 20{ id :'minimax' , name :'MiniMax' , baseUrl :'https://api.minimax.io/v1' , protocol :'openai-chat' }, 21{ id :'mistral' , name :'Mistral' , baseUrl :'https://api.mistral.ai/v1' , protocol :'openai-chat' }, 22{ id :'moonshotai' , name :'Moonshot AI · Kimi' , baseUrl :'https://api.moonshot.ai/v1' , protocol :'openai-chat' }, 23{ id :'nvidia' , name :'NVIDIA' , baseUrl :'https://integrate.api.nvidia.com/v1' , protocol :'openai-chat' }, 24{ id :'qwen' , name :'Qwen · Model Studio' , baseUrl :'' , protocol :'openai-chat' , baseUrlHint :'Paste the OpenAI compatible base URL for your workspace and region from Model Studio.' }, 25{ id :'qwen-us' , name :'Qwen · US' , baseUrl :'https://dashscope-us.aliyuncs.com/compatible-mode/v1' , protocol :'openai-chat' }, 26{ id :'together' , name :'Together AI' , baseUrl :'https://api.together.ai/v1' , protocol :'openai-chat' }, 27{ id :'vercel-ai-gateway' , name :'Vercel AI Gateway' , baseUrl :'https://ai-gateway.vercel.sh/v1' , protocol :'openai-chat' }, 28{ id :'xai' , name :'xAI' , baseUrl :'https://api.x.ai/v1' , protocol :'openai-responses' }, 29{ id :'zai' , name :'Z.AI' , baseUrl :'https://api.z.ai/api/paas/v4' , protocol :'openai-chat' }, 30]; 31const PROTOCOLS = [ 'openai-chat' , 'openai-responses' , 'anthropic' ]; 32const fail = message => { throw new Error ( message ); }; 33const text = ( value , max = 160 ) => typeof value === 'string' ?value . trim (). slice ( 0 , max ) :'' ; 34/** The answer speed of a model API's reply: the tokens it reports over the time from its first streamed token to the end, never over the whole 35* wait (that would put the time to the first token, often seconds of prompt reading, into the speed). null when it reported no tokens; 36* with no usable first-token time (or under a quarter of a second) the whole time is the best there is. */ 37export function answerSpeed ( tokensOut , durationMs , firstTokenMs ) { 38if ( ! Number . isFinite ( tokensOut ) || tokensOut <= 0 ) return null ; 39const decodeMs = Number . isFinite ( firstTokenMs ) ?durationMs - firstTokenMs :NaN ; 40const ms = decodeMs >= 250 ?decodeMs :durationMs ; 41return Number (( tokensOut / Math . max ( 0.001 , ms / 1000 )). toFixed ( 1 )); 42} 43 44export function normalizeBaseUrl ( value ) { 45let url ; try { url = new URL ( text ( value , 2048 )); } catch { fail ( 'Enter a full http:// or https:// API address.' ); } 46if ( ! [ 'http:' , 'https:' ]. includes ( url . protocol ) || url . username || url . password || url . search || url . hash ) fail ( 'Use an HTTP or HTTPS base URL without credentials, a query, or a fragment.' ); 47if ( / \/ ( chat\/completions | responses | messages | models ) \/ ? $ / . test ( url . pathname )) fail ( 'Enter the API base URL, without /chat/completions, /responses, /messages, or /models.' ); 48return url . href . replace ( / \/ + $ / , '' ); 49} 50const publicConnection = ({ apiKey, ...connection }) => ({ ...connection , apiKeySet :!! apiKey }); 51const numeric = value => typeof value === 'number' && Number . isFinite ( value ) && value >= 0 ?value :null ; 52 53export function createModelProviders ({ directory, changed= () => {}, fetchImpl= fetch , knownThinks= () => null }) { 54mkdirSync ( directory , { recursive :true }); 55const file = join ( directory , 'model-providers.json' ); 56let connections = []; 57if ( existsSync ( file )) { 58// Do not silently erase connections if a credentials file needs repair. 59const saved = JSON . parse ( readFileSync ( file , 'utf8' )); 60if ( ! Array . isArray ( saved )) fail ( 'The model connections file is invalid.' ); 61connections = saved ; makePrivate ( file ); 62} 63function list () { return { catalog :PROVIDER_CATALOG , connections :connections . map ( publicConnection ) }; } 64function persist ( next ) { 65const temp = ` ${ file } . ${ randomUUID ()} .tmp` ; 66writeFileSync ( temp , JSON . stringify ( next , null , 2 ), { mode :0o600 }); 67makePrivate ( temp ); renameSync ( temp , file ); makePrivate ( file ); 68connections = next ; changed ( list ()); return list (); 69} 70function draft ( body ) { 71const existing = body . id ?connections . find ( c => c . id === body . id ) :null ; 72if ( body . id && ! existing ) fail ( 'This connection no longer exists. Close the editor and try again.' ); 73const kind = body . kind === 'custom' ?'custom' :'provider' ; 74const catalog = kind === 'provider' ?PROVIDER_CATALOG . find ( p => p . id === body . provider ) :null ; 75if ( kind === 'provider' && ! catalog ) fail ( 'Choose a model provider.' ); 76const protocol = body . protocol ?? catalog ?. protocol ; 77if ( ! PROTOCOLS . includes ( protocol )) fail ( 'Choose a supported API protocol.' ); 78const name = text ( body . name ) || catalog ?. name ; 79if ( ! name ) fail ( 'Give this connection a display name.' ); 80const baseUrl = normalizeBaseUrl ( body . baseUrl || catalog ?. baseUrl ); 81const sameDestination = existing && existing . baseUrl === baseUrl && existing . protocol === protocol ; 82// An unchanged blank key means keep it; changing the destination requires a new key. 83const apiKey = body . clearKey ?'' :text ( body . apiKey , 4096 ) || ( sameDestination ?existing . apiKey :'' ) || '' ; 84if ( / [ \r\n ] / . test ( apiKey )) fail ( 'The API key contains an invalid character.' ); 85if ( kind === 'provider' && ! apiKey ) fail ( 'Enter this provider’s API key.' ); 86const rows = Array . isArray ( body . models ) ?body . models :[]; 87if ( rows . length > 100 ) fail ( 'Add up to 100 models to one connection.' ); 88const models = rows . map ( row => { 89const id = text ( row . id , 256 ); if ( ! id || / [ \r\n ] / . test ( id )) fail ( 'Every model needs a model ID.' ); 90return { id, name :text ( row . name ) || id , contextMax :numeric ( row . contextMax ), maxOutput :numeric ( row . maxOutput ), vision :row . vision === true ?true :row . vision === false ?false :null , reasoning :row . reasoning === true ?true :row . reasoning === false ?false :null }; 91}); 92if ( new Set ( models . map ( m => m . id )). size !== models . length ) fail ( 'Each model ID must be unique within this connection.' ); 93return { id :existing ?. id ?? randomUUID (), kind, provider :catalog ?. id ?? null , name, baseUrl, protocol, apiKey, models}; 94} 95function save ( body ) { 96const connection = draft ( body ); 97if ( ! connection . models . length ) fail ( 'Choose at least one model or add its ID.' ); 98return persist ( connections . some ( c => c . id === connection . id ) ?connections . map ( c => c . id === connection . id ?connection :c ) :[ ...connections , connection ]); 99} 100function remove ( id ) { return persist ( connections . filter ( c => c . id !== id )); } 101function resolve ( selection ) { 102const connection = connections . find ( c => c . id === selection ?. connectionId ); 103const model = connection ?. models . find ( m => m . id === selection ?. modelId ); 104if ( ! connection || ! model ) fail ( 'This API model is no longer available. Choose another model in the chat picker.' ); 105return { connection, model}; 106} 107function headers ( connection ) { 108return { 109'content-type' :'application/json' , 110 ...( connection . protocol === 'anthropic' ?{ 'anthropic-version' :'2023-06-01' , ...( connection . apiKey ?{ 'x-api-key' :connection . apiKey } :{}) } :connection . apiKey ?{ authorization :`Bearer ${ connection . apiKey } ` } :{}), 111}; 112} 113async function request ( connection , path , { signal, ...options } = {}) { 114let res ; 115try { 116res = await fetchImpl ( ` ${ connection . baseUrl } / ${ path } ` , { ...options , headers :headers ( connection ), redirect :'error' , signal}); 117} catch ( err ) { 118if ( signal ?. aborted ) throw signal . reason ; 119fail ( 'Could not reach the model API. Check the address and whether the server is running.' ); 120} 121if ( ! res . ok ) { 122// Provider errors can echo credentials/request bodies. Report status, not their raw body. 123await res . body ?. cancel (); 124fail ( res . status === 401 || res . status === 403 ?'The model API rejected the credentials. Check the API key.' :res . status === 404 ?'The model API could not find this endpoint or model. Check the base URL and model ID.' :res . status === 429 ?'The model API is rate limited or out of credit. Try again later.' :`The model API returned HTTP ${ res . status } . Check the connection and try again.` ); 125} 126return res ; 127} 128async function discover ( body , signal ) { 129const connection = draft ( body ); 130const timeout = AbortSignal . timeout ( 20000 ); 131const requestSignal = signal ?AbortSignal . any ([ signal , timeout ]) :timeout ; 132let data , rows = [], after = null ; 133// Anthropic paginates /models. Most compatible APIs return the list in one page. 134for ( let page = 0 ; page < 20 ; page ++ ) { 135const path = connection . protocol === 'anthropic' ?`models?limit=100 ${ after ? `&after_id= ${ encodeURIComponent ( after )} ` : '' } ` :'models' ; 136const res = await request ( connection , path , { signal :requestSignal }); 137try { data = await res . json (); } catch { fail ( 'The API did not return a model list. You can add a model ID manually.' ); } 138if ( ! Array . isArray ( data . data )) fail ( 'The API did not return a model list. You can add a model ID manually.' ); 139rows . push ( ...data . data ); 140if ( connection . protocol !== 'anthropic' || ! data . has_more ) break ; 141after = data . last_id ; if ( ! after ) break ; 142} 143const models = [ ...new Map ( rows . filter ( m => text ( m . id , 256 )). map ( m => [ m . id , { id :text ( m . id , 256 ), name :text ( m . display_name ?? m . name ) || text ( m . id , 256 ), contextMax :numeric ( m . context_length ?? m . max_context_length ?? m . context_window ), maxOutput :numeric ( m . max_output_tokens ?? m . max_completion_tokens ?? m . top_provider ?. max_completion_tokens ), vision :modelReadsPictures ( m ), reasoning :modelSupportsReasoning ( m ) }])). values ()]; 144return { models :models . sort (( a , b ) => a . name . localeCompare ( b . name )) }; 145} 146async function stream ({ selection, message, history= [], systemPrompt= '' , images= [], thinking, signal, onFrame}) { 147const { connection, model} = resolve ( selection ); 148const started = Date . now (); 149const messages = history . filter ( m => [ 'user' , 'assistant' ]. includes ( m . role ) && typeof m . content === 'string' ). slice ( - 40 ). map ( m => ({ role :m . role , content :m . content })); 150// Pictures only go to OpenAI-style servers (the one protocol every local server shares); other protocols keep the text. 151const pics = connection . protocol === 'openai-chat' ?images :[]; 152messages . push ({ role :'user' , content :pics . length ?[{ type :'text' , text :message }, ...pics . map ( i => ({ type :'image_url' , image_url :{ url :i . url } }))] :message }); 153const protocol = connection . protocol ; 154const payload = protocol === 'anthropic' 155 ?{ model :model . id , messages, system :systemPrompt , max_tokens :8192 , stream :true } 156 :protocol === 'openai-responses' 157 ?{ model :model . id , input :messages , instructions :systemPrompt , stream :true , store :false } 158 :{ model :model . id , messages :[ ...( systemPrompt ?[{ role :'system' , content :systemPrompt }] :[]), ...messages ], stream :true , ...([ 'openai' , 'deepseek' , 'openrouter' , 'google' , 'moonshotai' ]. includes ( connection . provider ) ?{ stream_options :{ include_usage :true } } :{}) }; 159// Match the native composer's effort names. Unknown support and other protocols keep provider defaults. 160const choice = typeof thinking === 'string' ?thinking . toLowerCase () :'' ; 161if ( protocol === 'openai-chat' && ( model . reasoning ?? knownThinks ( connection , model . id )) === true && [ 'off' , 'low' , 'medium' , 'high' , 'max' ]. includes ( choice )) { 162if ( isOpenRouter ( connection )) payload . reasoning = { effort :OPENROUTER_EFFORTS [ choice ] }; 163else payload . reasoning_effort = ({ off :'none' , max :'high' })[ choice ] ?? choice ; 164} 165const requestSignal = signal ?AbortSignal . any ([ signal , AbortSignal . timeout ( 10 * 60 * 1000 )]) :AbortSignal . timeout ( 10 * 60 * 1000 ); 166const res = await request ( connection , protocol === 'anthropic' ?'messages' :protocol === 'openai-responses' ?'responses' :'chat/completions' , { method :'POST' , body :JSON . stringify ( payload ), signal :requestSignal }); 167if ( ! res . body ) fail ( 'The model API returned an empty response.' ); 168onFrame ({ type :'start' , model :model . name , contextMax :model . contextMax , demo :false }); 169let tokensIn = null , tokensOut = null , textLength = 0 , firstToken = null , finished = false ; 170function emit ( type , value ) { 171if ( typeof value !== 'string' || ! value ) return ; 172if ( firstToken === null ) firstToken = Date . now () - started ; 173if ( type === 'delta' ) textLength += value . length ; 174onFrame ({ type, text :value }); 175} 176function usage ( value ) { 177if ( ! value ) return ; 178tokensIn = numeric ( value . prompt_tokens ?? value . input_tokens ) ?? tokensIn ; 179tokensOut = numeric ( value . completion_tokens ?? value . output_tokens ) ?? tokensOut ; 180} 181function consume ( data ) { 182if ( data . error || data . type === 'error' || data . type === 'response.failed' ) fail ( 'The model API could not complete this response. Check the provider and try again.' ); 183if ( protocol === 'anthropic' ) { 184if ( data . type === 'message_start' ) usage ( data . message ?. usage ); 185if ( data . type === 'content_block_delta' ) { emit ( 'delta' , data . delta ?. text ); emit ( 'reasoning' , data . delta ?. thinking ); } 186if ( data . type === 'message_delta' ) usage ( data . usage ); 187if ( data . type === 'message_stop' ) finished = true ; 188} else if ( protocol === 'openai-responses' ) { 189if ([ 'response.output_text.delta' , 'response.refusal.delta' ]. includes ( data . type )) emit ( 'delta' , data . delta ); 190if ( data . type === 'response.reasoning_summary_text.delta' ) emit ( 'reasoning' , data . delta ); 191if ( data . type === 'response.completed' ) { usage ( data . response ?. usage ); finished = true ; } 192if ( data . type === 'response.incomplete' ) fail ( 'The API stopped before completing the response. Partial output is preserved.' ); 193} else { 194const choice = data . choices ?. find ( c => c . index === 0 ) ?? data . choices ?.[ 0 ]; 195emit ( 'delta' , choice ?. delta ?. content ?? choice ?. delta ?. refusal ); 196emit ( 'reasoning' , choice ?. delta ?. reasoning_content ?? choice ?. delta ?. reasoning ); 197usage ( data . usage ); 198if ( choice ?. finish_reason ) finished = true ; 199} 200} 201const reader = res . body . getReader (), decoder = new TextDecoder (); 202let buffer = '' , eventData = []; 203const line = value => { 204if ( ! value ) { 205if ( ! eventData . length ) return ; 206const raw = eventData . join ( '\n' ); eventData = []; 207if ( raw === '[DONE]' ) { finished = true ; return ; } 208let data ; try { data = JSON . parse ( raw ); } catch { fail ( 'The model API sent an invalid stream event. Partial output is preserved.' ); } 209consume ( data ); 210} else if ( value . startsWith ( 'data:' )) eventData . push ( value . slice ( 5 ). trimStart ()); 211}; 212try { 213for (;;) { 214const { done, value} = await reader . read (); 215if ( done ) break ; 216buffer += decoder . decode ( value , { stream :true }); 217if ( buffer . length > 4 * 1024 * 1024 ) fail ( 'The model API sent an oversized stream event.' ); 218let end ; 219while (( end = buffer . indexOf ( '\n' )) >= 0 ) { line ( buffer . slice ( 0 , end ). replace ( / \r$ / , '' )); buffer = buffer . slice ( end + 1 ); } 220} 221if ( buffer ) line ( buffer . replace ( / \r$ / , '' )); line ( '' ); 222requestSignal . throwIfAborted (); 223if ( ! finished ) fail ( 'The API connection ended early. Partial output is preserved; try again.' ); 224if ( ! textLength ) fail ( 'The model returned no text. Choose a model that supports text chat.' ); 225} finally { await reader . cancel (). catch (() => {}); reader . releaseLock (); } 226const durationMs = Date . now () - started ; 227const result = { tokensIn, tokensOut, usageSource :tokensIn !== null && tokensOut !== null ?'reported' :'unavailable' , durationMs, ttftMs :firstToken , tps :answerSpeed ( tokensOut , durationMs , firstToken ) }; 228onFrame ({ type :'done' , ...result }); return result ; 229} 230/** Connections WITH their keys, for the host's own agent bridge only; never serialised to a client. */ 231function withSecrets () { return connections . map ( c => ({ ...c , models :c . models . map ( m => ({ ...m })) })); } 232return { list, save, remove, discover, resolve, stream, withSecrets}; 233}