okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
19ea30f6a
main
1/** 2* Live status for a running turn: one small `status` frame that says what the assistant is doing right now. 3* 4* The page draws only the LATEST status, so a status must be replaced the moment it stops being true. This reporter therefore sends a 5* new frame on every change of phase or target (at most one per `gapMs`, the newest change wins), and between changes only repeats the 6* frame to refresh a counter (reasoning tokens, bytes written) every `beatMs`. It never sends the same words twice in a row. 7* 8* { type:'status', seq, phase, code, text, key?, values?, args?, tokens?, elapsedMs } 9* `key`/`values` (only when the sentence has a name or a number in it): the catalog template ("Writing {0}…") and its values, for translation. 10* 11* phases: starting waiting thinking answering preparing tool approval helpers goal idle (see notes-split-agent3.md) 12*/ 13 14/** Fill the `{0}` slots of a template (the catalog key of a sentence) with values. */ 15export const fillTemplate = ( key , values = []) => String ( key ). replace ( / \{ ( \d + ) \} / g , ( _ , i ) => String ( values [ Number ( i )] ?? '' )); 16 17/** 18* The sentence for a tool, in the person's words: what it is doing to what ("Writing pagoda.html…"), as a catalog template and its values 19* so the page can translate it: `{ key: 'Writing {0}…', values: ['pagoda.html'] }`. 20*/ 21export function toolStatus ( name , args = {}, { bytes= 0 } = {}) { 22const base = value => String ( value ?? '' ). split ( / [ \\ / ] / ). filter ( Boolean ). pop () ?? '' ; 23const file = base ( args . file_path ?? args . path ?? args . filePath ); 24const kb = bytes >= 1500 ?( bytes / 1024 ). toFixed ( bytes >= 10240 ?0 :1 ) :null ; 25const act = ( verb , noun ) => file 26 ?( kb ?{ key :` ${ verb } {0}… ({1} KB)` , values :[ file , kb ] } :{ key :` ${ verb } {0}…` , values :[ file ] }) 27 :( kb ?{ key :` ${ verb } ${ noun } … ({0} KB)` , values :[ kb ] } :{ key :` ${ verb } ${ noun } …` , values :[] }); 28switch ( name ) { 29case 'write' :return act ( 'Writing' , 'a file' ); 30case 'edit' :return act ( 'Changing' , 'a file' ); 31case 'read' :return file ?{ key :'Reading {0}…' , values :[ file ] } :{ key :'Reading a file…' , values :[] }; 32case 'read_image' :return { key :'Looking at a picture…' , values :[] }; 33case 'pwsh' :case 'bash' :return { key :'Running a command…' , values :[] }; 34case 'glob' :case 'grep' :return { key :'Searching your files…' , values :[] }; 35case 'web_search' :return { key :'Searching the web…' , values :[] }; 36case 'web_fetch' :{ let host = '' ; try { host = new URL ( args . url ). hostname ; } catch { /* partial address */ } return host ?{ key :'Opening {0}…' , values :[ host ] } :{ key :'Opening a web page…' , values :[] }; } 37case 'create_goal' :return { key :'Setting the goal…' , values :[] }; 38case 'update_goal' :return { key :'Updating the goal…' , values :[] }; 39case 'get_goal' :return { key :'Checking the goal…' , values :[] }; 40case 'todo_write' :return { key :'Updating its to-do list…' , values :[] }; 41case 'skill' :return { key :'Using a saved skill…' , values :[] }; 42case 'present' :return { key :'Showing you a result…' , values :[] }; 43case 'workflow' :return { key :'Running a multi-step plan…' , values :[] }; 44case 'job_list' :case 'job_output' :case 'job_kill' :return { key :'Checking background tasks…' , values :[] }; 45default : 46if ( name . startsWith ( 'mcp__browser__' )) return name . endsWith ( 'navigate' ) ?( args . url ?{ key :'Opening {0}…' , values :[ String ( args . url )] } :{ key :'Opening a page…' , values :[] }) :{ key :'Using the browser…' , values :[] }; 47if ( name . startsWith ( 'mcp__strata-instructions__' )) return { key :'Reading your instructions…' , values :[] }; 48if ( name . startsWith ( 'mcp__strata-commands__' )) return { key :'Running your tool…' , values :[] }; 49return { key :'Using a tool…' , values :[] }; 50} 51} 52 53/** The same, as one English sentence. */ 54export function toolStatusText ( name , args = {}, options = {}) { 55const s = toolStatus ( name , args , options ); 56return fillTemplate ( s . key , s . values ); 57} 58 59/** A status update (what the reporter takes) for a tool: text, catalog template and values together. */ 60export function toolUpdate ( phase , code , name , args , options , extra = {}) { 61const s = toolStatus ( name , args , options ); 62return { phase, code, text :fillTemplate ( s . key , s . values ), key :s . key , values :s . values , ...extra }; 63} 64 65const COUNTERS = new Set ([ 'tokens' , 'bytes' ]); 66const keyOf = u => ` ${ u . phase } | ${ u . code } | ${ JSON . stringify ( Object . fromEntries ( Object . entries ( u . args ?? {}). filter (([ k ]) => ! COUNTERS . has ( k ))))} ` ; 67 68export class StatusReporter { 69/** 70* @param { {emit: (frame: object) => void, now?: () => number, gapMs?: number, beatMs?: number, timers?: {set: Function, clear: Function}} } options 71*/ 72constructor ({ emit, now= Date . now , gapMs= 300 , beatMs= 2000 , timers= { set :setTimeout , clear :clearTimeout } }) { 73Object . assign ( this , { emitFrame :emit , now, gapMs, beatMs, timers}); 74this . seq = 0 ; 75this . current = null ; // what the page was last told 76this . wanted = null ; // the newest thing that is true now 77this . phaseStartedAt = 0 ; 78this . lastEmitAt = - Infinity ; 79this . timer = null ; 80this . closed = false ; 81} 82 83/** Say what is true now. `{phase, code, text, args?, tokens?}`. */ 84set ( update ) { 85if ( this . closed ) return ; 86const next = { ...update , args :update . args ?{ ...update . args } :undefined }; 87const changed = ! this . wanted || keyOf ( next ) !== keyOf ( this . wanted ); 88if ( changed ) this . phaseStartedAt = this . now (); 89this . wanted = next ; 90const sinceEmit = this . now () - this . lastEmitAt ; 91const due = changed ?this . gapMs :this . beatMs ; 92if ( ! this . current || sinceEmit >= due || update . phase === 'goal' ) this . #flush(); // a goal step is rare and the page should always hear it 93else if ( this . #differs()) this . #arm( due - sinceEmit ); 94} 95 96/** Nothing is happening any more: tell the page to drop the line. */ 97clear () { 98if ( this . closed ) return ; 99if ( this . current && this . current . phase !== 'idle' ) { this . wanted = { phase :'idle' , code :'idle' , text :'' }; this . #flush(); } 100this . dispose (); 101} 102 103dispose () { this . closed = true ; if ( this . timer ) this . timers . clear ( this . timer ); this . timer = null ; } 104 105 #differs() { 106const a = this . wanted , b = this . current ; 107return ! b || a . text !== b . text || a . tokens !== b . tokens ; 108} 109 110 #arm( ms ) { 111if ( this . timer || this . closed ) return ; 112this . timer = this . timers . set (() => { this . timer = null ; if ( ! this . closed && this . #differs()) this . #flush(); }, Math . max ( 0 , ms )); 113this . timer . unref ?.(); 114} 115 116 #flush() { 117if ( this . timer ) { this . timers . clear ( this . timer ); this . timer = null ; } 118const w = this . wanted ; 119if ( ! w || ( this . current && this . current . text === w . text && this . current . phase === w . phase && this . current . tokens === w . tokens )) return ; 120this . current = w ; 121this . lastEmitAt = this . now (); 122this . emitFrame ({ 123type :'status' , seq :++ this . seq , phase :w . phase , code :w . code , text :w . text , 124 ...( w . key && w . key !== w . text ?{ key :w . key , values :w . values ?? [] } :{}), 125 ...( w . args ?{ args :w . args } :{}), ...( w . tokens !== undefined ?{ tokens :w . tokens } :{}), 126elapsedMs :Math . max ( 0 , this . now () - this . phaseStartedAt ), 127}); 128} 129} 130 131/** Counts streamed tokens: one per chunk, or characters / 4 when a server batches many characters into a chunk. */ 132export class TokenCount { 133constructor () { this . chunks = 0 ; this . chars = 0 ; } 134add ( text ) { this . chunks += 1 ; this . chars += String ( text ). length ; } 135get tokens () { return this . chars / Math . max ( 1 , this . chunks ) < 8 ?this . chunks :Math . ceil ( this . chars / 4 ); } 136} 137 138export const fmtTokens = n => Number ( n ). toLocaleString ( 'en-US' ); 139 140/** 141* The same status line for a plain chat turn (no tools): the request is being read, the model is thinking (tokens), the model is writing. 142* Wraps the function that writes frames to the client; the returned function has `dispose()` for a client that left early. 143*/ 144export function withPlainStatus ( write , options = {}) { 145const reporter = new StatusReporter ({ emit :write , ...options }); 146const reasoning = new TokenCount (); 147reporter . set ({ phase :'starting' , code :'starting' , text :'Starting…' }); 148const frame = f => { 149switch ( f . type ) { 150case 'start' :reporter . set ({ phase :'waiting' , code :'reading-prompt' , text :'Reading your message…' }); break ; 151case 'reasoning' :reasoning . add ( f . text ?? '' ); reporter . set ({ phase :'thinking' , code :'thinking' , text :`Thinking… ${ fmtTokens ( reasoning . tokens )} tokens` , key :'Thinking… {0} tokens' , values :[ fmtTokens ( reasoning . tokens )], tokens :reasoning . tokens , args :{ tokens :reasoning . tokens } }); break ; 152case 'delta' :reporter . set ({ phase :'answering' , code :'answering' , text :'Writing the answer…' }); break ; 153case 'done' :case 'error' :reporter . clear (); break ; 154default :break ; 155} 156write ( f ); 157}; 158frame . dispose = () => reporter . dispose (); 159return frame ; 160}