okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
394de9291
main
1/** 2* The host's HTTP surface for agent chats, against a real host process, the real Harness and a 3* scripted worker standing in as an API model. 4* 5* Needs STRATA_HARNESS_DIR (a built Harness) for everything except the "component missing" test. 6* What is exercised: /api/chat/stream (NDJSON), /api/chat/approval, /api/chat/stop, /api/agent/status, 7* resume across a host restart, two chats at once, and the visible fallback when the component is absent. 8*/ 9import test from 'node:test' ; 10import assert from 'node:assert/strict' ; 11import { spawn , spawnSync } from 'node:child_process' ; 12import { existsSync , mkdirSync , mkdtempSync , readFileSync , rmSync } from 'node:fs' ; 13import { createServer } from 'node:net' ; 14import { tmpdir } from 'node:os' ; 15import { join , resolve } from 'node:path' ; 16import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 17import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 18 19const HARNESS = process . env . STRATA_HARNESS_DIR ; 20const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 21const HOST = resolve ( import . meta. dirname , '..' , 'server' , 'index.mjs' ); 22 23const freePort = () => new Promise ( r => { const s = createServer (); s . listen ( 0 , '127.0.0.1' , () => { const p = s . address (). port ; s . close (() => r ( p )); }); }); 24const cleanup = dir => { try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } }; 25const sleep = ms => new Promise ( r => setTimeout ( r , ms )); 26 27async function startHost ( t , { home, ws, harness= HARNESS } = {}) { 28const port = await freePort (); 29const env = { ...process . env , STRATA_HOME :home , STRATA_PORT :String ( port ), STRATA_WORKSPACE :ws , STRATA_REAL_ENGINE :'0' , STRATA_COMPONENTS_DIR :join ( home , 'components' ) }; 30if ( harness ) env . STRATA_HARNESS_DIR = harness ; else delete env . STRATA_HARNESS_DIR ; 31const child = spawn ( process . execPath , [ HOST ], { env, stdio :[ 'ignore' , 'pipe' , 'pipe' ], windowsHide :true }); 32let log = '' ; 33child . stdout . on ( 'data' , d => { log += d ; }); child . stderr . on ( 'data' , d => { log += d ; }); 34const stop = async () => { 35if ( child . exitCode !== null ) return ; 36if ( process . platform === 'win32' ) spawnSync ( 'taskkill' , [ '/PID' , String ( child . pid ), '/T' , '/F' ], { windowsHide :true }); 37else child . kill ( 'SIGTERM' ); 38await new Promise ( r => child . once ( 'exit' , r )); 39}; 40t . after ( stop ); 41const base = `http://127.0.0.1: ${ port } ` ; 42for ( let i = 0 ; i < 100 ; i ++ ) { 43try { if (( await fetch ( ` ${ base } /api/agent/status` )). ok ) break ; } catch { /* not up yet */ } 44if ( child . exitCode !== null ) throw new Error ( `the host exited: ${ log . slice ( - 500 )} ` ); 45await sleep ( 200 ); 46} 47const post = async ( path , body ) => { const res = await fetch ( ` ${ base } ${ path } ` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ( body ) }); return { status :res . status , body :await res . json (). catch (() => null ) }; }; 48/** Stream one chat turn; `onFrame` may react while it runs. Resolves with every frame. */ 49const chat = async ( body , onFrame = () => {}) => { 50const res = await fetch ( ` ${ base } /api/chat/stream` , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ( body ) }); 51assert . equal ( res . status , 200 , `chat/stream: ${ res . status } ` ); 52const frames = []; let buffer = '' ; 53const decoder = new TextDecoder (); 54for await ( const chunk of res . body ) { 55buffer += decoder . decode ( chunk , { stream :true }); 56let i ; 57while (( i = buffer . indexOf ( '\n' )) >= 0 ) { 58const line = buffer . slice ( 0 , i ). trim (); buffer = buffer . slice ( i + 1 ); 59if ( line ) { const f = JSON . parse ( line ); frames . push ( f ); onFrame ( f ); } 60} 61} 62return frames ; 63}; 64return { base, port, post, chat, stop, log :() => log , status :async () => ( await fetch ( ` ${ base } /api/agent/status` )). json () }; 65} 66 67async function setup ( t , { harness= HARNESS , reuse} = {}) { 68const worker = reuse ?. worker ?? await startScriptedWorker ({ model :'cloud-model' }); 69const home = reuse ?. home ?? mkdtempSync ( join ( tmpdir (), 'strata-host-' )); 70const ws = join ( home , 'workspace' ); mkdirSync ( ws , { recursive :true }); 71const host = await startHost ( t , { home, ws, harness}); 72let connectionId = reuse ?. connectionId ; 73if ( ! connectionId ) { 74const saved = await host . post ( '/api/model-providers' , { kind :'custom' , name :'Scripted API' , baseUrl :worker . url , protocol :'openai-chat' , apiKey :'sk-host-test-0123456789' , models :[{ id :'cloud-model' , name :'Cloud model' , contextMax :64000 }] }); 75assert . equal ( saved . status , 200 , JSON . stringify ( saved . body )); 76connectionId = saved . body . connections [ 0 ]. id ; 77} 78if ( ! reuse ) t . after ( async () => { await worker . close (); cleanup ( home ); }); 79const remoteModel = { connectionId, modelId :'cloud-model' }; 80const send = ( host , sessionId , message , onFrame ) => host . chat ({ sessionId, message, remoteModel, workspaceId :null , history :[] }, onFrame ); 81return { worker, home, ws, host, connectionId, remoteModel, send :( sessionId , message , onFrame ) => send ( host , sessionId , message , onFrame ) }; 82} 83 84const toolStates = ( frames , id ) => frames . filter ( f => f . type === 'agent-tool' && ( ! id || f . tool . id === id )). map ( f => f . tool . state ); 85const text = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 86const lines = file => readFileSync ( file , 'utf8' ). split ( / \r ? \n / ). filter ( Boolean ). length ; 87 88test ( 'status names the component and the routes, and carries no secret' , { skip}, async t => { 89const s = await setup ( t ); 90const status = await s . host . status (); 91assert . equal ( status . harness . version , '0.2.1-alpha.3' ); 92assert . ok ( status . routes . some ( r => r . kind === 'api' && r . modelId === 'cloud-model' )); 93assert . ok ( ! JSON . stringify ( status ). includes ( 'sk-host-test' )); 94}); 95 96test ( 'A03 over HTTP: the card waits for Approve, the answer reaches the Harness, the tool runs once' , { skip}, async t => { 97const s = await setup ( t ); 98let answered = false ; 99const frames = await s . send ( 'chat-h-a03' , 'SCRIPT:tool http.txt hi' , async f => { 100if ( f . type === 'agent-tool' && f . tool . state === 'proposed' && ! answered ) { 101answered = true ; 102const r = await s . host . post ( '/api/chat/approval' , { sessionId :'chat-h-a03' , toolId :f . tool . id , decision :'approve' }); 103assert . equal ( r . status , 200 , JSON . stringify ( r . body )); 104} 105}); 106assert . ok ( answered , 'an approval request must have reached the client' ); 107const id = frames . find ( f => f . type === 'agent-tool' ). tool . id ; 108assert . deepEqual ([ ...new Set ( toolStates ( frames , id ))], [ 'running' , 'proposed' , 'done' ]); 109assert . equal ( lines ( join ( s . ws , 'http.txt' )), 1 ); 110assert . equal ( frames . at ( - 1 ). type , 'done' ); 111// A second answer to the same approval is refused: it is no longer pending. 112const again = await s . host . post ( '/api/chat/approval' , { sessionId :'chat-h-a03' , toolId :id , decision :'approve' }); 113assert . equal ( again . status , 409 ); 114}); 115 116test ( 'A04 over HTTP: Deny means the tool never runs' , { skip}, async t => { 117const s = await setup ( t ); 118const frames = await s . send ( 'chat-h-a04' , 'SCRIPT:tool never-http.txt x' , async f => { 119if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) await s . host . post ( '/api/chat/approval' , { sessionId :'chat-h-a04' , toolId :f . tool . id , decision :'deny' }); 120}); 121assert . equal ( toolStates ( frames ). at ( - 1 ), 'denied' ); 122assert . equal ( existsSync ( join ( s . ws , 'never-http.txt' )), false ); 123assert . equal ( frames . at ( - 1 ). type , 'done' ); 124}); 125 126test ( 'A05 over HTTP: /api/chat/stop ends that chat only and answers after the turn ended' , { skip}, async t => { 127const s = await setup ( t ); 128let live = 0 , stopResult = null ; 129const slow = s . send ( 'chat-h-a05-a' , 'SCRIPT:slow 400' , async f => { 130if ( f . type === 'delta' && ++ live === 3 ) stopResult = await s . host . post ( '/api/chat/stop' , { sessionId :'chat-h-a05-a' }); 131}); 132const other = s . send ( 'chat-h-a05-b' , 'SCRIPT:slow 50' ); 133const [ a , b ] = await Promise . all ([ slow , other ]); 134assert . equal ( stopResult . status , 200 ); 135assert . equal ( stopResult . body . stopped , true ); assert . equal ( stopResult . body . ended , 'aborted' ); 136assert . equal ( a . at ( - 1 ). finishReason , 'aborted' ); 137assert . equal ( b . at ( - 1 ). finishReason , 'stop' ); assert . equal ( b . filter ( f => f . type === 'delta' ). length , 50 ); 138assert . ok ( s . worker . aborted >= 1 ); 139// Nothing to stop afterwards. 140const none = await s . host . post ( '/api/chat/stop' , { sessionId :'chat-h-a05-a' }); 141assert . equal ( none . body . stopped , false ); 142}); 143 144test ( 'a client that disconnects does not stop the turn; the tool still waits for its approval' , { skip}, async t => { 145const s = await setup ( t ); 146const controller = new AbortController (); 147const res = await fetch ( ` ${ s . host . base } /api/chat/stream` , { method :'POST' , headers :{ 'content-type' :'application/json' }, signal :controller . signal , body :JSON . stringify ({ sessionId :'chat-h-detach' , message :'SCRIPT:tool detach.txt d' , remoteModel :s . remoteModel , history :[] }) }); 148const reader = res . body . getReader (); let seen = '' ; 149while ( ! seen . includes ( '"proposed"' )) { const { value, done} = await reader . read (); if ( done ) break ; seen += new TextDecoder (). decode ( value ); } 150assert . match ( seen , / "proposed" / ); 151controller . abort (); // the tab closes 152await sleep ( 500 ); 153assert . equal ( existsSync ( join ( s . ws , 'detach.txt' )), false , 'a closed tab is not an approval' ); 154const pending = await ( await fetch ( ` ${ s . host . base } /api/agent/pending?chatId=chat-h-detach` )). json (); 155assert . equal ( pending . pending . length , 1 , 'the approval is still waiting for someone' ); 156// Someone comes back and answers it; the turn finishes in the background. 157const r = await s . host . post ( '/api/chat/approval' , { sessionId :'chat-h-detach' , toolId :pending . pending [ 0 ]. callId , decision :'approve' }); 158assert . equal ( r . status , 200 ); 159for ( let i = 0 ; i < 100 && ! existsSync ( join ( s . ws , 'detach.txt' )); i ++ ) await sleep ( 100 ); 160assert . equal ( lines ( join ( s . ws , 'detach.txt' )), 1 ); 161}); 162 163test ( 'A06 over HTTP: after the host restarts, the same chat resumes its session and nothing is replayed' , { skip}, async t => { 164const first = await setup ( t ); 165const frames1 = await first . send ( 'chat-h-a06' , 'SCRIPT:tool again.txt once' , async f => { 166if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) await first . host . post ( '/api/chat/approval' , { sessionId :'chat-h-a06' , toolId :f . tool . id , decision :'approve' }); 167}); 168assert . equal ( frames1 . at ( - 1 ). type , 'done' ); 169const sessionBefore = JSON . parse ( readFileSync ( join ( first . home , 'data' , 'agent' , 'sessions.json' ), 'utf8' ))[ 'chat-h-a06' ]. sessionId ; 170await first . host . stop (); 171const second = await setup ( t , { reuse :{ worker :first . worker , home :first . home , connectionId :first . connectionId } }); 172const frames2 = await second . send ( 'chat-h-a06' , 'SCRIPT:echo back again' ); 173assert . equal ( text ( frames2 ), 'back again' ); 174assert . equal ( frames2 . filter ( f => f . type === 'agent-tool' ). length , 0 ); 175assert . equal ( lines ( join ( second . ws , 'again.txt' )), 1 , 'the first turn\'s tool did not run a second time' ); 176const sessionAfter = JSON . parse ( readFileSync ( join ( second . home , 'data' , 'agent' , 'sessions.json' ), 'utf8' ))[ 'chat-h-a06' ]. sessionId ; 177assert . equal ( sessionAfter , sessionBefore ); 178t . after (() => { cleanup ( first . home ); }); 179await first . worker . close (). catch (() => {}); 180}); 181 182test ( 'A08 over HTTP: two chats stream at the same time without mixing' , { skip}, async t => { 183const s = await setup ( t ); 184const [ a , b ] = await Promise . all ([ s . send ( 'chat-h-a08-a' , 'SCRIPT:slow 30' ), s . send ( 'chat-h-a08-b' , 'SCRIPT:echo only b' )]); 185assert . equal ( a . filter ( f => f . type === 'delta' ). length , 30 ); 186assert . equal ( text ( b ), 'only b' ); 187assert . ok ( ! text ( a ). includes ( 'only b' ) && ! text ( b ). includes ( 'w0' )); 188assert . notEqual ( a . find ( f => f . type === 'start' ). sessionId , b . find ( f => f . type === 'start' ). sessionId ); 189}); 190 191test ( '/goal over HTTP: shown, set with rounds that stream into the chat, and refused when one is unfinished' , { skip}, async t => { 192const s = await setup ( t ); 193const status = frames => frames . filter ( f => f . type === 'delta' ). map ( f => f . text ). join ( '' ); 194assert . match ( status ( await s . send ( 'chat-h-goal' , '/goal' )), / No goal is set / ); 195assert . match ( status ( await s . send ( 'chat-h-goal' , '/goal edit nothing' )), / no goal in this chat yet / i ); 196assert . equal (( await s . host . status ()). activeTurns , 0 ); 197}); 198 199test ( 'without the agent component the chat says so and still uses the model the user chose' , async t => { 200const s = await setup ( t , { harness :null }); 201const status = await s . host . status (); 202assert . equal ( status . state , 'unavailable' ); assert . match ( status . reason , / coding assistant / i ); 203const frames = await s . send ( 'chat-h-fallback' , 'SCRIPT:hello' ); 204const notice = frames . find ( f => f . type === 'notice' ); 205assert . equal ( notice . code , 'agent-unavailable' ); assert . match ( notice . message , / coding assistant isn.t installed / ); assert . match ( notice . message , / Chat works without it / ); 206assert . match ( notice . details , / agent component / , 'the technical text is kept apart as details' ); 207assert . equal ( frames . filter ( f => f . type === 'agent-tool' ). length , 0 ); 208assert . match ( text ( frames ), / Hello from the scripted worker / ); 209// The direct path used the API model the chat picked, nothing else. 210assert . ok ( s . worker . requests . length >= 1 && s . worker . requests . every ( q => q . model === 'cloud-model' )); 211}); 212 213test ( 'Mode over HTTP: the chat body carries the Mode menu choice; Plan refuses a write, Bypass writes, Manual asks' , { skip}, async t => { 214const s = await setup ( t ); 215const body = ( sessionId , message , mode ) => ({ sessionId, message, remoteModel :s . remoteModel , workspaceId :null , history :[], ...( mode ?{ mode} :{}) }); 216 217const plan = await s . host . chat ( body ( 'chat-h-plan' , 'SCRIPT:retrywrite plan-http.txt x' , 'plan' )); 218assert . equal ( plan . find ( f => f . type === 'start' ). mode , 'plan' ); 219assert . equal ( existsSync ( join ( s . ws , 'plan-http.txt' )), false ); 220assert . ok ( ! toolStates ( plan ). includes ( 'proposed' )); 221assert . equal ( toolStates ( plan ). at ( - 1 ), 'denied' ); 222 223const bypass = await s . host . chat ( body ( 'chat-h-bypass' , 'SCRIPT:retrywrite bypass-http.txt x' , 'bypass' )); 224assert . equal ( lines ( join ( s . ws , 'bypass-http.txt' )), 1 ); 225assert . ok ( ! toolStates ( bypass ). includes ( 'proposed' )); 226 227// No mode in the body (an older page) is Manual: it asks. 228let asked = false ; 229const manual = await s . host . chat ( body ( 'chat-h-manual' , 'SCRIPT:retrywrite manual-http.txt x' ), async f => { 230if ( f . type === 'agent-tool' && f . tool . state === 'proposed' && ! asked ) { 231asked = true ; 232assert . equal ( existsSync ( join ( s . ws , 'manual-http.txt' )), false ); 233await s . host . post ( '/api/chat/approval' , { sessionId :'chat-h-manual' , toolId :f . tool . id , decision :'approve' }); 234} 235}); 236assert . ok ( asked ); 237assert . equal ( manual . find ( f => f . type === 'start' ). mode , 'manual' ); 238assert . equal ( lines ( join ( s . ws , 'manual-http.txt' )), 1 ); 239assert . equal ( manual . filter ( f => f . type === 'agent-tool' ). at ( - 1 ). tool . approved , true ); 240}); 241 242test ( 'item 9: a chat that asks for no tools never runs one (agent:false and tools:false answer directly)' , { skip}, async t => { 243const s = await setup ( t ); 244for ( const [ chatId , flag ] of [[ 'chat-plain-a' , { agent :false }], [ 'chat-plain-t' , { tools :false }]]) { 245s . worker . requests . length = 0 ; 246const frames = await s . host . chat ({ sessionId :chatId , message :'SCRIPT:tool plain-never.txt x' , remoteModel :s . remoteModel , workspaceId :null , history :[], ...flag }); 247assert . equal ( frames . filter ( f => f . type === 'agent-tool' ). length , 0 , ` ${ chatId } : no tool card` ); 248assert . ok ( ! frames . some ( f => f . type === 'start' && f . agent === true ), ` ${ chatId } : not an agent turn` ); 249assert . ok ( ! frames . some ( f => f . type === 'notice' && f . code === 'agent-skipped' ), ` ${ chatId } : asking for plain chat is not a surprise to explain` ); 250assert . equal ( existsSync ( join ( s . ws , 'plain-never.txt' )), false ); 251assert . ok ( s . worker . requests . length >= 1 && s . worker . requests . every ( r => r . toolNames . length === 0 ), ` ${ chatId } : the model was offered no tool` ); 252} 253});