okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
52ba0b781
main
1/** Live status of a running turn: the sentences, the throttling, and what the projector says as the model moves from thinking to writing a file. */ 2import test from 'node:test' ; 3import assert from 'node:assert/strict' ; 4import { StatusReporter , toolStatusText , TokenCount } from '../server/agent/status.mjs' ; 5import { TurnProjector } from '../server/agent/events.mjs' ; 6 7test ( 'a tool is described by what it does to what, in the person\'s words' , () => { 8assert . equal ( toolStatusText ( 'write' , { file_path :'C:\\work\\pagoda.html' }), 'Writing pagoda.html…' ); 9assert . equal ( toolStatusText ( 'write' , { file_path :'/a/b/pagoda.html' }, { bytes :12000 }), 'Writing pagoda.html… (12 KB)' ); 10assert . equal ( toolStatusText ( 'write' , {}), 'Writing a file…' ); 11assert . equal ( toolStatusText ( 'edit' , { path :'notes.md' }), 'Changing notes.md…' ); 12assert . equal ( toolStatusText ( 'pwsh' , { command :'Get-ChildItem' }), 'Running a command…' ); 13assert . equal ( toolStatusText ( 'web_search' , {}), 'Searching the web…' ); 14assert . equal ( toolStatusText ( 'update_goal' , {}), 'Updating the goal…' ); 15assert . equal ( toolStatusText ( 'web_fetch' , { url :'https://example.com/a' }), 'Opening example.com…' ); 16assert . equal ( toolStatusText ( 'mcp__browser__browser_navigate' , { url :'https://example.com' }), 'Opening https://example.com…' ); 17assert . equal ( toolStatusText ( 'mcp__strata-commands__x' , {}), 'Running your tool…' ); 18assert . equal ( toolStatusText ( 'mcp__other__thing' , {}), 'Using a tool…' ); 19}); 20 21function rig () { 22let clock = 1000 ; 23const timers = []; 24const frames = []; 25const reporter = new StatusReporter ({ 26emit :f => frames . push ( f ), now :() => clock , 27timers :{ set :( fn , ms ) => { const t = { fn, at :clock + ms , unref () {} }; timers . push ( t ); return t ; }, clear :t => { const i = timers . indexOf ( t ); if ( i >= 0 ) timers . splice ( i , 1 ); } }, 28}); 29const advance = ms => { clock += ms ; for ( const t of [ ...timers ]. sort (( a , b ) => a . at - b . at )) if ( t . at <= clock ) { timers . splice ( timers . indexOf ( t ), 1 ); t . fn (); } }; 30return { reporter, frames, advance, now :() => clock }; 31} 32 33test ( 'status: a change is sent at once, the same words are never sent twice, and a quick burst keeps only the newest' , () => { 34const { reporter, frames, advance} = rig (); 35reporter . set ({ phase :'starting' , code :'starting' , text :'Starting…' }); 36reporter . set ({ phase :'starting' , code :'starting' , text :'Starting…' }); 37assert . equal ( frames . length , 1 ); assert . deepEqual ([ frames [ 0 ]. type , frames [ 0 ]. seq , frames [ 0 ]. phase , frames [ 0 ]. text ], [ 'status' , 1 , 'starting' , 'Starting…' ]); 38advance ( 50 ); 39reporter . set ({ phase :'waiting' , code :'reading-prompt' , text :'Reading your message…' }); // 50 ms after the last: held 40reporter . set ({ phase :'preparing' , code :'preparing-tool' , text :'Writing a.html…' , args :{ tool :'write' , target :'a.html' , bytes :10 } }); 41assert . equal ( frames . length , 1 , 'held back, not dropped' ); 42advance ( 300 ); 43assert . equal ( frames . length , 2 ); assert . equal ( frames [ 1 ]. text , 'Writing a.html…' , 'the newest change wins; the one in between was never true for long enough to show' ); 44}); 45 46test ( 'status: a counter (reasoning tokens, bytes) is refreshed every 2 s, not on every chunk' , () => { 47const { reporter, frames, advance} = rig (); 48reporter . set ({ phase :'thinking' , code :'thinking' , text :'Thinking… 10 tokens' , tokens :10 , args :{ tokens :10 } }); 49for ( let i = 1 ; i <= 15 ; i ++ ) { advance ( 100 ); reporter . set ({ phase :'thinking' , code :'thinking' , text :`Thinking… ${ 10 + i * 10 } tokens` , tokens :10 + i * 10 , args :{ tokens :10 + i * 10 } }); } 50assert . ok ( frames . length <= 2 , `1.5 s of chunks made ${ frames . length } frames` ); 51advance ( 600 ); 52assert . equal ( frames . at ( - 1 ). tokens , 160 , 'the refresh carries the latest count' ); 53assert . ok ( frames . length <= 3 ); 54assert . ok ( frames . every ( f => f . phase === 'thinking' )); 55}); 56 57test ( 'status: clear says idle once and then nothing more is sent' , () => { 58const { reporter, frames, advance} = rig (); 59reporter . set ({ phase :'tool' , code :'tool' , text :'Running a command…' }); 60advance ( 400 ); 61reporter . clear (); 62assert . deepEqual ( frames . map ( f => f . phase ), [ 'tool' , 'idle' ]); 63reporter . set ({ phase :'tool' , code :'tool' , text :'x' }); advance ( 5000 ); 64assert . equal ( frames . length , 2 ); 65}); 66 67test ( 'projector: thinking counts tokens; composing a file call is "Writing pagoda.html…" while no text arrives; running, result and next step follow' , () => { 68const p = new TurnProjector (); 69const seen = []; 70p . onStatus = u => seen . push ( u ); 71const chunk = ( c , attemptId = 'a1' ) => p . consume ({ type :'assistant-stream' , frame :{ type :'chunk' , attemptId, chunk :c } }); 72for ( const t of [ 'Let ' , 'me ' , 'think ' , 'about ' , 'this' ]) chunk ({ type :'reasoning-delta' , text :t }); 73assert . deepEqual ([ seen . at ( - 1 ). phase , seen . at ( - 1 ). tokens , seen . at ( - 1 ). text ], [ 'thinking' , 5 , 'Thinking… 5 tokens' ]); 74chunk ({ type :'text-delta' , text :'I will build the pagoda HTML file now.' }); 75assert . equal ( seen . at ( - 1 ). phase , 'answering' ); 76chunk ({ type :'reasoning-delta' , text :'again' }, 'a2' ); 77assert . equal ( seen . at ( - 1 ). tokens , 1 , 'a new model request counts its own thinking from zero' ); 78chunk ({ type :'tool-call-delta' , index :0 , id :'call-1' , name :'write' , argumentsDelta :'{"file_path":"C:\\\\work\\\\pagoda.html","content":"<html>' }); 79assert . deepEqual ([ seen . at ( - 1 ). phase , seen . at ( - 1 ). code , seen . at ( - 1 ). text ], [ 'preparing' , 'preparing-tool' , 'Writing pagoda.html…' ], 'the stale sentence is replaced the moment the call starts' ); 80assert . equal ( seen . at ( - 1 ). args . target , 'C:\\work\\pagoda.html' ); 81chunk ({ type :'tool-call-delta' , index :0 , id :'call-1' , argumentsDelta :'x' . repeat ( 9000 ) }); 82assert . match ( seen . at ( - 1 ). text , / ^Writing pagoda\.html… \(\d + ( \.\d ) ? KB\)$ / ); 83p . consume ({ type :'event' , event :{ type :'tool/call' , time :1 , data :{ callId :'call-1' , name :'write' , arguments :JSON . stringify ({ file_path :'C:/work/pagoda.html' , content :'x' }) } } }); 84assert . deepEqual ([ seen . at ( - 1 ). phase , seen . at ( - 1 ). text ], [ 'tool' , 'Writing pagoda.html…' ]); 85p . consume ({ type :'event' , event :{ type :'tool/result' , time :2 , data :{ message :{ toolCallId :'call-1' , content :[{ type :'text' , text :'ok' }] } } } }); 86assert . deepEqual ([ seen . at ( - 1 ). phase , seen . at ( - 1 ). code ], [ 'waiting' , 'model-working' ]); 87}); 88 89test ( 'projector: a tool that asks shows "waiting for your answer", and a helper call is not announced as a tool' , () => { 90const p = new TurnProjector (); 91const seen = []; 92p . onStatus = u => seen . push ( u ); 93p . consume ({ type :'event' , event :{ type :'tool/call' , time :1 , data :{ callId :'c1' , name :'pwsh' , arguments :JSON . stringify ({ command :'rm x' }) } } }); 94p . consume ({ type :'event' , event :{ type :'approval/asked' , time :2 , data :{ id :'ap1' , callId :'c1' , reason :'Run a command' } } }); 95assert . deepEqual ([ seen . at ( - 1 ). phase , seen . at ( - 1 ). text ], [ 'approval' , 'Waiting for your answer…' ]); 96p . consume ({ type :'event' , event :{ type :'approval/decided' , time :3 , data :{ id :'ap1' , outcome :'allowed-once' } } }); 97assert . equal ( seen . at ( - 1 ). phase , 'tool' , 'back to the running tool after the answer' ); 98const before = seen . length ; 99p . consume ({ type :'assistant-stream' , frame :{ type :'chunk' , attemptId :'a' , chunk :{ type :'tool-call-delta' , index :0 , id :'h1' , name :'subagent' , argumentsDelta :'{"prompt":"x"}' } } }); 100assert . equal ( seen . length , before , 'helpers have their own status' ); 101}); 102 103test ( 'token count: one per chunk, or characters / 4 when the server batches' , () => { 104const a = new TokenCount (); for ( const t of [ 'a' , 'b' , 'c' ]) a . add ( t ); assert . equal ( a . tokens , 3 ); 105const b = new TokenCount (); b . add ( 'x' . repeat ( 400 )); assert . equal ( b . tokens , 100 ); 106}); 107 108test ( 'plain chat says what it is doing too: reading the message, thinking with a token count, writing, then the line is cleared before done' , async () => { 109const { withPlainStatus} = await import ( '../server/agent/status.mjs' ); 110let clock = 1000 ; const written = []; 111const frame = withPlainStatus ( f => written . push ( f ), { now :() => clock , timers :{ set :() => ({ unref () {} }), clear () {} } }); 112const feed = f => { clock += 2100 ; frame ( f ); }; 113feed ({ type :'start' , demo :false }); 114for ( const t of [ 'a' , 'b' , 'c' ]) feed ({ type :'reasoning' , text :t }); 115feed ({ type :'delta' , text :'Hello' }); 116feed ({ type :'done' , tokensOut :4 }); 117const phases = written . filter ( f => f . type === 'status' ). map ( f => f . phase ); 118assert . deepEqual ( phases . filter (( p , i , a ) => a [ i - 1 ] !== p ), [ 'starting' , 'waiting' , 'thinking' , 'answering' , 'idle' ]); 119const think = written . filter ( f => f . type === 'status' && f . phase === 'thinking' ). at ( - 1 ); 120assert . equal ( think . tokens , 3 ); assert . equal ( think . text , 'Thinking… 3 tokens' ); 121assert . equal ( written . at ( - 1 ). type , 'done' ); 122assert . equal ( written . at ( - 2 ). phase , 'idle' ); 123frame . dispose (); 124}); 125 126// ------------------------------------------------------------------------------------------------- real Harness 127 128import { existsSync , mkdtempSync , mkdirSync , rmSync } from 'node:fs' ; 129import { tmpdir } from 'node:os' ; 130import { join } from 'node:path' ; 131import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 132import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 133import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 134 135const skip = ! process . env . STRATA_HARNESS_DIR || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 136 137test ( 'real Harness: a turn that writes a file says what it is doing, in order, and ends with the status cleared before done' , { skip}, async ( t ) => { 138const worker = await startScriptedWorker ({}); 139const dir = mkdtempSync ( join ( tmpdir (), 'strata-status-' )); 140const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 141const local = [{ id :'inst-1' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots :2 }]; 142const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => [], env :process . env , startTimeoutMs :90_000 }); 143t . after ( async () => { await bridge . close (); await worker . close (); try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }); 144const frames = []; 145await bridge . runTurn ({ chatId :'s1' , message :`SCRIPT:call write ${ JSON . stringify ({ file_path : join ( ws , 'pagoda.html' ), content : '<html></html>' })} ` , workspacePath :ws , mode :'bypass' , onFrame :f => frames . push ( f ) }); 146const statuses = frames . filter ( f => f . type === 'status' ); 147assert . ok ( statuses . length >= 2 , 'statuses were sent' ); 148assert . equal ( statuses [ 0 ]. phase , 'starting' ); 149assert . deepEqual ( statuses . map ( s => s . seq ), statuses . map (( _ , i ) => i + 1 ), 'sequence numbers count up' ); 150assert . equal ( statuses . at ( - 1 ). phase , 'idle' ); 151assert . ok ( frames . indexOf ( statuses . at ( - 1 )) < frames . findIndex ( f => f . type === 'done' ), 'cleared before done' ); 152assert . ok ( existsSync ( join ( ws , 'pagoda.html' ))); 153}); 154 155test ( 'a sentence with a name or a number also carries its catalog template and values, and every status sentence is in the catalog in every language' , async () => { 156const { readFileSync} = await import ( 'node:fs' ); 157const 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' ))])); 158const idOf = text => Object . entries ( catalog . en ). find (([, v ]) => v === text )?.[ 0 ]; 159const p = new TurnProjector (); const seen = []; p . onStatus = u => seen . push ( u ); 160p . consume ({ type :'assistant-stream' , frame :{ type :'chunk' , attemptId :'a' , chunk :{ type :'tool-call-delta' , index :0 , id :'c' , name :'write' , argumentsDelta :'{"file_path":"/w/pagoda.html","content":"' + 'x' . repeat ( 4000 ) } } }); 161assert . deepEqual ([ seen . at ( - 1 ). key , seen . at ( - 1 ). values ], [ 'Writing {0}… ({1} KB)' , [ 'pagoda.html' , '3.9' ]]); 162assert . equal ( seen . at ( - 1 ). text , 'Writing pagoda.html… (3.9 KB)' ); 163const keys = [ 'Starting the assistant…' , 'Starting…' , 'Reading your message…' , 'Working out the next step…' , 'Thinking… {0} tokens' , 'Writing the answer…' , 'Waiting for your answer…' , 'Helpers are working ({0})…' , 'Working on the goal…' , 164'Writing {0}…' , 'Writing a file…' , 'Writing {0}… ({1} KB)' , 'Writing a file… ({0} KB)' , 'Changing {0}…' , 'Changing a file…' , 'Reading {0}…' , 'Reading a file…' , 'Running a command…' , 'Searching your files…' , 'Searching the web…' , 165'Opening {0}…' , 'Opening a web page…' , 'Using the browser…' , 'Setting the goal…' , 'Updating the goal…' , 'Checking the goal…' , 'Using a tool…' , 'Reading your files…' , 'Trying an improved version…' , 'Checking the result…' , 'Comparing the two versions…' ]; 166for ( const key of keys ) { const id = idOf ( key ); assert . ok ( id , ` ${ key } is in the catalog` ); for ( const l of [ 'de' , 'es' , 'fr' , 'ja' , 'ko' , 'pt' , 'ru' , 'zh' ]) { assert . ok ( catalog [ l ][ id ]?. trim (), ` ${ l } : ${ key } ` ); assert . deepEqual (( catalog [ l ][ id ]. match ( / \{\d\} / g ) ?? []). sort (), ( key . match ( / \{\d\} / g ) ?? []). sort (), ` ${ l } keeps the slots of ${ key } ` ); } } 167}); 168 169test ( 'a goal step is always sent, even right after another status (it used to be swallowed by the 300 ms gap, which made a test flaky)' , () => { 170const { reporter, frames, advance} = rig (); 171reporter . set ({ phase :'waiting' , code :'reading-prompt' , text :'Reading your message…' }); 172advance ( 20 ); 173reporter . set ({ phase :'goal' , code :'goal-step' , text :'Working on the goal…' , args :{ round :1 , max :3 } }); 174advance ( 10 ); 175reporter . set ({ phase :'thinking' , code :'thinking' , text :'Thinking… 1 tokens' , tokens :1 }); 176advance ( 400 ); 177assert . ok ( frames . some ( f => f . phase === 'goal' && f . args . round === 1 ), frames . map ( f => f . phase ). join ( ',' )); 178}); 179 180import { plainTurnFailure } from '../server/agent/agent-bridge.mjs' ; 181test ( 'a start failure from the agent reads in plain words and keeps the raw text for Details' , () => { 182const raw = new Error ( 'session/create: tool-bash (@deepseek-ai/dsh-tool-bash): waiting for shell\ntool-workflow: waiting for workflowEngine' ); 183raw . code = 'agent-preset/invalid' ; 184const f = plainTurnFailure ( raw ); 185assert . doesNotMatch ( f . message , / session\/create | waiting for | @deepseek-ai | workflowEngine / ); 186assert . match ( f . message , / reinstall | reopen / i ); 187assert . match ( f . details , / waiting for workflowEngine / ); 188assert . doesNotMatch ( plainTurnFailure ( new Error ( 'turn/start: boom' )). message , / turn\/start / ); 189}); 190 191import { createSessionWhenReady , AgentUnavailable } from '../server/agent/agent-bridge.mjs' ; 192test ( 'first chat on a fresh start waits for the Harness plugins instead of failing' , async () => { 193let calls = 0 ; let waits = 0 ; 194const create = async () => { 195calls ++ ; 196if ( calls < 3 ) throw new Error ( 'session/create: tool-bash (@deepseek-ai/dsh-tool-bash): waiting for shell\ntool-workflow: waiting for workflowEngine' ); 197return { sessionId :'s1' }; 198}; 199const r = await createSessionWhenReady ( create , { readyMs :5000 , retryMs :5 , onWait :() => { waits ++ ; } }); 200assert . deepEqual ( r , { sessionId :'s1' }); 201assert . equal ( calls , 3 ); 202assert . equal ( waits , 2 , 'the page is told twice that the assistant is starting' ); 203}); 204test ( 'a start that never finishes gives the plain message with the raw text for Details' , async () => { 205const raw = 'session/create: tool-bash: waiting for shell' ; 206let clock = 0 ; 207await assert . rejects ( 208createSessionWhenReady ( async () => { throw new Error ( raw ); }, { readyMs :100 , retryMs :1 , now :() => ( clock += 60 ) }), 209e => { 210assert . ok ( e instanceof AgentUnavailable ); 211const f = plainTurnFailure ( e ); 212assert . equal ( f . message , 'The assistant could not start. Try again in a moment.' ); 213assert . equal ( f . details , raw ); 214assert . equal ( f . code , 'AGENT_NOT_READY' ); 215return true ; 216}); 217}); 218test ( 'other session errors are not retried, and Stop while waiting ends the wait' , async () => { 219let calls = 0 ; 220await assert . rejects ( createSessionWhenReady ( async () => { calls ++ ; throw new Error ( 'session/create: disk full' ); }, { retryMs :1 }), / disk full / ); 221assert . equal ( calls , 1 ); 222const r = await createSessionWhenReady ( async () => { throw new Error ( 'x: waiting for shell' ); }, { retryMs :1 , cancelled :() => true }); 223assert . equal ( r , null ); 224});