okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1/** 2* A scripted OpenAI-compatible chat-completions worker, for the agent-bridge tests. 3* 4* It stands in for the Strata API worker so that the Harness agent loop, the tool executor, the 5* approval gate and the host bridge are all real while the model is scripted. A scripted model proves 6* the integration path, not model quality; the real-model run is a separate step. 7* 8* Script selection is by a directive in the last user message (`SCRIPT:<name> <args>`), never by 9* request count: the Harness makes requests a script author does not plan for (a session title, a 10* re-ask after a tool result), and a counter would shift every later reply. 11* 12* SCRIPT:hello reasoning then a short text reply 13* SCRIPT:slow [n] n (default 400) text chunks, 40 ms apart: a window for Stop 14* SCRIPT:tool <file> <text> one shell call that appends <text> to <file>; it asks the sandbox for 15* wider access, so the approval gate is exercised 16* SCRIPT:plain <file> <text> the same call without the escalation (no approval needed) 17* SCRIPT:echo <text> replies with <text> 18* SCRIPT:ask one ask_user_question call (the agent asking the person something) 19* SCRIPT:envdump <file> one shell call that writes the shell's environment to <file> 20* SCRIPT:retrywrite <file> <text> the `write` tool, like a careful model: when the sandbox denies it and offers 21* an escalation, retry once with `sandbox_permissions: workspace-write` 22* SCRIPT:retryshell <file> <text> the same with the shell tool (an in-workspace append) 23* SCRIPT:read <file> the `read` tool on <file> 24* SCRIPT:spawn <n> <script...> n `subagent` calls in one reply; each child's prompt is SCRIPT:<script...>. When a child's 25* completion notice wakes the parent, it answers with a short text quoting the notice. 26* SCRIPT:goalstep one goal round: get_goal, then update_goal complete, then a short closing text 27* SCRIPT:planreply a reply ending with a numbered plan of three steps (each step's text carries SCRIPT:goalstep) 28* SCRIPT:call <tool> <json> one call to any tool with the given JSON arguments 29* SCRIPT:multi <json> {"calls":[[tool,args],...],"say":"final text"}: all the calls in one reply, then the text once their results are in 30* SCRIPT:searchloop a model that never stops: every reply rewrites a numbered plan and calls web_search again with a new query 31* SCRIPT:bloat <prompt tokens> a reply that is only thinking (no answer text), with usage reporting that many prompt tokens (a context at 100%) 32* 33* A request whose last message is a tool result is answered with a text that quotes the result. 34*/ 35import { createServer } from 'node:http' ; 36import { createHash } from 'node:crypto' ; 37 38const delay = ms => new Promise ( r => setTimeout ( r , ms )); 39 40export async function startScriptedWorker ({ port= 0 , chunkDelayMs= 40 , model= 'scripted-model' , serial= false , window= 0 , charsPerToken= 0 , noCount= false } = {}) { 41// `window` + `charsPerToken` make it behave like the engine: every request's prompt is counted (its size over charsPerToken), the usage it 42// reports is that count, and a prompt that leaves no room to answer is refused with the engine's own 400 ("requests are never truncated"). 43// `serial` stands in for an engine with one request slot: the next request waits until the one before it has finished. 44let tail = Promise . resolve (); 45const turn = () => { let release ; const mine = new Promise ( r => { release = r ; }); const wait = tail ; tail = tail . then (() => mine ); return wait . then (() => release ); }; 46const requests = []; 47const counts = []; 48let aborted = 0 ; 49const server = createServer ( async ( req , res ) => { 50const url = new URL ( req . url , 'http://x' ); 51const json = ( code , body ) => { res . writeHead ( code , { 'content-type' :'application/json' }); res . end ( JSON . stringify ( body )); }; 52if ( req . method === 'GET' && url . pathname === '/health' ) return json ( 200 , { ok :true }); 53if ( req . method === 'GET' && url . pathname === '/v1/models' ) return json ( 200 , { object :'list' , data :[{ id :model , object :'model' }] }); 54if ( req . method === 'GET' && url . pathname === '/__requests' ) return json ( 200 , { requests, aborted}); 55// The engine's own token count of a message (Anthropic style): characters over the density, plus the template's few tokens. 56if ( req . method === 'POST' && url . pathname . endsWith ( '/messages/count_tokens' )) { 57if ( noCount ) return json ( 404 , { error :'no count here' }); // an older engine: the message cannot be counted before it is sent 58let text = '' ; 59for await ( const c of req ) text += c ; 60const sent = JSON . parse ( text ); 61const chars = ( sent . messages ?? []). reduce (( n , m ) => n + ( typeof m . content === 'string' ?m . content . length :JSON . stringify ( m . content ). length ), 0 ); 62counts . push ( chars ); 63return json ( 200 , { input_tokens :Math . ceil ( chars / ( charsPerToken || 4 )) + 12 }); 64} 65if ( req . method !== 'POST' || ! url . pathname . endsWith ( '/chat/completions' )) return json ( 404 , { error :'no route' }); 66const release = serial ?await turn () :() => {}; 67res . on ( 'close' , release ); 68let raw = '' ; 69for await ( const c of req ) raw += c ; 70const body = JSON . parse ( raw ); 71const messages = body . messages ?? []; 72const last = messages [ messages . length - 1 ] ?? {}; 73const text = m => typeof m ?. content === 'string' ?m . content :Array . isArray ( m ?. content ) ?m . content . map ( p => p . text ?? '' ). join ( ' ' ) :'' ; 74// The Harness appends runtime-context messages after the prompt, so the newest user message is not 75// the prompt: take the newest one that carries a directive. 76const directive = [ ...messages ]. reverse (). filter ( m => m . role === 'user' ) 77. map ( m => / SCRIPT: ( \w + )([ ^ \n ] * ) / . exec ( text ( m ))). find ( Boolean ); 78requests . push ({ 79at :Date . now (), model :body . model , stream :body . stream === true , 80toolNames :( body . tools ?? []). map ( t => t . function ?. name ), 81// everything the client sent besides the conversation (sampling, limits, stream options) 82params :Object . fromEntries ( Object . entries ( body ). filter (([ k ]) => ! [ 'messages' , 'tools' , 'model' ]. includes ( k ))), 83lastRole :last . role , directive :directive ?.[ 1 ] ?? null , messageCount :messages . length , 84authorization :req . headers . authorization ?'present' :'absent' , 85authSha :req . headers . authorization ?createHash ( 'sha256' ). update ( req . headers . authorization ). digest ( 'hex' ) :null , 86promptChars :raw . length , raw, 87}); 88const counted = charsPerToken > 0 ?Math . ceil ( raw . length / charsPerToken ) :0 ; 89if ( window > 0 && counted > 0 && counted > window - 64 ) { 90requests . at ( - 1 ). refused = counted ; 91return json ( 400 , { error :{ type :'invalid_request_error' , message :`request exceeds the context window: prompt ( ${ counted } tokens) leaves no room to answer in the context ( ${ window } ); requests are never truncated` } }); 92} 93const shellName = () => ( body . tools ?? []). find ( t => [ 'bash' , 'pwsh' ]. includes ( t . function ?. name ))?. function ?. name ?? 'bash' ; 94const shellCommand = ( file , value ) => ( shellName () === 'pwsh' ?`Add-Content -Path ' ${ file } ' -Value ' ${ value } '` :`echo ${ value } >> ${ file } ` ); 95let closed = false ; 96res . on ( 'close' , () => { if ( ! res . writableEnded ) { closed = true ; aborted ++ ; } }); 97 98res . writeHead ( 200 , { 'content-type' :'text/event-stream' , 'cache-control' :'no-cache' }); 99const id = `chatcmpl- ${ requests . length } ` ; 100const send = ( delta , finish = null , extra = {}) => res . write ( `data: ${ JSON . stringify ({ id , object : 'chat.completion.chunk' , created : 0 , model : body . model , choices : [{ index : 0 , delta , finish_reason : finish }], ... extra })} \n\n` ); 101let promptTokens = counted || 100 + messages . length ; 102const finish = ( reason , tokens = 10 ) => { 103send ({}, reason ); 104res . write ( `data: ${ JSON . stringify ({ id , object : 'chat.completion.chunk' , created : 0 , model : body . model , choices : [], usage : { prompt_tokens : promptTokens , completion_tokens : tokens , total_tokens : promptTokens + tokens } })} \n\n` ); 105res . write ( 'data: [DONE]\n\n' ); res . end (); 106}; 107const toolCall = async ( name , call ) => { 108send ({ role :'assistant' , content :'' , reasoning_content :`I will use ${ name } .` }); 109await delay ( chunkDelayMs ); 110const argsJson = JSON . stringify ( call ); 111send ({ tool_calls :[{ index :0 , id :`call_ ${ requests . length } ` , type :'function' , function :{ name, arguments :'' } }] }); 112for ( let i = 0 ; i < argsJson . length ; i += 17 ) { send ({ tool_calls :[{ index :0 , function :{ arguments :argsJson . slice ( i , i + 17 ) } }] }); await delay ( 5 ); } 113return finish ( 'tool_calls' , 30 ); 114}; 115const say = async ( parts , tokens ) => { 116send ({ role :'assistant' , content :'' }); 117for ( const p of parts ) { if ( closed ) return ; send ({ content :p }); await delay ( chunkDelayMs ); } 118if ( ! closed ) finish ( 'stop' , tokens ?? parts . length ); 119}; 120 121// A model that read "[sandbox: escalation available ...]" retries the exact call once with the narrowest wider mode. 122// Only this prompt's own tool results count: a chat that has run tools before carries older ones. 123const promptAt = messages . findLastIndex ( m => m . role === 'user' && / SCRIPT: / . test ( text ( m ))); 124const toolMessages = messages . slice ( promptAt + 1 ). filter ( m => m . role === 'tool' ); 125if ( last . role === 'tool' && [ 'retrywrite' , 'retryshell' ]. includes ( directive ?.[ 1 ]) && toolMessages . length === 1 && / escalation available / . test ( text ( last ))) { 126const [ file , ...rest ] = ( directive [ 2 ] ?? '' ). trim (). split ( / \s +/ ); 127const value = rest . join ( ' ' ) || 'run' ; 128return toolCall ( directive [ 1 ] === 'retrywrite' ?'write' :shellName (), directive [ 1 ] === 'retrywrite' 129 ?{ file_path :file , content :` ${ value } 130` , sandbox_permissions :'workspace-write' , justification :'The user asked for this file to be written.' } 131 :{ command :shellCommand ( file , value ), description :`Append one line to ${ file } ` , sandbox_permissions :'workspace-write' , justification :'The user asked for this file to be written.' }); 132} 133// Time-skip's two own questions (they quote the plan, whose steps carry directives, so they are recognised by their words first). 134{ 135const t = messages . filter ( m => m . role === 'user' ). map ( text ). join ( ' ' ); 136const answered = messages . some ( m => m . role === 'assistant' ); 137if ( / biggest lever / . test ( t ) && ! answered && last . role !== 'tool' ) return say ([ '{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}' ]); 138if ( / IMPROVEMENT PLAN / . test ( t ) && ! answered && last . role !== 'tool' ) return say ([ '## Better path\n\n' , '1. Improve the first attempt SCRIPT:goalstep\n' , '2. Polish and check SCRIPT:goalstep\n' ]); 139} 140if ( directive ?.[ 1 ] === 'searchloop' ) { 141const n = requests . filter ( r => r . directive === 'searchloop' ). length ; 142send ({ role :'assistant' , content :`Plan, version ${ n } : 143 144## Search plan 145 1461. Search for the topic 1472. Read the best result 1483. Write the summary 149 150` }); 151const argsJson = JSON . stringify ({ queries :[ `topic search number ${ n } ` ] }); 152send ({ tool_calls :[{ index :0 , id :`call_ ${ requests . length } ` , type :'function' , function :{ name :'web_search' , arguments :argsJson } }] }); 153return finish ( 'tool_calls' , 60 ); 154} 155if ( directive ?.[ 1 ] === 'cutwrite' || directive ?.[ 1 ] === 'cutalways' ) { 156// A reply the length limit cuts inside a tool call (AGENT-LOST): some words, then `write` arguments that never close, finish "length". 157// `cutwrite` is cut once and then, asked to carry on, writes the file in a small call; `cutalways` is cut every time. 158const nudged = messages . some ( m => m . role === 'user' && / cut off by the output limit / . test ( text ( m ))); 159if ( directive [ 1 ] === 'cutwrite' && nudged ) { 160if ( last . role === 'tool' ) return say ([ 'Written in parts. The file is complete.' ]); 161return toolCall ( 'write' , { file_path :( directive [ 2 ] ?? '' ). trim () || 'big.txt' , content :'entry 0001\nentry 0002\n' }); 162} 163send ({ role :'assistant' , content :'Writing the whole file in one call now. ' }); 164await delay ( chunkDelayMs ); 165const file = ( directive [ 2 ] ?? '' ). trim () || 'big.txt' ; 166send ({ tool_calls :[{ index :0 , id :`call_ ${ requests . length } ` , type :'function' , function :{ name :'write' , arguments :'' } }] }); 167const head = `{"file_path":" ${ file } ","content":"` ; 168for ( let i = 0 ; i < head . length ; i += 11 ) { send ({ tool_calls :[{ index :0 , function :{ arguments :head . slice ( i , i + 11 ) } }] }); await delay ( 2 ); } 169for ( let n = 1 ; n <= 60 ; n ++ ) { send ({ tool_calls :[{ index :0 , function :{ arguments :`entry ${ String ( n ). padStart ( 4 , '0' )} : alpha beta gamma delta\\n` } }] }); await delay ( 2 ); } 170return finish ( 'length' , 19660 ); 171} 172if ( directive ?.[ 1 ] === 'bloat' ) { 173promptTokens = parseInt (( directive [ 2 ] ?? '' ). trim (), 10 ) || 100 ; 174send ({ role :'assistant' , content :'' , reasoning_content :'Thinking about it for a long time and never getting to the answer.' }); 175return finish ( 'stop' , 20 ); 176} 177if ( directive ?.[ 1 ] === 'goalstep' ) { 178// A goal round: read the goal, mark it complete, then say so. 179if ( ! toolMessages . length ) return toolCall ( 'get_goal' , {}); 180if ( toolMessages . length === 1 && last . role === 'tool' ) { 181const t = text ( last ); const id = / "id"\s * :\s * " ([ ^ " ] + ) " / . exec ( t )?.[ 1 ]; const revision = Number ( / "revision"\s * :\s * ( \d + ) / . exec ( t )?.[ 1 ] ?? 1 ); 182if ( id ) return toolCall ( 'update_goal' , { goal_id :id , revision, action :'complete' }); 183} 184return say ([ 'Step finished. The result is checked.' ]); 185} 186if ( directive ?.[ 1 ] === 'planslow' ) return say ([ '## Slow plan\n\n' , '1. First thing SCRIPT:goalstep\n' , '2. A step that never finishes SCRIPT:slow 4000\n' , '3. Third thing SCRIPT:goalstep\n' ]); 187if ( directive ?.[ 1 ] === 'planreply' ) return say ([ 'I looked around the folder first.\n\n## The pagoda plan\n\n' , '1. First thing SCRIPT:goalstep\n' , '2. Second thing SCRIPT:goalstep\n' , '3. Third thing SCRIPT:goalstep\n' ]); 188if ( directive ?.[ 1 ] === 'multi' && last . role === 'tool' ) { 189let cfg = {}; 190try { cfg = JSON . parse (( directive [ 2 ] ?? '' ). trim ()); } catch { /* a test bug */ } 191return say ([ String ( cfg . say ?? 'Done.' )]); 192} 193if ( last . role === 'tool' ) { 194const result = text ( last ). replace ( / \s +/ g , ' ' ). slice ( 0 , 120 ); 195return say ([ 'Tool finished. ' , `Result: ${ result } ` ]); 196} 197const [ name , args ] = [ directive ?.[ 1 ], ( directive ?.[ 2 ] ?? '' ). trim ()]; 198// The Harness's compaction request (its summarizer prompt asks for the person's evolving goals): answer with a short summary. 199if ( messages . some ( m => / evolving goals / . test ( text ( m )))) { requests . at ( - 1 ). summary = true ; return say ([ 'Summary of the earlier conversation: the person asked for echoes of a word and got them.' ]); } 200// The Harness's session-title request carries the same user text but offers no tools. 201if ( ! ( body . tools ?? []). length && messages . some ( m => / concise title / i . test ( text ( m )))) return say ([ 'Scripted title' ]); 202if ( name === 'slow' ) { 203const n = parseInt ( args , 10 ) || 400 ; 204return say ( Array . from ({ length :n }, ( _ , i ) => `w ${ i } ` )); 205} 206if ( name === 'hang' ) { send ({ role :'assistant' , content :'' }); return ; } // headers sent, then silence: a model server that went quiet 207if ( name === 'echo' ) return say ([ args ]); 208if ( name === 'retrywrite' || name === 'retryshell' ) { 209const [ file , ...rest ] = args . split ( / \s +/ ); 210const value = rest . join ( ' ' ) || 'run' ; 211return name === 'retrywrite' 212 ?toolCall ( 'write' , { file_path :file , content :` ${ value } 213` }) 214 :toolCall ( shellName (), { command :shellCommand ( file , value ), description :`Append one line to ${ file } ` }); 215} 216if ( name === 'read' ) return toolCall ( 'read' , { file_path :args }); 217if ( name === 'call' ) { 218// This prompt's one call already ran (the Harness may add a context message after its result): answer, never call twice. 219if ( toolMessages . length ) return say ([ 'Tool finished. ' , `Result: ${ text ( toolMessages [ toolMessages . length - 1 ]). replace ( / \s +/ g , ' ' ). slice ( 0 , 120 )} ` ]); 220const at = args . indexOf ( ' ' ); 221let callArgs = {}; 222try { callArgs = JSON . parse ( at < 0 ?'{}' :args . slice ( at + 1 ). replace ( / \s + #\d + . * $ / , '' )); } catch { /* an unparsable script argument is a test bug; send no arguments */ } 223return toolCall ( at < 0 ?args :args . slice ( 0 , at ), callArgs ); 224} 225if ( name === 'multi' ) { 226let cfg = {}; 227try { cfg = JSON . parse ( args . trim ()); } catch { /* a test bug: no calls */ } 228if ( toolMessages . length ) return say ([ String ( cfg . say ?? 'Done.' )]); 229send ({ role :'assistant' , content :'' , reasoning_content :'I will use the tools.' }); 230await delay ( chunkDelayMs ); 231( cfg . calls ?? []). forEach (([ tool , callArgs ], i ) => send ({ tool_calls :[{ index :i , id :`call_ ${ requests . length } _ ${ i } ` , type :'function' , function :{ name :tool , arguments :JSON . stringify ( callArgs ?? {}) } }] })); 232return finish ( 'tool_calls' , 20 ); 233} 234if ( name === 'spawn' ) { 235// A settlement notice (or any later user-role message) after this prompt already got its tool round: just answer. 236if ( messages . slice ( promptAt + 1 ). some ( m => m . role === 'assistant' ) && last . role === 'user' ) { 237return say ([ 'Noted: ' , text ( last ). replace ( / \s +/ g , ' ' ). slice ( 0 , 90 )]); 238} 239const [ count , ...script ] = args . split ( / \s +/ ); 240const n = Math . max ( 1 , Number ( count ) || 1 ); 241send ({ role :'assistant' , content :'' , reasoning_content :`I will start ${ n } helper agents.` }); 242await delay ( chunkDelayMs ); 243for ( let i = 0 ; i < n ; i ++ ) { 244const argsJson = JSON . stringify ({ description :`Helper ${ i + 1 } ` , prompt :`SCRIPT: ${ script . join ( ' ' ) || 'echo done' } # ${ i + 1 } ` }); 245send ({ tool_calls :[{ index :i , id :`call_ ${ requests . length } _ ${ i } ` , type :'function' , function :{ name :'subagent' , arguments :'' } }] }); 246for ( let k = 0 ; k < argsJson . length ; k += 23 ) { send ({ tool_calls :[{ index :i , function :{ arguments :argsJson . slice ( k , k + 23 ) } }] }); await delay ( 2 ); } 247} 248return finish ( 'tool_calls' , 40 * n ); 249} 250if ( name === 'ask' ) { 251send ({ role :'assistant' , content :'' }); 252send ({ tool_calls :[{ index :0 , id :`call_ ${ requests . length } ` , type :'function' , function :{ name :'ask_user_question' , arguments :JSON . stringify ({ questions :[{ id :'q1' , question :'Which colour?' , options :[{ label :'Red' }, { label :'Blue' }] }] }) } }] }); 253return finish ( 'tool_calls' , 20 ); 254} 255if ( name === 'tool' || name === 'plain' || name === 'envdump' ) { 256const [ file , ...rest ] = args . split ( / \s +/ ); 257const shell = ( body . tools ?? []). find ( t => [ 'bash' , 'pwsh' ]. includes ( t . function ?. name ))?. function ?. name ?? 'bash' ; 258const value = rest . join ( ' ' ) || 'run' ; 259let command = shell === 'pwsh' ?`Add-Content -Path ' ${ file } ' -Value ' ${ value } '` :`echo ${ value } >> ${ file } ` ; 260if ( name === 'envdump' ) command = shell === 'pwsh' ?`Get-ChildItem Env: | ForEach-Object { $_.Name + '=' + $_.Value } | Set-Content -Path ' ${ file } '` :`env > ${ file } ` ; 261const call = { command, description :`Append one line to ${ file } ` }; 262if ( name === 'tool' ) { 263call . sandbox_permissions = 'danger-full-access' ; 264call . justification = 'The write must not be refused by the file sandbox.' ; 265} 266send ({ role :'assistant' , content :'' , reasoning_content :'I will write the file with the shell.' }); 267await delay ( chunkDelayMs ); 268const argsJson = JSON . stringify ( call ); 269send ({ tool_calls :[{ index :0 , id :`call_ ${ requests . length } ` , type :'function' , function :{ name :shell , arguments :'' } }] }); 270// Fragment the arguments the way real servers do. 271for ( let i = 0 ; i < argsJson . length ; i += 17 ) { 272send ({ tool_calls :[{ index :0 , function :{ arguments :argsJson . slice ( i , i + 17 ) } }] }); 273await delay ( 5 ); 274} 275return finish ( 'tool_calls' , 30 ); 276} 277// hello, and the default for anything unscripted (including the Harness's own title request) 278send ({ role :'assistant' , content :'' , reasoning_content :'Considering a greeting.' }); 279await delay ( chunkDelayMs ); 280return say ([ 'Hello ' , 'from ' , 'the ' , 'scripted ' , 'worker.' ]); 281}); 282await new Promise ( r => server . listen ( port , '127.0.0.1' , r )); 283return { 284port :server . address (). port , 285url :`http://127.0.0.1: ${ server . address (). port } /v1` , 286 requests, counts, get aborted () { return aborted ; }, 287close :() => new Promise ( r => { server . closeAllConnections ?.(); server . close ( r ); }), 288}; 289} 290 291if ( import . meta. url === `file:// ${ process . argv [ 1 ]. replace ( / \\ / g , '/' )} ` || process . argv [ 1 ]?. endsWith ( 'scripted-worker.mjs' )) { 292const w = await startScriptedWorker ({ port :Number ( process . env . PORT ?? 0 ) }); 293console . log ( `scripted worker on ${ w . url } ` ); 294}