okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7b06ea51b
main
1// Response settings (thinking effort, thinking budget, Expert sampling) reach the agent's model request, and nothing changes while they are at their defaults. 2import test from 'node:test' ; 3import assert from 'node:assert/strict' ; 4import http from 'node:http' ; 5import { mkdtempSync , mkdirSync , rmSync } from 'node:fs' ; 6import { tmpdir } from 'node:os' ; 7import { join } from 'node:path' ; 8import { BUDGETS , createLlmProxy , isPrivateHost , nearestBudget , samplingFromExpert , shapeBody } from '../server/agent/llm-shape.mjs' ; 9import { buildProfile } from '../server/agent/profile.mjs' ; 10import { createVisionProbe } from '../server/vision-probe.mjs' ; 11import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 12import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 13import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 14 15const HARNESS = process . env . STRATA_HARNESS_DIR ; 16const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 17 18test ( 'only the Expert settings that differ from their defaults are sent; the thinking budget only while thinking is on' , () => { 19assert . equal ( samplingFromExpert ({}), null ); 20assert . equal ( samplingFromExpert ({ 'sample.temp' :0.6 , 'sample.topP' :0.95 , 'sample.topK' :40 , 'sample.repeat' :1.05 , 'sample.seed' :- 1 , 'sample.speedProjection' :true , 'sample.maxTokens' :0 }), null , 'all defaults: nothing' ); 21assert . deepEqual ( samplingFromExpert ({ 'sample.temp' :0.2 , 'sample.topK' :10 , 'sample.seed' :7 , 'sample.maxTokens' :500 , 'sample.speedProjection' :false }), 22{ temperature :0.2 , top_k :10 , seed :7 , max_tokens :500 , experimental_speed_projection :false }); 23const body = { model :'m' , messages :[], max_tokens :4096 , chat_template_kwargs :{ enable_thinking :true , reasoning_effort :'high' } }; 24assert . deepEqual ( shapeBody ( body , {}), body , 'no settings: the request is the same' ); 25const shaped = shapeBody ( body , { sampling :{ temperature :0.2 , max_tokens :500 }, budget :8192 }); 26assert . equal ( shaped . temperature , 0.2 ); assert . equal ( shaped . max_tokens , 500 , 'an output cap only lowers the request' ); assert . equal ( shaped . reasoning_budget_tokens , 8192 ); 27assert . equal ( shapeBody ({ ...body , max_tokens :100 }, { sampling :{ max_tokens :500 } }). max_tokens , 100 ); 28assert . equal ( shapeBody ({ ...body , temperature :1 }, { sampling :{ temperature :0.2 } }). temperature , 1 , 'a field the request already has wins' ); 29assert . equal ( shapeBody ({ ...body , chat_template_kwargs :{ enable_thinking :false } }, { budget :8192 }). reasoning_budget_tokens , undefined , 'thinking off: no budget' ); 30assert . deepEqual ( BUDGETS , [ 2048 , 8192 , 32768 ]); assert . equal ( nearestBudget ( 0 ), 0 ); assert . equal ( nearestBudget ( 5000 ), 2048 ); assert . equal ( nearestBudget ( 7000 ), 8192 ); assert . equal ( nearestBudget ( '32768' ), 32768 ); 31}); 32 33test ( 'only this computer and private networks are shaped, never a cloud address' , () => { 34for ( const ok of [ 'http://127.0.0.1:8080/v1' , 'http://localhost:11434/v1' , 'http://192.168.1.20:8080' , 'http://10.0.0.5/v1' , 'http://172.20.1.1/v1' , 'http://z440.local:8080' , 'http://[::1]:9/v1' ]) assert . equal ( isPrivateHost ( ok ), true , ok ); 35for ( const no of [ 'https://api.openai.com/v1' , 'http://8.8.8.8/v1' , 'http://172.32.0.1/v1' , 'http://example.com' , 'nonsense' ]) assert . equal ( isPrivateHost ( no ), false , no ); 36}); 37 38test ( 'the profile adds a response-settings copy of each shapeable route (local, or an OpenAI-style server on this network) and never of a cloud route' , () => { 39const profile = buildProfile ({ 40local :[{ id :'a' , modelId :'m' , baseUrl :'http://127.0.0.1:9001' , context :65536 }], 41connections :[ 42{ id :'lan' , name :'LAN' , baseUrl :'http://192.168.1.9:8080/v1' , protocol :'openai-chat' , apiKey :'' , models :[{ id :'x' }] }, 43{ id :'cloud' , name :'Cloud' , baseUrl :'https://api.deepseek.com' , protocol :'openai-chat' , apiKey :'k' , models :[{ id :'y' }] }, 44], 45proxyBase :'http://127.0.0.1:8791/api/internal/agent-llm' , 46}); 47const local = profile . routes . find ( r => r . kind === 'local' ); 48assert . deepEqual ( Object . keys ( local . shaped ), [ '0' , '2048' , '8192' , '32768' ]); 49assert . equal ( local . shaped [ 8192 ], 'strata-local~s8192' ); 50assert . deepEqual ( Object . keys ( profile . shapeTargets ). sort (), [ ...Object . values ( local . shaped ), ...Object . values ( profile . routes . find ( r => r . connectionId === 'lan' ). shaped )]. sort ()); 51assert . equal ( profile . shapeTargets [ 'strata-local~s0' ], 'http://127.0.0.1:9001' ); 52assert . equal ( profile . routes . find ( r => r . connectionId === 'cloud' ). shaped , undefined ); 53const doc = JSON . parse ( profile . patch . slice ( profile . patch . indexOf ( '[' ))); 54const providers = doc . find ( e => e . id === 'llm-pi-ai' ). config . providers ; 55assert . equal ( providers [ 'api-lan' ]. compat . thinkingFormat , 'chat-template' , 'a model server on this network gets the thinking vocabulary of a local model' ); 56assert . equal ( providers [ 'api-lan' ]. models [ 0 ]. reasoning , true ); 57assert . equal ( providers [ 'api-cloud' ]. compat , undefined , 'a cloud service does not' ); 58const small = buildProfile ({ local :[], connections :[{ id :'own' , name :'Own' , baseUrl :'http://127.0.0.1:18798/v1' , protocol :'openai-chat' , apiKey :'' , models :[{ id :'m' , contextMax :32768 }] }] }); 59const own = JSON . parse ( small . patch . slice ( small . patch . indexOf ( '[' ))). find ( e => e . id === 'llm-pi-ai' ). config . providers [ 'api-own' ]; 60assert . equal ( own . models [ 0 ]. maxTokens , 9830 , 'a server on this network keeps 30 percent of its window for the reply so long tasks can be compacted (it was 28672 of 32768: no room, no compaction)' ); 61assert . match ( profile . patch , / "baseURL": "http:\/\/127\.0\.0\.1:8791\/api\/internal\/agent-llm\/strata-local~s8192\/v1" / ); 62assert . match ( profile . patch , / "x-strata-budget": "8192" / ); 63assert . match ( profile . patch , / "provider": "strata-local~s8192" / , 'compaction keeps its timing on the copy too' ); 64const plain = buildProfile ({ local :[{ id :'a' , modelId :'m' , baseUrl :'http://127.0.0.1:9001' , context :65536 }], connections :[] }); 65assert . equal ( plain . routes [ 0 ]. shaped , undefined ); assert . ok ( ! /~s / . test ( plain . patch ), 'without a forwarding address nothing changes' ); 66}); 67 68test ( 'the forwarding endpoint adds the settings, streams the reply back and passes the key through' , async ( t ) => { 69const seen = []; 70const upstream = http . createServer (( req , res ) => { 71let raw = '' ; req . on ( 'data' , c => { raw += c ; }); req . on ( 'end' , () => { 72seen . push ({ url :req . url , auth :req . headers . authorization , internal :req . headers [ 'x-strata-budget' ], body :raw ?JSON . parse ( raw ) :null }); 73res . writeHead ( 200 , { 'content-type' :'text/event-stream' }); res . write ( 'data: one\n\n' ); setTimeout (() => { res . write ( 'data: two\n\n' ); res . end (); }, 30 ); 74}); 75}); 76await new Promise ( r => upstream . listen ( 0 , '127.0.0.1' , r )); 77let expert = null ; 78const proxy = createLlmProxy ({ targetOf :key => ( key === 'k1' ?`http://127.0.0.1: ${ upstream . address (). port } /v1` :null ), samplingNow :() => expert }); 79const front = http . createServer (( req , res ) => { const m = / ^\/api\/internal\/agent-llm\/ ([ ^ / ] + )( \/. * ) $ / . exec ( req . url ); proxy ( req , res , m [ 1 ], m [ 2 ]); }); 80await new Promise ( r => front . listen ( 0 , '127.0.0.1' , r )); 81t . after (() => { front . close (); upstream . close (); }); 82const call = ( key , headers = {}) => new Promise (( resolve , reject ) => { 83const r = http . request ({ host :'127.0.0.1' , port :front . address (). port , path :`/api/internal/agent-llm/ ${ key } /v1/chat/completions` , method :'POST' , headers :{ 'content-type' :'application/json' , authorization :'Bearer abc' , ...headers } }, res => { let t2 = '' ; res . on ( 'data' , c => { t2 += c ; }); res . on ( 'end' , () => resolve ({ status :res . statusCode , text :t2 })); }); 84r . on ( 'error' , reject ); r . end ( JSON . stringify ({ model :'m' , stream :true , messages :[], max_tokens :100 })); 85}); 86const a = await call ( 'k1' ); 87assert . equal ( a . status , 200 ); assert . match ( a . text , / one [ \s\S ] * two / ); 88assert . deepEqual ( seen [ 0 ]. body , { model :'m' , stream :true , messages :[], max_tokens :100 }, 'defaults: the body is untouched' ); assert . equal ( seen [ 0 ]. auth , 'Bearer abc' ); assert . equal ( seen [ 0 ]. url , '/v1/chat/completions' ); assert . equal ( seen [ 0 ]. internal , undefined , 'our own header is not forwarded' ); 89expert = { temperature :0.1 }; 90await call ( 'k1' , { 'x-strata-budget' :'8192' }); 91assert . equal ( seen [ 1 ]. body . temperature , 0.1 ); assert . equal ( seen [ 1 ]. body . reasoning_budget_tokens , 8192 ); 92assert . equal (( await call ( 'nope' )). status , 404 ); 93}); 94 95test ( 'a turn uses the response-settings route only when a setting is changed: the model receives the sampling and the budget; defaults go straight to the model' , { skip}, async ( t ) => { 96const worker = await startScriptedWorker ({}); 97const dir = mkdtempSync ( join ( tmpdir (), 'strata-shape-' )); 98const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 99let expert = null ; let front ; let bridge ; 100const proxy = createLlmProxy ({ targetOf :key => bridge . llmTarget ( key ), samplingNow :() => expert }); 101front = http . createServer (( req , res ) => { const m = / ^\/api\/internal\/agent-llm\/ ([ ^ / ] + )( \/. * ) $ / . exec ( req . url ); proxy ( req , res , m [ 1 ], m [ 2 ]); }); 102await new Promise ( r => front . listen ( 0 , '127.0.0.1' , r )); 103bridge = createAgentBridge ({ dataDir :dir , localInstances :() => [{ id :'i' , label :'S' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots :2 }], connections :() => [], env :process . env , startTimeoutMs :90_000 , 104proxyBase :`http://127.0.0.1: ${ front . address (). port } /api/internal/agent-llm` , expertSampling :() => expert }); 105t . after ( async () => { await bridge . close (); await worker . close (); front . close (); try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }); 106const run = ( chatId , extra = {}) => bridge . runTurn ({ chatId, message :'SCRIPT:echo hello' , workspacePath :ws , mode :'bypass' , onFrame :() => {}, ...extra }); 107const last = () => worker . requests . filter ( r => r . directive === 'echo' ). at ( - 1 ). params ; 108 109await run ( 's1' , { thinking :'High' }); 110assert . equal ( last (). temperature , undefined , 'defaults: no sampling sent' ); assert . equal ( last (). reasoning_budget_tokens , undefined ); 111assert . equal ( last (). chat_template_kwargs . reasoning_effort , 'high' , 'the reasoning level reaches the request' ); 112await run ( 's2' , { thinking :'Low' }); 113assert . equal ( last (). chat_template_kwargs . reasoning_effort , 'low' ); 114await run ( 's3' , { thinking :'Off' }); 115assert . equal ( last (). chat_template_kwargs . enable_thinking , false , 'Off turns thinking off' ); 116await run ( 's4' , { thinking :'High' , thinkingBudget :8192 }); 117assert . equal ( last (). reasoning_budget_tokens , 8192 , 'the composer budget reaches the request' ); 118assert . equal ( last (). chat_template_kwargs . reasoning_effort , 'high' ); 119await run ( 's5' , { thinking :'Off' , thinkingBudget :8192 }); 120assert . equal ( last (). reasoning_budget_tokens , undefined , 'a budget is not sent while thinking is off' ); 121expert = { temperature :0.2 , top_k :12 , seed :5 }; 122await run ( 's6' , { thinking :'Medium' }); 123assert . equal ( last (). temperature , 0.2 ); assert . equal ( last (). top_k , 12 ); assert . equal ( last (). seed , 5 ); assert . equal ( last (). reasoning_budget_tokens , undefined ); 124await run ( 's7' , { thinking :'Medium' , thinkingBudget :2048 }); 125assert . equal ( last (). temperature , 0.2 ); assert . equal ( last (). reasoning_budget_tokens , 2048 ); 126expert = null ; 127await run ( 's8' , { thinking :'Medium' }); 128assert . equal ( last (). temperature , undefined , 'back to defaults: straight to the model again' ); 129}); 130 131test ( 'a model server on this network gets picture input unless its own model list or the person says it does not read pictures' , async () => { 132const lists = { yes :{ data :[{ id :'m' , architecture :{ input_modalities :[ 'text' , 'image' ] } }] }, no :{ data :[{ id :'m' , architecture :{ input_modalities :[ 'text' ] } }] } }; 133let which = 'yes' ; 134const probe = createVisionProbe ({ fetcher :async () => ({ ok :true , json :async () => lists [ which ] }) }); 135const conn = { id :'c' , baseUrl :'http://127.0.0.1:1/v1' , apiKey :'' }; 136assert . equal ( probe . known ( conn , 'm' ), undefined ); 137assert . equal ( await probe . check ( conn , 'm' ), true ); assert . equal ( probe . known ( conn , 'm' ), true ); 138which = 'no' ; assert . equal ( await probe . check ( conn , 'm' ), true , 'cached for a few minutes' ); 139assert . equal ( await createVisionProbe ({ fetcher :async () => { throw new Error ( 'down' ); } }). check ( conn , 'm' ), null , 'unreachable is unknown: pictures stay on by default' ); 140const build = vision => JSON . parse ( buildProfile ({ local :[], connections :[{ id :'own' , name :'Own' , baseUrl :'http://127.0.0.1:18798/v1' , protocol :'openai-chat' , apiKey :'' , models :[{ id :'m' , contextMax :32768 , vision}] }] }). patch . slice ( buildProfile ({ local :[], connections :[] }). patch . indexOf ( '[' ))). find ( e => e . id === 'llm-pi-ai' ). config . providers [ 'api-own' ]. models [ 0 ]. input ; 141assert . deepEqual ( build ( true ), [ 'text' , 'image' ]); assert . deepEqual ( build ( false ), [ 'text' ]); assert . deepEqual ( build ( undefined ), [ 'text' , 'image' ], 'pictures are on by default' ); 142});