okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c163678f7
main
1/** 2* Response settings for agent turns. 3* 4* The chat's own path sends the Expert sampling (temperature, top-p, top-k, repeat penalty, seed) and the composer's thinking budget with 5* every request. The agent's requests are made by the Harness, which has no place for either, so they never reached the model. When a 6* person has changed one of them, the agent's model route goes through the small forwarding endpoint below (on this computer only), which 7* adds exactly the fields that differ from the defaults and passes everything else through untouched. With every setting at its default the 8* agent talks to the model directly, byte for byte as before. 9* 10* Only a local model, or an OpenAI-style server on this computer or this network, is shaped: a cloud service would reject fields it does not know. 11*/ 12 13import http from 'node:http' ; 14import https from 'node:https' ; 15 16/** The thinking budgets the composer offers (0 = no limit is not a budget). */ 17export const BUDGETS = Object . freeze ([ 2048 , 8192 , 32768 ]); 18/** The offered budget nearest to what a chat asks for (0 stays 0). */ 19export function nearestBudget ( value ) { 20const n = Number ( value ); 21if ( ! Number . isFinite ( n ) || n <= 0 ) return 0 ; 22return BUDGETS . reduce (( best , b ) => ( Math . abs ( b - n ) < Math . abs ( best - n ) ?b :best ), BUDGETS [ 0 ]); 23} 24 25/** Expert setting id -> request field, and the default each one has (the catalog's recommended value). */ 26const SAMPLING = Object . freeze ({ 27'sample.temp' :[ 'temperature' , 0.6 ], 28'sample.topP' :[ 'top_p' , 0.95 ], 29'sample.topK' :[ 'top_k' , 40 ], 30'sample.repeat' :[ 'repeat_penalty' , 1.05 ], 31'sample.seed' :[ 'seed' , - 1 ], 32}); 33 34/** The request fields for the Expert settings that are not at their default, or null when all are. */ 35export function samplingFromExpert ( expert ) { 36const out = {}; 37for ( const [ id , [ field , recommended ]] of Object . entries ( SAMPLING )) { 38const v = expert ?.[ id ]; 39if ( typeof v === 'number' && Number . isFinite ( v ) && v !== recommended ) out [ field ] = v ; 40} 41if ( expert ?.[ 'sample.speedProjection' ] === false ) out . experimental_speed_projection = false ; 42const cap = Number ( expert ?.[ 'sample.maxTokens' ]); 43if ( Number . isFinite ( cap ) && cap > 0 ) out . max_tokens = Math . floor ( cap ); 44return Object . keys ( out ). length ?out :null ; 45} 46 47/** 48* The request body with the person's settings added. A field the request already carries is left alone (the Harness's own wins), the 49* thinking budget is only added while thinking is on, and an output cap only ever lowers the request's own. 50*/ 51export function shapeBody ( body , { sampling= null , budget= 0 } = {}) { 52if ( ! body || typeof body !== 'object' || Array . isArray ( body )) return body ; 53const out = { ...body }; 54for ( const [ field , value ] of Object . entries ( sampling ?? {})) { 55if ( field === 'max_tokens' || field === 'max_completion_tokens' ) continue ; 56if ( out [ field ] === undefined ) out [ field ] = value ; 57} 58if ( sampling ?. max_tokens ) { 59for ( const key of [ 'max_tokens' , 'max_completion_tokens' ]) if ( Number . isFinite ( out [ key ])) out [ key ] = Math . min ( out [ key ], sampling . max_tokens ); 60if ( out . max_tokens === undefined && out . max_completion_tokens === undefined ) out . max_tokens = sampling . max_tokens ; 61} 62const thinkingOff = out . chat_template_kwargs ?. enable_thinking === false ; 63if ( budget > 0 && ! thinkingOff && out . reasoning_budget_tokens === undefined ) out . reasoning_budget_tokens = budget ; 64return out ; 65} 66 67/** An address on this computer or on a private network: where the person's own model servers live. */ 68export function isPrivateHost ( url ) { 69let host ; 70try { host = new URL ( url ). hostname . toLowerCase (); } catch { return false ; } 71host = host . replace ( / ^\[ | \]$ / g , '' ); 72if ( host === 'localhost' || host === '::1' || host . endsWith ( '.local' ) || host . endsWith ( '.lan' )) return true ; 73const m = / ^ ( \d + ) \. ( \d + ) \. ( \d + ) \. ( \d + ) $ / . exec ( host ); 74if ( ! m ) return false ; 75const [ a , b ] = [ Number ( m [ 1 ]), Number ( m [ 2 ])]; 76return a === 127 || a === 10 || ( a === 192 && b === 168 ) || ( a === 172 && b >= 16 && b <= 31 ) || ( a === 169 && b === 254 ) || ( a === 100 && b >= 64 && b <= 127 ); 77} 78 79const HOP = new Set ([ 'host' , 'connection' , 'content-length' , 'transfer-encoding' , 'keep-alive' , 'upgrade' , 'proxy-connection' ]); 80 81/** 82* The forwarding endpoint. `targetOf(key)` gives the real base address of a shaped route (or null), `samplingNow()` the Expert fields that 83* differ from the defaults right now. Called for `/api/internal/agent-llm/<key>/<path>`; this computer's own address only. 84*/ 85export function createLlmProxy ({ targetOf, samplingNow}) { 86return function handle ( req , res , key , rest ) { 87const remote = req . socket ?. remoteAddress ?? '' ; 88if ( ! /^ ( ::1 | 127\. | ::ffff:127\. ) / . test ( remote )) { res . writeHead ( 403 , { 'content-type' :'application/json' }); res . end ( JSON . stringify ({ error :'This endpoint is for the assistant on this computer only.' })); return ; } 89const base = targetOf ( key ); 90if ( ! base ) { res . writeHead ( 404 , { 'content-type' :'application/json' }); res . end ( JSON . stringify ({ error :'Unknown model route.' })); return ; } 91const chunks = []; 92req . on ( 'data' , c => chunks . push ( c )); 93req . on ( 'error' , () => res . destroy ()); 94req . on ( 'end' , () => { 95let body = Buffer . concat ( chunks ); 96const budget = nearestBudget ( req . headers [ 'x-strata-budget' ]); 97if ( req . method === 'POST' && / \/chat\/completions\/ ? $ / . test ( rest ) && body . length ) { 98try { body = Buffer . from ( JSON . stringify ( shapeBody ( JSON . parse ( body . toString ( 'utf8' )), { sampling :samplingNow (), budget}))); } catch { /* not JSON: pass it on untouched */ } 99} 100// The route's address is the model's own base (it ends in /v1): the assistant's /v1 is that same prefix. 101const target = new URL ( base . replace ( / \/ + $ / , '' ) + rest . replace ( / ^\/v1 (? = \/ | $ | \? ) / , '' )); 102const headers = {}; 103for ( const [ k , v ] of Object . entries ( req . headers )) if ( ! HOP . has ( k ) && ! k . startsWith ( 'x-strata-' )) headers [ k ] = v ; 104headers [ 'content-length' ] = String ( body . length ); 105const lib = target . protocol === 'https:' ?https :http ; 106const upstream = lib . request ( target , { method :req . method , headers}, reply => { 107const out = { ...reply . headers }; delete out [ 'transfer-encoding' ]; delete out . connection ; 108res . writeHead ( reply . statusCode ?? 502 , out ); 109reply . pipe ( res ); 110reply . on ( 'error' , () => res . destroy ()); 111}); 112upstream . on ( 'error' , e => { if ( ! res . headersSent ) { res . writeHead ( 502 , { 'content-type' :'application/json' }); res . end ( JSON . stringify ({ error :`The model server could not be reached: ${ e . message } ` })); } else res . destroy (); }); 113// The assistant stopped waiting (Stop): stop the model too. 114res . on ( 'close' , () => { if ( ! res . writableEnded ) upstream . destroy (); }); 115upstream . end ( body ); 116}); 117}; 118}