okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
788e0b731
main
1/** 2* Drive the host over HTTP (no browser) against a real model and print what the page would receive. 3* 4* STRATA_URL=http://127.0.0.1:8899 node scripts/agent3-http.mjs <command> [args] 5* 6* connect <baseUrl> <modelId> save an API connection to a model server (once per STRATA_HOME) 7* stream "<message>" [mode] one chat turn; prints every frame compactly with its time (status, goal, tools, deltas counted) 8* goal "<objective>" /goal run, then the goal bar calls: state, pause, edit, clear, resume 9* timeskip "<request>" [stopAfterS] a Time-skip job; polls status (phase + activity); with stopAfterS, presses Stop that many seconds in 10* 11* Environment: STRATA_URL (required), CHAT (chat id, default a fresh one), WORKSPACE_ID. 12*/ 13const BASE = process . env . STRATA_URL ; 14if ( ! BASE ) { console . error ( 'STRATA_URL is required' ); process . exit ( 2 ); } 15const [ command , ...rest ] = process . argv . slice ( 2 ); 16const t0 = Date . now (); 17const stamp = () => ` ${ String ( Math . round (( Date . now () - t0 ) / 1000 )). padStart ( 4 )} s` ; 18const j = async ( path , body , method = body ?'POST' :'GET' ) => { 19const res = await fetch ( BASE + path , { method, headers :{ 'content-type' :'application/json' }, ...( body ?{ body :JSON . stringify ( body ) } :{}) }); 20const text = await res . text (); 21let data ; try { data = JSON . parse ( text ); } catch { data = { raw :text }; } 22if ( ! res . ok ) throw new Error ( ` ${ path } -> ${ res . status } ${ data . error ?? text . slice ( 0 , 200 )} ` ); 23return data ; 24}; 25const sleep = ms => new Promise ( r => setTimeout ( r , ms )); 26 27async function model () { 28const providers = await j ( '/api/model-providers' ); 29const c = providers . connections . at ( - 1 ); 30if ( ! c ) throw new Error ( 'no API connection saved: run "connect" first' ); 31return { connectionId :c . id , modelId :c . models [ 0 ]. id }; 32} 33 34/** One chat stream; returns the frames. `print` shows a compact line per frame, deltas and reasoning as counters. */ 35async function stream ( body , { quiet= false , path= '/api/chat/stream' , onFrame= null } = {}) { 36const res = await fetch ( BASE + path , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ( body ) }); 37if ( ! res . ok ) throw new Error ( `stream -> ${ res . status } ${ await res . text ()} ` ); 38const frames = []; let buffer = '' , text = 0 , reasoning = 0 , lastLine = '' ; 39const flushCounters = () => { if ( text || reasoning ) { console . log ( ` ${ stamp ()} ... ${ reasoning } reasoning chars, ${ text } answer chars` ); text = 0 ; reasoning = 0 ; } }; 40const reader = res . body . getReader (); const dec = new TextDecoder (); 41for (;;) { 42const { value, done} = await reader . read (); 43if ( value ) { 44buffer += dec . decode ( value , { stream :true }); 45const lines = buffer . split ( '\n' ); buffer = lines . pop () ?? '' ; 46for ( const line of lines . filter ( Boolean )) { 47const f = JSON . parse ( line ); f . _at = Date . now (); frames . push ( f ); 48try { onFrame ?.( f ); } catch ( e ) { console . log ( 'onFrame error' , e . message ); } 49if ( f . type === 'delta' ) { text += ( f . text ?? '' ). length ; continue ; } 50if ( f . type === 'reasoning' ) { reasoning += ( f . text ?? '' ). length ; continue ; } 51if ( f . type === 'stats' ) continue ; 52flushCounters (); 53let out = f . type ; 54if ( f . type === 'status' ) out = `status[ ${ f . seq } ] ${ f . phase } / ${ f . code } : ${ f . text } ${ f . tokens !== undefined ? ` (tokens ${ f . tokens } )` : '' } + ${ f . elapsedMs } ms` ; 55else if ( f . type === 'goal' ) out = `goal ${ JSON . stringify ( f . goal )} ` ; 56else if ( f . type === 'agent-tool' ) { 57out = `tool ${ f . tool . state } ${ f . tool . verb } ${ f . tool . target ?? '' } ${ f . tool . state === 'proposed' ? ` [asks: ${ f . tool . effect } ]` : '' } ` ; 58// ANSWER=approve|deny answers every card that asks (the card is the real Approve/Deny card of Manual mode) 59if ( f . tool . state === 'proposed' && process . env . ANSWER ) void j ( '/api/chat/approval' , { sessionId :body . sessionId , toolId :f . tool . id , decision :process . env . APPROVE_MATCH && new RegExp ( process . env . APPROVE_MATCH , 'i' ). test ( ` ${ f . tool . target } ${ f . tool . effect } ` ) ?'approve' :process . env . ANSWER }). then (() => console . log ( ` ${ stamp ()} -> ${ process . env . ANSWER } ${ f . tool . id } ` ), e => console . log ( ` ${ stamp ()} answer failed: ${ e . message } ` )); 60} 61else if ( f . type === 'plan' ) out = `PLAN ${ f . event } ${ f . plan . state } " ${ f . plan . title } " steps= ${ f . plan . steps . map ( x => x . state [ 0 ] + ':' + x . text . slice ( 0 , 40 )). join ( ' | ' )} ` ; 62else if ( f . type === 'plan-step' ) out = `PLAN-STEP ${ f . line } ${ f . summary ? ' | summary: ' + f . summary : '' } ` ; 63else if ( f . type === 'queued-message' ) out = `QUEUED-MESSAGE ${ f . state } " ${ f . message . text . slice ( 0 , 50 )} " deliverAt= ${ f . message . deliverAt } ${ f . afterStep ? ' afterStep=' + f . afterStep : '' } queue= ${ f . queue . length } ` ; 64else if ( f . type === 'queued-release' ) out = `QUEUED-RELEASE ${ f . messages . map ( m => m . text . slice ( 0 , 40 )). join ( ' | ' )} ` ; 65else if ( f . type === 'research' ) out = `RESEARCH sources= ${ f . sources . map ( x => x . n + ':' + x . url ). join ( ' ' )} ` ; 66else if ( f . type === 'done' ) out = `done ${ f . finishReason } tokensOut= ${ f . tokensOut } ` ; 67else if ( f . type === 'error' ) out = `ERROR ${ f . message } ` ; 68if ( ! quiet && out !== lastLine ) console . log ( ` ${ stamp ()} ${ out } ` ); 69lastLine = out ; 70} 71} 72if ( done ) break ; 73} 74flushCounters (); 75if ( process . env . SHOWTEXT && ! quiet ) console . log ([ '---- answer text ----' , frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ), '---- end ----' ]. join ( String . fromCharCode ( 10 ))); 76return frames ; 77} 78 79if ( command === 'connect' ) { 80const [ baseUrl , modelId ] = rest ; 81await j ( '/api/model-providers' , { kind :'custom' , name :'Cloud model' , baseUrl, protocol :'openai-chat' , apiKey :'' , models :[{ id :modelId , name :'Test model' , ...( process . env . CTX ?{ contextMax :Number ( process . env . CTX ) } :{}), ...( process . env . MAXOUT ?{ maxOutput :Number ( process . env . MAXOUT ) } :{}) }] }); 82console . log ( 'saved' ); 83} else if ( command === 'stream' ) { 84const [ message , mode = 'bypass' ] = rest ; 85const chat = process . env . CHAT ?? `c- ${ Date . now ()} ` ; 86await stream ({ sessionId :chat , message, mode, remoteModel :await model (), workspaceId :process . env . WORKSPACE_ID , ...( process . env . PLAIN ?{ agent :false } :{}), ...( process . env . THINK ?{ thinking :process . env . THINK } :{}) }); 87} else if ( command === 'skill' ) { 88// create a skill through the Skills page route: skill "Name" "description" "instructions" 89const [ name , description , instructions ] = rest ; 90const out = await j ( '/api/skills' , { name, description, body :instructions }); 91console . log ( 'saved' , out . id , '| skills now:' , out . skills . map ( s => ` ${ s . id } ( ${ s . source } )` ). join ( ', ' )); 92} else if ( command === 'goal' ) { 93const [ objective ] = rest ; 94const chat = process . env . CHAT ?? `g- ${ Date . now ()} ` ; 95const common = { sessionId :chat , mode :'bypass' , remoteModel :await model () }; 96console . log ( ` ${ stamp ()} -- /goal run` ); 97const frames = await stream ({ ...common , message :`/goal ${ objective } ` }); 98const last = frames . filter ( f => f . type === 'goal' ). at ( - 1 ); 99console . log ( ` ${ stamp ()} -- goal bar: state` , JSON . stringify (( await j ( `/api/goal?chatId= ${ chat } ` )). goal )); 100console . log ( ` ${ stamp ()} -- pause` , JSON . stringify ( await j ( '/api/goal/pause' , { chatId :chat }))); 101console . log ( ` ${ stamp ()} -- edit` , JSON . stringify ( await j ( '/api/goal/edit' , { chatId :chat , text :` ${ objective } (edited)` }))); 102console . log ( ` ${ stamp ()} -- resume (stream)` ); 103await stream ({ ...common , goalAction :'resume' }); 104console . log ( ` ${ stamp ()} -- clear` , JSON . stringify ( await j ( '/api/goal/clear' , { chatId :chat }))); 105console . log ( ` ${ stamp ()} -- state after clear` , JSON . stringify ( await j ( `/api/goal?chatId= ${ chat } ` ))); 106void last ; 107} else if ( command === 'goalbar' ) { 108// Pause from the goal bar while a round runs, then resume through the chat stream. 109const [ objective , pauseAfter = '6' ] = rest ; 110const chat = process . env . CHAT ?? `gb- ${ Date . now ()} ` ; 111const common = { sessionId :chat , mode :'bypass' , remoteModel :await model () }; 112const running = stream ({ ...common , message :`/goal ${ objective } ` }); 113await sleep ( Number ( pauseAfter ) * 1000 ); 114console . log ( ` ${ stamp ()} -- pause from the bar` , JSON . stringify ( await j ( '/api/goal/pause' , { chatId :chat }))); 115await running ; 116console . log ( ` ${ stamp ()} -- state after the run` , JSON . stringify (( await j ( `/api/goal?chatId= ${ chat } ` )). goal )); 117console . log ( ` ${ stamp ()} -- resume (stream, no message)` ); 118await stream ({ ...common , goalAction :'resume' }); 119console . log ( ` ${ stamp ()} -- state after resume` , JSON . stringify (( await j ( `/api/goal?chatId= ${ chat } ` )). goal )); 120console . log ( ` ${ stamp ()} -- remove` , JSON . stringify ( await j ( '/api/goal/clear' , { chatId :chat }))); 121} else if ( command === 'timeskip' ) { 122const [ request , stopAfter ] = rest ; 123const chat = process . env . CHAT ?? `t- ${ Date . now ()} ` ; 124const started = await j ( '/api/timeskip/start' , { prompt :request , sessionId :chat , attempts :1 , workspaceId :process . env . WORKSPACE_ID , remoteModel :await model () }); 125const id = started . run . id ; 126console . log ( ` ${ stamp ()} started ${ id } activity= ${ JSON . stringify ( started . run . activity )} ` ); 127let last = '' , stopped = false ; 128for (;;) { 129const { run} = await j ( `/api/timeskip/status?id= ${ id } ` ); 130const line = ` ${ run . phase } ${ run . activity ? ` | ${ run . activity . text } ${ run . activity . args ?. step && typeof run . activity . args . step === 'string' ? ` | assistant: ${ run . activity . args . step } ` : '' } ` : '' } ${ run . lever ? ` | lever: step ${ run . lever . step } / ${ run . lever . total } ${ run . lever . defaulted ? '(default) ' : '' } - ${ run . lever . why } ` : '' } ${ run . a ?. line ? ` | A: ${ run . a . state } ${ run . a . line . slice ( 0 , 50 )} ` : '' } ${ run . b ?. state ? ` | B: ${ run . b . state } ${( run . b . line ?? '' ). slice ( 0 , 50 )} ` : '' } ` ; 131if ( line !== last ) { console . log ( ` ${ stamp ()} ${ line } ` ); last = line ; } 132if ( stopAfter && ! stopped && ( Date . now () - t0 ) / 1000 >= Number ( stopAfter )) { 133console . log ( ` ${ stamp ()} -- pressing Stop (the chat Stop route)` ); 134console . log ( ` ${ stamp ()} ` , JSON . stringify ( await j ( '/api/chat/stop' , { sessionId :chat }))); 135stopped = true ; 136} 137if ([ 'completed' , 'cancelled' , 'failed' , 'interrupted' ]. includes ( run . phase )) { 138console . log ( ` ${ stamp ()} END ${ run . phase } ${ run . error ? ` error= ${ run . error } ` : '' } needsReview= ${ run . needsUserReview } ` ); 139try { const files = await j ( `/api/timeskip/files?id= ${ id } ` ); console . log ( ` ${ stamp ()} files: ${ files . files . map ( f => ` ${ f . status } ${ f . path } ` ). join ( ', ' ) || '(none)' } ` ); } catch ( e ) { console . log ( ` ${ stamp ()} files: ${ e . message } ` ); } 140break ; 141} 142await sleep ( 4000 ); 143} 144} else if ( command === 'plan' ) { 145// /plan <task>, then (unless STOP_AT_PLAN) Start as goal with an optional queued message: plan "<task>" ["<queued message>"] 146const [ task , queued ] = rest ; 147const chat = process . env . CHAT ?? `pl- ${ Date . now ()} ` ; 148const common = { sessionId :chat , mode :process . env . MODE ?? 'manual' , remoteModel :await model (), workspaceId :process . env . WORKSPACE_ID }; 149console . log ( ` ${ stamp ()} -- /plan` ); 150const frames = await stream ({ ...common , message :`/plan ${ task } ` }); 151const plan = frames . find ( f => f . type === 'plan' )?. plan ; 152if ( ! plan ) { console . log ( 'NO PLAN FRAME (the reply stays plain text)' ); process . exit ( 1 ); } 153console . log ( JSON . stringify ( plan . steps . map ( x => x . text ))); 154console . log ( ` ${ stamp ()} -- GET /api/plan` , ( await j ( `/api/plan?sessionId= ${ chat } ` )). plan ?. state ); 155if ( process . env . EDIT_LAST ) { const steps = plan . steps . map ( x => x . text ); steps . push ( process . env . EDIT_LAST ); console . log ( ` ${ stamp ()} -- edit` , ( await j ( '/api/plan/edit' , { sessionId :chat , planId :plan . id , steps})). plan . steps . length , 'steps' ); } 156if ( process . env . STOP_AT_PLAN ) { console . log ( ` ${ stamp ()} -- ${ process . env . STOP_AT_PLAN } ` , JSON . stringify (( await j ( '/api/plan/' + process . env . STOP_AT_PLAN , { sessionId :chat , planId :plan . id })). plan . state )); process . exit ( 0 ); } 157console . log ( ` ${ stamp ()} -- start as goal` ); 158let sent = false ; 159const run = stream ({ ...common , planId :plan . id }, { path :'/api/plan/start-goal' , onFrame :f => { 160if ( queued && ! sent && f . type === 'plan-step' && f . state === 'running' ) { sent = true ; setTimeout ( async () => { try { console . log ( ` ${ stamp ()} -- queue` , JSON . stringify (( await j ( '/api/chat/queue' , { sessionId :chat , message :queued })). message )); } catch ( e ) { console . log ( 'queue failed' , e . message ); } }, Number ( process . env . QUEUE_AFTER ?? 8 ) * 1000 ); } 161} }); 162await run ; 163console . log ( ` ${ stamp ()} -- final plan` , JSON . stringify (( await j ( `/api/plan?sessionId= ${ chat } ` )). plan ?. steps . map ( x => x . state + ':' + x . text . slice ( 0 , 30 )))); 164} else if ( command === 'modeswitch' ) { 165// Manual run that needs several approvals; after the first card the chat is switched to Bypass: no further card may ask. 166const [ message ] = rest ; 167const chat = process . env . CHAT ?? `ms- ${ Date . now ()} ` ; 168const common = { sessionId :chat , mode :'manual' , remoteModel :await model (), workspaceId :process . env . WORKSPACE_ID }; 169let asked = 0 , switched = false ; 170const frames = await stream ({ ...common , message}, { onFrame :async f => { 171if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) { 172asked ++ ; 173if ( ! switched ) { switched = true ; console . log ( ` ${ stamp ()} -- switching to Bypass` , JSON . stringify ( await j ( '/api/chat/mode' , { sessionId :chat , mode :'bypass' }))); } 174} 175} }); 176const done = frames . filter ( f => f . type === 'agent-tool' && f . tool . state === 'done' ). length ; 177console . log ( ` ${ stamp ()} RESULT cards that asked= ${ asked } (expected 1), tools done= ${ done } ` ); 178} else if ( command === 'long' ) { 179// Fill the context with long pastes so the Harness has to compact, then ask about the first one: long <rounds> <chars> 180const [ rounds = '6' , chars = '16000' ] = rest ; 181const chat = process . env . CHAT ?? `lg- ${ Date . now ()} ` ; 182const common = { sessionId :chat , mode :'bypass' , remoteModel :await model (), workspaceId :process . env . WORKSPACE_ID }; 183const filler = n => Array . from ({ length :Math . ceil ( Number ( chars ) / 60 ) }, ( _ , i ) => `Entry ${ n } - ${ i } : the quick brown fox number ${ i * 7 + n } jumps over the lazy dog.` ). join ( '\n' ); 184let frames = await stream ({ ...common , message :'Remember this code word for later: PAGODA-7731. Reply with just OK.' }, { quiet :true }); 185console . log ( ` ${ stamp ()} round 0 done, ctx= ${ frames . at ( - 1 ). contextTokens ?? "?" } ` ); 186for ( let n = 1 ; n <= Number ( rounds ); n ++ ) { 187frames = await stream ({ ...common , message :`Here is log chunk ${ n } . Reply with just the word OK. 188 189${ filler ( n )} ` }, { quiet :true }); 190const d = frames . at ( - 1 ); 191console . log ( ` ${ stamp ()} round ${ n } ${ d . type } ${ d . finishReason ?? d . message ?? "" } tokensIn= ${ d . tokensIn } ctx= ${ d . contextTokens ?? d . context ?? "?" } ` ); 192} 193frames = await stream ({ ...common , message :'What was the code word I asked you to remember at the very start? Answer with the code word only.' }, { quiet :true }); 194console . log ( ` ${ stamp ()} ANSWER: ${ frames . filter ( f => f . type === "delta" ). map ( f => f . text ). join ( "" ). trim (). slice ( 0 , 120 )} ` ); 195} else if ( command === 'effort' ) { 196// The same question at each reasoning level (and optional thinking budget): what really changes is the thinking the model did. 197const [ question = 'What is 17 times 23, and is the result divisible by 3? Explain briefly.' , budget = '0' ] = rest ; 198const rows = []; 199for ( const level of ( process . env . LEVELS ?process . env . LEVELS . split ( ',' ) :[ 'Off' , 'Low' , 'Medium' , 'High' , 'Max' ])) { 200const t = Date . now (); 201const frames = await stream ({ sessionId :`ef- ${ level } - ${ Date . now ()} ` , message :question , mode :'bypass' , remoteModel :await model (), thinking :level , thinkingBudget :Number ( budget ), agent :process . env . PLAIN ?false :undefined }, { quiet :true }); 202const reasoning = frames . filter ( x => x . type === 'reasoning' ). map ( x => x . text ?? '' ). join ( '' ). length ; 203const answer = frames . filter ( x => x . type === 'delta' ). map ( x => x . text ?? '' ). join ( '' ); 204const done = frames . at ( - 1 ); 205rows . push ({ level, budget :Number ( budget ), reasoningChars :reasoning , answerChars :answer . length , tokensOut :done . tokensOut , seconds :Math . round (( Date . now () - t ) / 1000 ), answer :answer . replace ( / \s +/ g , ' ' ). slice ( 0 , 90 ) }); 206console . log ( JSON . stringify ( rows . at ( - 1 ))); 207} 208} else if ( command === 'sampling' ) { 209// Set Expert sampling through the engine settings route (as the Response settings dialog does), then ask for a random word a few times. 210const [ temp = '0' , seed = '1' , n = '3' ] = rest ; 211const before = await j ( '/api/engine' ); 212const set = async values => j ( '/api/engine' , { expert :Object . entries ( values ). map (([ id , value ]) => ({ id, value})) }, 'PATCH' ); 213await set ({ 'sample.temp' :Number ( temp ), 'sample.seed' :Number ( seed ) }); 214const words = []; 215for ( let i = 0 ; i < Number ( n ); i ++ ) { 216const frames = await stream ({ sessionId :`sm- ${ Date . now ()} - ${ i } ` , message :'Reply with one random everyday English word and nothing else.' , mode :'bypass' , remoteModel :await model (), thinking :'Off' }, { quiet :true }); 217words . push ( frames . filter ( x => x . type === 'delta' ). map ( x => x . text ?? '' ). join ( '' ). trim (). slice ( 0 , 30 )); 218} 219console . log ( JSON . stringify ({ temp :Number ( temp ), seed :Number ( seed ), words})); 220await set ({ 'sample.temp' :0.6 , 'sample.seed' :- 1 }); 221} else { 222console . error ( 'commands: connect | stream | goal | timeskip | plan | modeswitch | long | effort | sampling' ); process . exit ( 2 ); 223}