okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
52ba0b781
main
1/** Pure parts of the agent bridge: profile generation, environment scrubbing, event projection. No Harness needed. */ 2import test from 'node:test' ; 3import assert from 'node:assert/strict' ; 4import { buildProfile , outputBudget , routeFor , ASSUMED_API_CONTEXT } from '../server/agent/profile.mjs' ; 5import { agentEnvironment , redact } from '../server/agent/harness-runtime.mjs' ; 6import { TurnProjector , presentTool , toolScope , toolVerb , friendlyFailure } from '../server/agent/events.mjs' ; 7import { withEarlierConversation } from '../server/agent/agent-bridge.mjs' ; 8 9const local = [{ id :'inst-1' , label :'Qwen' , baseUrl :'http://127.0.0.1:8095/v1' , modelId :'qwen' , context :32768 , key :'local-secret-key-1' }]; 10const conn = { id :'c0nn-1234-abcd' , name :'Cloud' , baseUrl :'https://api.example.com/v1' , protocol :'openai-chat' , apiKey :'sk-live-ABCDEFGH' , models :[{ id :'m1' , name :'M1' , contextMax :64000 }, { id :'m2' , name :'M2' , contextMax :null }] }; 11 12test ( 'the generated profile names credentials, never carries them, and declares only what exists' , () => { 13const p = buildProfile ({ local, connections :[ conn ] }); 14assert . ok ( ! p . patch . includes ( 'sk-live-ABCDEFGH' ) && ! p . patch . includes ( 'local-secret-key-1' )); 15assert . match ( p . patch , / apiKeyEnv / ); 16assert . deepEqual ( Object . values ( p . env ). sort (), [ 'local-secret-key-1' , 'sk-live-ABCDEFGH' ]); 17const entries = JSON . parse ( p . patch . replace ( / ^#. * \n / , '' )); 18const providers = entries . find ( e => e . id === 'llm-pi-ai' ). config . providers ; 19assert . deepEqual ( Object . keys ( providers ). sort (), [ 'api-c0nn-1234-ab' , 'strata-local' ]); 20assert . equal ( providers [ 'strata-local' ]. models [ 0 ]. contextWindow , 32768 ); 21assert . equal ( providers [ 'strata-local' ]. models [ 0 ]. maxTokens , 9830 , 'a local model gets 30 percent of its window for a reply (it was 8192, which cut big answers off) and the rest stays for the conversation, so the Harness can compact it' ); 22assert . equal ( providers [ 'strata-local' ]. models [ 0 ]. reasoning , true ); 23assert . equal ( providers [ 'strata-local' ]. compat . thinkingFormat , 'chat-template' ); 24assert . equal ( providers [ 'api-c0nn-1234-ab' ]. models [ 1 ]. contextWindow , ASSUMED_API_CONTEXT , 'an unknown API window is a stated assumption, not a catalog default' ); 25assert . equal ( entries . find ( e => e . id === 'agent-default-model' ). config . provider , 'strata-local' , 'local stays the default' ); 26assert . equal ( entries . find ( e => e . id === 'session-title-llm' ). disabled , true ); 27}); 28 29test ( 'no local model means no default model, so nothing can quietly fall to a cloud route' , () => { 30const p = buildProfile ({ local :[], connections :[ conn ] }); 31assert . equal ( p . defaultRoute , null ); 32assert . ok ( ! JSON . parse ( p . patch . replace ( / ^#. * \n / , '' )). some ( e => e . id === 'agent-default-model' )); 33assert . equal ( routeFor ( p , null ), null ); 34}); 35 36test ( 'a route fingerprint changes when its key or address changes, and only then' , () => { 37const a = buildProfile ({ local, connections :[ conn ] }); 38const b = buildProfile ({ local, connections :[{ ...conn , apiKey :'sk-live-OTHER-KEY' }] }); 39const c = buildProfile ({ local :[{ ...local [ 0 ], context :16384 }], connections :[ conn ] }); 40const fp = ( p , kind ) => p . routes . find ( r => r . kind === kind ). fp ; 41assert . notEqual ( fp ( a , 'api' ), fp ( b , 'api' )); 42assert . equal ( fp ( a , 'local' ), fp ( b , 'local' )); 43assert . notEqual ( fp ( a , 'local' ), fp ( c , 'local' )); 44assert . equal ( fp ( a , 'api' ), fp ( c , 'api' )); 45}); 46 47test ( 'routeFor picks the chat\'s own choice' , () => { 48const p = buildProfile ({ local, connections :[ conn ] }); 49assert . equal ( routeFor ( p , { connectionId :conn . id , modelId :'m2' }). modelId , 'm2' ); 50assert . equal ( routeFor ( p , { instanceId :'inst-1' }). route , 'strata-local' ); 51assert . equal ( routeFor ( p , { connectionId :'gone' , modelId :'m1' }), null ); 52assert . equal ( outputBudget ( 2048 ), 1536 , 'a small window keeps a quarter for the prompt' ); 53assert . equal ( outputBudget ( 1_000_000 ), 32768 , 'a big window with no known maximum gets a generous 32K, not 8K' ); 54assert . equal ( outputBudget ( 128_000 ), 32768 ); assert . equal ( outputBudget ( null ), 32768 ); 55assert . equal ( outputBudget ( 16_384 ), 16_384 - 4096 , 'never more than the window minus room for the prompt' ); 56assert . equal ( outputBudget ( 200_000 , 64_000 ), 64_000 , 'the connection own maximum is used when known' ); 57assert . equal ( outputBudget ( 8192 , 64_000 ), 8192 - 2048 , 'a known maximum is still bounded by the window' ); 58assert . equal ( outputBudget ( 200_000 , 4096 ), 4096 , 'a small known maximum is respected' ); 59}); 60 61test ( 'the agent environment keeps what a shell needs and drops ambient credentials' , () => { 62const env = agentEnvironment ({ PATH :'/bin' , HOME :'/h' , OPENAI_API_KEY :'x' , GITHUB_TOKEN :'y' , AWS_SECRET_ACCESS_KEY :'z' , SSH_AUTH_SOCK :'s' , SystemRoot :'C:\\Windows' }, { STRATA_API_KEY_X :'k' }); 63assert . deepEqual ( Object . keys ( env ). sort (), [ 'DSH_PERMISSION_MODE' , 'DSH_TELEMETRY_DISABLED' , 'HOME' , 'NODE_USE_SYSTEM_CA' , 'PATH' , 'STRATA_API_KEY_X' , 'SystemRoot' ]); 64}); 65 66test ( 'redact removes secret values and launch tokens from log text' , () => { 67const out = redact ( 'GET /?token=abcDEF_123-x failed with key sk-live-ABCDEFGH' , [ 'sk-live-ABCDEFGH' ]); 68assert . ok ( ! out . includes ( 'sk-live-ABCDEFGH' ) && ! out . includes ( 'abcDEF_123-x' )); 69}); 70 71const ev = ( type , data , seq = 1 , time = 1000 ) => ({ type :'event' , event :{ type, seq, time, data} }); 72const chunk = c => ({ type :'assistant-stream' , frame :{ type :'chunk' , attemptId :'a:1' , chunk :c } }); 73 74test ( 'a tool call walks running -> proposed -> done with its approval, and carries its result' , () => { 75const p = new TurnProjector ({ startedAt :0 }); 76const call = p . consume ( ev ( 'tool/call' , { callId :'c1' , name :'pwsh' , arguments :JSON . stringify ({ command :'ls' , description :'List files' }) }, 1 , 1000 )); 77assert . equal ( call [ 0 ]. tool . state , 'running' ); assert . equal ( call [ 0 ]. tool . scope , 'shell' ); assert . equal ( call [ 0 ]. tool . preview , 'ls' ); 78const asked = p . consume ( ev ( 'approval/asked' , { id :'ap1' , callId :'c1' , reason :'escalate sandbox' })); 79assert . equal ( asked [ 0 ]. tool . state , 'proposed' ); assert . match ( asked [ 0 ]. tool . effect , / escalate / ); 80const decided = p . consume ( ev ( 'approval/decided' , { id :'ap1' , outcome :'allowed-once' })); 81assert . equal ( decided [ 0 ]. tool . state , 'running' ); 82const done = p . consume ( ev ( 'tool/result' , { message :{ toolCallId :'c1' , content :[{ type :'text' , text :'ok' }] } }, 3 , 1500 )); 83assert . equal ( done [ 0 ]. tool . state , 'done' ); assert . equal ( done [ 0 ]. tool . result , 'ok' ); assert . equal ( done [ 0 ]. tool . durationMs , 500 ); 84}); 85 86test ( 'a rejected approval ends as denied even though the Harness returns an error result' , () => { 87const p = new TurnProjector ({ startedAt :0 }); 88p . consume ( ev ( 'tool/call' , { callId :'c2' , name :'pwsh' , arguments :'{}' })); 89p . consume ( ev ( 'approval/asked' , { id :'ap2' , callId :'c2' })); 90assert . equal ( p . consume ( ev ( 'approval/decided' , { id :'ap2' , outcome :'rejected' }))[ 0 ]. tool . state , 'denied' ); 91const res = p . consume ( ev ( 'tool/result' , { message :{ toolCallId :'c2' , isError :true , content :[{ type :'text' , text :'the user rejected tool' }] } })); 92assert . equal ( res [ 0 ]. tool . state , 'denied' ); 93}); 94 95test ( 'live frames become deltas, usage is summed across steps, the turn ends with one terminal frame' , () => { 96const p = new TurnProjector ({ startedAt :0 }); 97assert . deepEqual ( p . consume ( chunk ({ type :'text-delta' , index :0 , text :'Hi' })), [{ type :'delta' , text :'Hi' }]); 98assert . deepEqual ( p . consume ( chunk ({ type :'reasoning-delta' , index :0 , text :'hmm' })), [{ type :'reasoning' , text :'hmm' }]); 99p . consume ( chunk ({ type :'usage' , usage :{ inputTokens :100 , outputTokens :5 } })); 100p . consume ( chunk ({ type :'usage' , usage :{ inputTokens :120 , outputTokens :7 } })); 101p . consume ( ev ( 'turn/end' , { turn :1 , reason :{ kind :'completed' } })); 102const [ done ] = p . finish ({ model :'M' , contextMax :1000 }); 103assert . equal ( done . type , 'done' ); assert . equal ( done . tokensIn , 220 ); assert . equal ( done . tokensOut , 12 ); assert . equal ( done . usageSource , 'reported' ); 104}); 105 106test ( 'every turn-end reason maps to a frame the chat knows' , () => { 107const finish = reason => { const p = new TurnProjector (); p . ended = reason ; return p . finish ()[ 0 ]; }; 108assert . equal ( finish ({ kind :'aborted' , reason :{ kind :'user' } }). cancelled , true ); 109assert . equal ( finish ({ kind :'max-tokens' }). finishReason , 'length' ); 110assert . equal ( finish ({ kind :'error' , error :{ code :'X' , message :'context window exceeded' } }). type , 'error' ); 111assert . match ( finish ({ kind :'error' , error :{ message :'request exceeds the context window' } }). message , / no longer fits / ); 112assert . equal ( finish ({ kind :'blocked' }). code , 'BLOCKED' ); 113assert . equal ( finish ( null ). code , 'INTERRUPTED' ); 114assert . equal ( finish ({ kind :'completed' }). usageSource , 'unavailable' , 'no usage reported means unavailable, not zero' ); 115}); 116 117test ( 'a text the live frames missed is completed from the committed message, once' , () => { 118const p = new TurnProjector (); 119p . consume ( chunk ({ type :'text-delta' , index :0 , text :'Hel' })); 120const out = p . consume ( ev ( 'assistant/message' , { message :{ content :[{ type :'text' , text :'Hello there' }] } })); 121assert . deepEqual ( out , [{ type :'delta' , text :'lo there' }]); 122assert . deepEqual ( p . consume ( ev ( 'assistant/message' , { message :{ content :[{ type :'text' , text :'Hello there' }] } })), []); 123}); 124 125test ( 'tool scopes and previews' , () => { 126assert . equal ( toolScope ( 'write' ), 'write' ); assert . equal ( toolScope ( 'grep' ), 'read' ); assert . equal ( toolScope ( 'web_fetch' ), 'connected' ); 127assert . equal ( presentTool ({ callId :'x' , name :'write' , args :{ file_path :'a.txt' } }). preview , 'a.txt' ); 128assert . equal ( friendlyFailure ({ message :'No API key' }), 'The model rejected the credentials. Check the connection in Settings.' ); 129}); 130 131test ( 'a chat that existed before the agent carries a bounded summary into its first agent turn' , () => { 132const history = Array . from ({ length :30 }, ( _ , i ) => ({ role :i % 2 ?'assistant' :'user' , content :`m ${ i } ` . padEnd ( 2000 , 'x' ) })); 133const prompt = withEarlierConversation ( history , 'NOW' ); 134assert . match ( prompt , / Current message:\nNOW$ / ); 135assert . ok ( prompt . length < 12 * 1600 + 200 , 'bounded' ); 136assert . equal ( withEarlierConversation ([], 'NOW' ), 'NOW' ); 137}); 138 139test ( 'the browser and the person\'s own tools have plain sentences, translated in every language' , async () => { 140const { readFileSync} = await import ( 'node:fs' ); 141const catalog = Object . fromEntries ([ 'en' , 'de' , 'es' , 'fr' , 'ja' , 'ko' , 'pt' , 'ru' , 'zh' ]. map ( l => [ l , JSON . parse ( readFileSync ( new URL ( `../src/locales/ ${ l } .json` , import . meta. url ), 'utf8' ))])); 142const idOf = text => Object . entries ( catalog . en ). find (([, v ]) => v === text )?.[ 0 ]; 143const cases = [ 144[ 'mcp__browser__browser_navigate' , 'Opening a page in the browser' , 'Opened a page in the browser' , "Couldn't open the page" ], 145[ 'mcp__browser__browser_click' , 'Clicking on the page' , 'Clicked on the page' , "Couldn't click on the page" ], 146[ 'mcp__browser__browser_type' , 'Typing on the page' , 'Typed on the page' , "Couldn't type on the page" ], 147[ 'mcp__browser__browser_snapshot' , 'Looking at the page' , 'Looked at the page' , "Couldn't look at the page" ], 148[ 'mcp__browser__browser_evaluate' , 'Running a small program on the page' , 'Ran a small program on the page' , "Couldn't run the program on the page" ], 149[ 'mcp__browser__browser_wait_for' , 'Waiting for the page' , 'Waited for the page' , "Couldn't wait for the page" ], 150[ 'mcp__browser__browser_navigate_back' , 'Going back a page' , 'Went back a page' , "Couldn't go back" ], 151[ 'mcp__browser__browser_tabs' , 'Managing browser tabs' , 'Managed browser tabs' , "Couldn't manage the browser tabs" ], 152[ 'mcp__browser__browser_close' , 'Closing the browser page' , 'Closed the browser page' , "Couldn't close the browser page" ], 153[ 'mcp__browser__browser_something_new' , 'Using the browser' , 'Used the browser' , 'The browser step failed' ], 154[ 'mcp__strata-instructions__house_style' , 'Reading your instructions' , 'Read your instructions' , "Couldn't read your instructions" ], 155[ 'mcp__strata-commands__check_site' , 'Running your tool' , 'Ran your tool' , 'Your tool failed' ], 156[ 'mcp__github__create_issue' , 'Using a tool' , 'Used a tool' , 'The tool failed' ], 157]; 158for ( const [ name , running , done , failed ] of cases ) { 159assert . equal ( toolVerb ( name , 'running' ), running , name ); assert . equal ( toolVerb ( name , 'done' ), done , name ); assert . equal ( toolVerb ( name , 'error' ), failed , name ); 160for ( const text of [ running , done , failed ]) { const id = idOf ( text ); assert . ok ( id , ` ${ text } is in the catalog` ); for ( const l of [ 'de' , 'es' , 'fr' , 'ja' , 'ko' , 'pt' , 'ru' , 'zh' ]) assert . ok ( catalog [ l ][ id ]?. trim (), ` ${ l } : ${ text } ` ); } 161} 162const nav = presentTool ({ callId :'c1' , name :'mcp__browser__browser_navigate' , args :{ url :'https://example.com' } }); 163assert . equal ( nav . target , 'https://example.com' ); assert . equal ( nav . verb , 'Opening a page in the browser' ); 164const own = presentTool ({ callId :'c2' , name :'mcp__strata-commands__check_site' , args :{} }); 165assert . equal ( own . target , 'check site' ); 166assert . equal ( presentTool ({ callId :'c3' , name :'mcp__github__create_issue' , args :{} }). target , 'mcp__github__create_issue' , 'an unknown connected tool keeps its name' ); 167assert . equal ( presentTool ({ callId :'c4' , name :'mcp__browser__browser_snapshot' , args :{} }). preview , '' , 'no empty braces on a card' ); 168assert . equal ( presentTool ({ callId :'c5' , name :'mcp__browser__browser_evaluate' , args :{ function :'() => document.title' } }). preview , '' , 'a script in the page is not shown as code on the card' ); 169}); 170 171test ( 'an API model\'s route gets a generous answer room, or the connection\'s own maximum when the provider listed one' , () => { 172const profile = buildProfile ({ local :[], connections :[{ id :'c1' , name :'C' , baseUrl :'https://x/v1' , protocol :'openai-chat' , apiKey :'k' , models :[ 173{ id :'unknown' , contextMax :null }, { id :'big' , contextMax :200_000 , maxOutput :64_000 }, { id :'small' , contextMax :16_384 }] }] }); 174const providers = JSON . parse ( profile . patch . split ( '\n' ). slice ( 1 ). join ( '\n' )). find ( e => e . id === 'llm-pi-ai' ). config . providers ; 175const models = Object . values ( providers )[ 0 ]. models ; 176const by = Object . fromEntries ( models . map ( m => [ m . id , m . maxTokens ])); 177assert . equal ( by . unknown , 32768 ); assert . equal ( by . big , 64_000 ); assert . equal ( by . small , 16_384 - 4096 ); 178});