okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1306424be
main
1/** 2* Agent bridge, end to end against the real pinned Harness and a scripted worker. 3* 4* Needs the built Harness: set STRATA_HARNESS_DIR to a checkout built with `pnpm install` and 5* `pnpm run build:artifacts`. Without it these tests skip, loudly, rather than pass. 6* 7* The model is scripted (tests/helpers/scripted-worker.mjs). What is real: the Harness process, its 8* agent loop, its tool executor and approval gate, the gateway, the durable session, and the bridge. 9* A scripted model proves the path; it does not prove a model chooses tools well. 10*/ 11import test from 'node:test' ; 12import assert from 'node:assert/strict' ; 13import { existsSync , mkdtempSync , readFileSync , readdirSync , rmSync , mkdirSync , statSync } from 'node:fs' ; 14import { tmpdir } from 'node:os' ; 15import { join } from 'node:path' ; 16import { createHash } from 'node:crypto' ; 17import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 18import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 19import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 20 21const HARNESS = process . env . STRATA_HARNESS_DIR ; 22const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 23 24function cleanup ( dir ) { 25// The Harness's Windows sandbox adds access entries under the directories it works in, which can make a 26// plain recursive delete fail with EPERM. Cleanup is best effort; a leftover temp dir is not a failure. 27try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } 28} 29 30const lines = file => readFileSync ( file , 'utf8' ). split ( / \r ? \n / ). filter ( Boolean ). length ; 31 32async function rig ( t , { connections= [], dataDir} = {}) { 33const worker = await startScriptedWorker ({}); 34const dir = dataDir ?? mkdtempSync ( join ( tmpdir (), 'strata-agent-' )); 35const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 36const local = [{ id :'inst-1' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 }]; 37const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => connections , env :process . env , startTimeoutMs :90_000 }); 38t . after ( async () => { await bridge . close (); await worker . close (); if ( ! dataDir ) cleanup ( dir ); }); 39const run = ( chatId , message , opts = {}) => { 40const frames = []; 41const answerWith = opts . answer ; // 'approve' | 'deny' | undefined 42const promise = bridge . runTurn ({ 43 chatId, message, workspacePath :ws , choice :opts . choice ?? null , mode :opts . mode ?? null , history :opts . history ?? [], 44onFrame :f => { 45frames . push ( f ); 46opts . onFrame ?.( f ); 47if ( answerWith && f . type === 'agent-tool' && f . tool . state === 'proposed' ) { 48void bridge . approve ({ chatId, callId :f . tool . id , decision :answerWith }). catch ( e => frames . push ({ type :'test-error' , message :e . message })); 49} 50}, 51signal :opts . signal , 52}); 53return { frames, promise}; 54}; 55return { worker, bridge, dir, ws, run, local}; 56} 57 58const states = ( frames , id ) => frames . filter ( f => f . type === 'agent-tool' && ( ! id || f . tool . id === id )). map ( f => f . tool . state ); 59const text = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 60 61test ( 'A01/A02 a turn streams reasoning and text, then finishes with usage' , { skip}, async t => { 62const r = await rig ( t ); 63const { frames, promise} = r . run ( 'chat-a01' , 'SCRIPT:hello' ); 64await promise ; 65assert . equal ( frames [ 0 ]. type , 'queued' ); 66const start = frames . find ( f => f . type === 'start' ); 67assert . equal ( start . agent , true ); assert . equal ( start . model , 'Scripted' ); assert . equal ( start . contextMax , 32768 ); 68assert . match ( frames . filter ( f => f . type === 'reasoning' ). map ( f => f . text ). join ( '' ), / Considering a greeting / ); 69assert . equal ( text ( frames ), 'Hello from the scripted worker.' ); 70const done = frames . at ( - 1 ); 71assert . equal ( done . type , 'done' ); assert . equal ( done . finishReason , 'stop' ); assert . equal ( done . usageSource , 'reported' ); 72assert . ok ( done . tokensIn > 0 && done . tokensOut > 0 ); 73assert . equal ( frames . filter ( f => f . type === 'error' ). length , 0 ); 74// The route is the declared local one, not a default the catalog would have chosen. 75assert . ok ( r . worker . requests . every ( q => q . model === 'scripted-model' )); 76}); 77 78test ( 'A03 a tool runs exactly once, in the Harness, after the user approves' , { skip}, async t => { 79const r = await rig ( t ); 80const { frames, promise} = r . run ( 'chat-a03' , 'SCRIPT:tool marker.txt hi' , { answer :'approve' }); 81await promise ; 82const calls = frames . filter ( f => f . type === 'agent-tool' && f . tool . state === 'running' ); 83assert . ok ( calls . length >= 1 ); 84const id = frames . find ( f => f . type === 'agent-tool' ). tool . id ; 85assert . deepEqual ([ ...new Set ( states ( frames , id ))], [ 'running' , 'proposed' , 'done' ]); 86assert . equal ( frames . filter ( f => f . type === 'test-error' ). length , 0 ); 87assert . equal ( lines ( join ( r . ws , 'marker.txt' )), 1 , 'the marker must have exactly one line: the tool ran once' ); 88const card = frames . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool ; 89assert . equal ( card . scope , 'shell' ); assert . match ( card . preview , / marker\.txt / ); 90assert . equal ( frames . at ( - 1 ). type , 'done' ); 91// The worker only saw a transcript: it has no execution path, and it was asked twice (call, then result). 92assert . equal ( r . worker . requests . filter ( q => q . toolNames . length ). length , 2 ); 93assert . match ( text ( frames ), / Tool finished / ); 94}); 95 96test ( 'A04 a denied tool never runs, and the agent is told' , { skip}, async t => { 97const r = await rig ( t ); 98const { frames, promise} = r . run ( 'chat-a04' , 'SCRIPT:tool denied.txt nope' , { answer :'deny' }); 99await promise ; 100const id = frames . find ( f => f . type === 'agent-tool' ). tool . id ; 101assert . deepEqual ([ ...new Set ( states ( frames , id ))], [ 'running' , 'proposed' , 'denied' ]); 102assert . equal ( existsSync ( join ( r . ws , 'denied.txt' )), false , 'a denied tool must not run' ); 103assert . equal ( frames . at ( - 1 ). type , 'done' , 'the turn still settles' ); 104// The model got the denial back as a tool result it can read. 105assert . match ( text ( frames ), / reject | denied | Tool finished / i ); 106}); 107 108test ( 'A05 Stop cancels exactly that chat, waits for the turn to end, and leaves other chats running' , { skip}, async t => { 109const r = await rig ( t ); 110const slowA = r . run ( 'chat-a05-a' , 'SCRIPT:slow 400' ); 111const slowB = r . run ( 'chat-a05-b' , 'SCRIPT:slow 60' ); 112// wait until A is demonstrably live 113for ( let i = 0 ; i < 200 && slowA . frames . filter ( f => f . type === 'delta' ). length < 3 ; i ++ ) await new Promise ( x => setTimeout ( x , 50 )); 114assert . ok ( slowA . frames . filter ( f => f . type === 'delta' ). length >= 3 , 'the turn must be live before Stop, or the test proves nothing' ); 115const stopped = await r . bridge . stop ( 'chat-a05-a' ); 116assert . equal ( stopped . stopped , true ); assert . equal ( stopped . ended , 'aborted' ); 117await slowA . promise ; 118assert . equal ( slowA . frames . at ( - 1 ). finishReason , 'aborted' ); assert . equal ( slowA . frames . at ( - 1 ). cancelled , true ); 119assert . ok ( slowA . frames . filter ( f => f . type === 'delta' ). length < 400 , 'the stream was cut short' ); 120assert . ok ( r . worker . aborted >= 1 , 'the model request was cancelled at the worker' ); 121assert . equal ( r . bridge . isRunning ( 'chat-a05-a' ), false ); 122// B was not touched and runs to its end. 123await slowB . promise ; 124assert . equal ( slowB . frames . at ( - 1 ). finishReason , 'stop' ); 125assert . equal ( slowB . frames . filter ( f => f . type === 'delta' ). length , 60 ); 126// And A can be used again. 127const again = r . run ( 'chat-a05-a' , 'SCRIPT:echo after stop' ); await again . promise ; 128assert . equal ( text ( again . frames ), 'after stop' ); 129}); 130 131test ( 'A05b Stop while an approval is pending denies it and ends the turn' , { skip}, async t => { 132const r = await rig ( t ); 133const { frames, promise} = r . run ( 'chat-a05b' , 'SCRIPT:tool never.txt x' ); 134for ( let i = 0 ; i < 200 && ! states ( frames ). includes ( 'proposed' ); i ++ ) await new Promise ( x => setTimeout ( x , 50 )); 135assert . ok ( states ( frames ). includes ( 'proposed' )); 136const stopped = await r . bridge . stop ( 'chat-a05b' ); 137assert . equal ( stopped . stopped , true ); 138await promise ; 139assert . equal ( existsSync ( join ( r . ws , 'never.txt' )), false ); 140assert . equal ( states ( frames ). at ( - 1 ), 'denied' ); 141assert . equal ( r . bridge . pendingFor ( 'chat-a05b' ). length , 0 ); 142}); 143 144test ( 'A06 reopening a chat resumes its Harness session without replaying a tool' , { skip}, async t => { 145const dir = mkdtempSync ( join ( tmpdir (), 'strata-agent-resume-' )); 146t . after (() => cleanup ( dir )); 147const first = await rig ( t , { dataDir :dir }); 148const turn1 = first . run ( 'chat-a06' , 'SCRIPT:tool resume.txt once' , { answer :'approve' }); 149await turn1 . promise ; 150const sessionId = first . bridge . sessionOf ( 'chat-a06' ); 151assert . ok ( sessionId ); 152assert . equal ( lines ( join ( first . ws , 'resume.txt' )), 1 ); 153await first . bridge . close (); // the host goes away; the Harness process with it 154 155// A new host process over the same data directory. 156const second = await rig ( t , { dataDir :dir }); 157assert . equal ( second . bridge . sessionOf ( 'chat-a06' ), sessionId , 'the chat keeps its session id' ); 158const turn2 = second . run ( 'chat-a06' , 'SCRIPT:echo second turn' ); 159await turn2 . promise ; 160assert . equal ( second . bridge . sessionOf ( 'chat-a06' ), sessionId ); 161assert . equal ( text ( turn2 . frames ), 'second turn' ); 162assert . equal ( turn2 . frames . filter ( f => f . type === 'agent-tool' ). length , 0 , 'no tool card appears on resume' ); 163assert . equal ( lines ( join ( second . ws , 'resume.txt' )), 1 , 'the earlier tool effect was not replayed' ); 164// The agent really carried the earlier conversation: its request holds the earlier turn too. 165const resumed = second . worker . requests . find ( q => q . toolNames . length ); 166assert . ok ( resumed . messageCount > 5 , `expected earlier messages in the request, saw ${ resumed . messageCount } ` ); 167}); 168 169test ( 'A08 two chats run independently, each with its own session and approval' , { skip}, async t => { 170const r = await rig ( t ); 171const a = r . run ( 'chat-a08-a' , 'SCRIPT:tool a.txt A' ); // will wait on approval 172for ( let i = 0 ; i < 200 && ! states ( a . frames ). includes ( 'proposed' ); i ++ ) await new Promise ( x => setTimeout ( x , 50 )); 173assert . ok ( states ( a . frames ). includes ( 'proposed' )); 174const b = r . run ( 'chat-a08-b' , 'SCRIPT:hello' ); 175await b . promise ; // B finishes while A is parked on an approval 176assert . equal ( text ( b . frames ), 'Hello from the scripted worker.' ); 177assert . equal ( states ( a . frames ). at ( - 1 ), 'proposed' , 'A is still waiting' ); 178assert . notEqual ( r . bridge . sessionOf ( 'chat-a08-a' ), r . bridge . sessionOf ( 'chat-a08-b' )); 179assert . equal ( r . bridge . pendingFor ( 'chat-a08-b' ). length , 0 ); 180assert . equal ( r . bridge . pendingFor ( 'chat-a08-a' ). length , 1 ); 181assert . deepEqual ( r . bridge . pendingAll (). map ( c => c . chatId ), [ 'chat-a08-a' ], 'the board lists every chat that waits, and only those' ); 182const callId = a . frames . find ( f => f . type === 'agent-tool' ). tool . id ; 183// An approval cannot be answered through the wrong chat. 184await assert . rejects ( r . bridge . approve ({ chatId :'chat-a08-b' , callId, decision :'approve' }), / no longer waiting / ); 185await r . bridge . approve ({ chatId :'chat-a08-a' , callId, decision :'approve' }); 186await a . promise ; 187assert . equal ( states ( a . frames ). at ( - 1 ), 'done' ); 188assert . equal ( lines ( join ( r . ws , 'a.txt' )), 1 ); 189}); 190 191test ( 'a second send to a chat that is mid-turn is refused' , { skip}, async t => { 192const r = await rig ( t ); 193const first = r . run ( 'chat-busy' , 'SCRIPT:slow 80' ); 194for ( let i = 0 ; i < 100 && ! first . frames . some ( f => f . type === 'delta' ); i ++ ) await new Promise ( x => setTimeout ( x , 50 )); 195await assert . rejects ( r . run ( 'chat-busy' , 'SCRIPT:hello' ). promise , / still working / ); 196await first . promise ; 197}); 198 199test ( 'an API connection becomes a route; its key reaches the model by reference and nowhere else' , { skip}, async t => { 200const secret = 'sk-test-SECRET-0123456789abcdef' ; 201const dir = mkdtempSync ( join ( tmpdir (), 'strata-agent-keys-' )); 202t . after (() => cleanup ( dir )); 203const apiWorker = await startScriptedWorker ({ model :'cloud-model' }); 204t . after (() => apiWorker . close ()); 205const connections = [{ id :'abcd1234-conn' , name :'Cloud test' , baseUrl :apiWorker . url , protocol :'openai-chat' , apiKey :secret , models :[{ id :'cloud-model' , name :'Cloud model' , contextMax :64000 }] }]; 206const r = await rig ( t , { dataDir :dir , connections}); 207const frames = []; 208await r . bridge . runTurn ({ chatId :'chat-api' , message :'SCRIPT:hello' , workspacePath :r . ws , choice :{ connectionId :'abcd1234-conn' , modelId :'cloud-model' }, onFrame :f => frames . push ( f ) }); 209assert . equal ( frames . find ( f => f . type === 'start' ). remoteModel , true ); 210assert . equal ( frames . find ( f => f . type === 'start' ). model , 'Cloud model' ); 211assert . equal ( text ( frames ), 'Hello from the scripted worker.' ); 212// The chat used the API worker, the local worker was never asked. 213assert . ok ( apiWorker . requests . length >= 1 ); assert . equal ( r . worker . requests . length , 0 ); 214const expected = createHash ( 'sha256' ). update ( `Bearer ${ secret } ` ). digest ( 'hex' ); 215assert . ok ( apiWorker . requests . every ( q => q . authSha === expected ), 'the key arrived as the bearer credential' ); 216// A different chat on the local default is unaffected by the first chat's choice. 217const local = []; await r . bridge . runTurn ({ chatId :'chat-local' , message :'SCRIPT:hello' , workspacePath :r . ws , onFrame :f => local . push ( f ) }); 218assert . equal ( local . find ( f => f . type === 'start' ). remoteModel , false ); 219assert . ok ( r . worker . requests . length >= 1 ); 220 221// The shell tool the agent runs must not see the key. 222// Bypass: the dump is a plain in-workspace write, which Manual would (rightly) make the person approve first. 223const env = r . run ( 'chat-api' , 'SCRIPT:envdump envdump.txt' , { choice :{ connectionId :'abcd1234-conn' , modelId :'cloud-model' }, mode :'bypass' }); 224await env . promise ; 225assert . ok ( existsSync ( join ( r . ws , 'envdump.txt' )), 'the env dump tool must have run' ); 226const dump = readFileSync ( join ( r . ws , 'envdump.txt' ), 'utf8' ); 227assert . match ( dump , / ^PATH= / im , 'the dump must really list the environment, or its silence about the key proves nothing' ); 228assert . ok ( ! dump . includes ( secret ), 'the agent shell must not inherit the key' ); 229// Nowhere on disk the host wrote: profile, logs, session map. (The compressed session store is checked by absence in frames.) 230const stack = [ join ( dir , 'agent' )]; 231while ( stack . length ) { 232const p = stack . pop (); 233if ( statSync ( p ). isDirectory ()) { if ( p . endsWith ( 'home' )) continue ; for ( const n of readdirSync ( p )) stack . push ( join ( p , n )); continue ; } 234assert . ok ( ! readFileSync ( p ). includes ( secret ), ` ${ p } must not contain the key` ); 235} 236assert . ok ( ! JSON . stringify ( frames ). includes ( secret ) && ! JSON . stringify ( r . bridge . status ()). includes ( secret )); 237}); 238 239test ( 'a missing or removed connection is a typed error, never another model' , { skip}, async t => { 240const r = await rig ( t ); 241await assert . rejects ( r . bridge . runTurn ({ chatId :'chat-gone' , message :'SCRIPT:hello' , workspacePath :r . ws , choice :{ connectionId :'nope' , modelId :'m' }, onFrame :() => {} }), err => err . code === 'model-unavailable' ); 242assert . equal ( r . worker . requests . length , 0 , 'nothing was sent to the local model instead' ); 243}); 244 245test ( 'A05c Stop pressed while the agent is still starting cancels the start, and nothing reaches the model' , { skip}, async t => { 246const r = await rig ( t ); 247const { frames, promise} = r . run ( 'chat-a05c' , 'SCRIPT:slow 200' ); 248await new Promise ( x => setTimeout ( x , 150 )); // the Harness process takes about two seconds to boot 249const stopped = await r . bridge . stop ( 'chat-a05c' ); 250assert . equal ( stopped . stopped , true ); 251const result = await promise ; 252assert . equal ( result . cancelled , true ); 253assert . equal ( frames . at ( - 1 ). finishReason , 'aborted' ); 254assert . equal ( r . worker . requests . length , 0 , 'the model was never asked' ); 255// The chat is usable afterwards. 256const again = r . run ( 'chat-a05c' , 'SCRIPT:echo fine' ); await again . promise ; 257assert . equal ( text ( again . frames ), 'fine' ); 258}); 259 260test ( 'a leftover agent from a host that died is stopped at the next start, and an unrelated PID is never touched' , { skip}, async t => { 261const { HarnessProcess, stopStaleAgent} = await import ( '../server/agent/harness-runtime.mjs' ); 262const { buildProfile} = await import ( '../server/agent/profile.mjs' ); 263const { writeFileSync} = await import ( 'node:fs' ); 264const { spawn} = await import ( 'node:child_process' ); 265const dir = mkdtempSync ( join ( tmpdir (), 'strata-stale-' )); 266t . after (() => cleanup ( dir )); 267const profile = buildProfile ({ local :[{ id :'x' , baseUrl :'http://127.0.0.1:9/v1' , modelId :'m' , context :8192 }] }); 268const patchFile = join ( dir , 'p.patch.yml' ); writeFileSync ( patchFile , profile . patch ); 269const pidFile = join ( dir , 'harness.pid' ); 270const hp = new HarnessProcess ({ harness :resolveHarness ({ env :process . env }), home :join ( dir , 'home' ), patchFile, cwd :join ( dir , 'run' ), env :profile . env , pidFile}); 271await hp . start ({ timeoutMs :90_000 }); 272const pid = hp . pid ; 273assert . ok ( existsSync ( pidFile ), 'the agent records its PID' ); 274// The host "dies": nothing calls stop(). The next start finds the record. 275assert . equal ( stopStaleAgent ( pidFile ), pid ); 276for ( let i = 0 ; i < 50 && hp . exited === null ; i ++ ) await new Promise ( x => setTimeout ( x , 100 )); 277assert . notEqual ( hp . exited , null , 'the leftover agent was stopped' ); 278assert . equal ( existsSync ( pidFile ), false ); 279 280// A record that points at some other process must not kill it. 281const bystander = spawn ( process . execPath , [ '-e' , 'setTimeout(() => {}, 60000)' ], { stdio :'ignore' }); 282t . after (() => bystander . kill ()); 283writeFileSync ( pidFile , JSON . stringify ({ pid :bystander . pid })); 284assert . equal ( stopStaleAgent ( pidFile ), null ); 285await new Promise ( x => setTimeout ( x , 300 )); 286assert . equal ( bystander . exitCode , null , 'an unrelated process is left alone' ); 287}); 288 289const until = async ( fn , ms = 30_000 ) => { const t0 = Date . now (); for (;;) { const v = fn (); if ( v ) return v ; if ( Date . now () - t0 > ms ) return null ; await new Promise ( x => setTimeout ( x , 50 )); } }; 290 291test ( 'a question the agent asks the person waits for the person (#4244); a skip lets the model carry on and the turn does not hang' , { skip}, async t => { 292const r = await rig ( t ); 293const { frames, promise} = r . run ( 'chat-ask' , 'SCRIPT:ask' ); 294const asked = await until (() => frames . find ( f => f . type === 'agent-question' )); 295assert . ok ( asked , 'the question reaches the page as a frame' ); 296assert . equal ( asked . questions [ 0 ]. id , 'q1' ); assert . deepEqual ( asked . questions [ 0 ]. options . map ( o => o . label ), [ 'Red' , 'Blue' ]); 297await r . bridge . answerQuestion ({ chatId :'chat-ask' , callId :asked . callId , skip :true }); 298const result = await Promise . race ([ promise , new Promise ( x => setTimeout (() => x ( 'hung' ), 30_000 ))]); 299assert . notEqual ( result , 'hung' , 'the turn must not wait forever once the question is skipped' ); 300assert . equal ( frames . at ( - 1 ). type , 'done' ); 301assert . equal ( frames . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool . name , 'ask_user_question' ); 302assert . match ( text ( frames ), / Tool finished / , 'the model got the result back and finished' ); 303}); 304 305test ( 'an answer to the question of the agent reaches the model as the tool result (#4244)' , { skip}, async t => { 306const r = await rig ( t ); 307const { frames, promise} = r . run ( 'chat-ask2' , 'SCRIPT:ask' ); 308const asked = await until (() => frames . find ( f => f . type === 'agent-question' )); 309assert . ok ( asked ); 310await assert . rejects ( r . bridge . answerQuestion ({ chatId :'chat-ask2' , callId :asked . callId , answers :[{ id :'q1' , selected :[ 'Green' ] }] }), / Answer every question / , 'a label that was not offered is not an answer' ); 311await r . bridge . answerQuestion ({ chatId :'chat-ask2' , callId :asked . callId , answers :[{ id :'q1' , selected :[ 'Blue' ] }] }); 312await promise ; 313const tool = frames . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool ; 314assert . notEqual ( tool . state , 'error' , 'the tool was answered, not declared unanswerable' ); 315assert . match ( JSON . stringify ([ ...r . worker . requests ]. at ( - 1 ). raw ), / Blue / , 'the model was told what the person chose' ); 316await assert . rejects ( r . bridge . answerQuestion ({ chatId :'chat-ask2' , callId :asked . callId , skip :true }), / already answered / , 'an answer is final' ); 317});