okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8667a3dbf
main
1/** 2* Settings -> Tools, behind the screen: what is saved, what reaches the agent, web search with no key, and the person's own tools. 3* 4* Pure tests always run. The two that start the real Harness need STRATA_HARNESS_DIR (the model is scripted; what is real is the Harness, 5* its web seam and tool executor, the Strata gate plugin, the bridge and the app's own tool server). 6*/ 7import test from 'node:test' ; 8import assert from 'node:assert/strict' ; 9import { spawn } from 'node:child_process' ; 10import { existsSync , mkdtempSync , mkdirSync , readFileSync , rmSync , writeFileSync } from 'node:fs' ; 11import { tmpdir } from 'node:os' ; 12import { join } from 'node:path' ; 13import { createInterface } from 'node:readline' ; 14import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 15import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 16import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 17import { buildProfile , CUSTOM_TOOLS_SCRIPT } from '../server/agent/profile.mjs' ; 18import { standardPreset } from '../server/agent/preset.mjs' ; 19import { TOOL_GROUPS } from '../server/agent/tools-catalog.mjs' ; 20import { createAgentTools } from '../server/agent/tools-settings.mjs' ; 21import { findBrowser , browserCandidates , findPlaywrightMcp } from '../server/agent/browser-probe.mjs' ; 22import { manualDecision , planDecision } from '../server/agent/plugins/strata-gate.mjs' ; 23import { createDuckDuckGoSearch , looksBlocked , parseHtmlResults , parseLiteResults , realUrl , BLOCKED_MESSAGE } from '../server/web-search-ddg.mjs' ; 24import { createExaSearch , createPerplexitySearch } from '../server/web-search-keyed.mjs' ; 25 26const HARNESS = process . env . STRATA_HARNESS_DIR ; 27const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 28const tmp = () => mkdtempSync ( join ( tmpdir (), 'strata-tools-set-' )); 29const cleanup = dir => { try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }; 30const make = ( dir , state = {}) => { let saved = state ; return { tools :createAgentTools ({ read :() => saved , write :v => { saved = v ; }, dataDir :dir }), saved :() => saved }; }; 31 32// ------------------------------------------------------------------------------------------------ the saved choices 33 34test ( 'Tools: every tool is on at first, in plain words, and turning one off or on is remembered' , () => { 35const dir = tmp (); 36try { 37const { tools} = make ( dir ); 38const v = tools . view (); 39assert . equal ( v . groups . length , TOOL_GROUPS . length ); 40assert . ok ( v . groups . every ( g => g . enabled && g . name && g . about && [ 'computer' , 'web' , 'together' ]. includes ( g . area ))); 41assert . equal ( v . search . provider , 'builtin' ); assert . equal ( v . search . keySet , false ); 42const off = tools . update ({ groups :{ jobs :false , search :false } }); 43assert . deepEqual ( off . groups . filter ( g => ! g . enabled ). map ( g => g . id ), [ 'jobs' , 'search' ]); 44assert . deepEqual ([ ...tools . profileView (). off ]. sort (), [ 'jobs' , 'search' ]); 45assert . ok ( tools . update ({ groups :{ jobs :true } }). groups . find ( g => g . id === 'jobs' ). enabled ); 46assert . throws (() => tools . update ({ groups :{ nonsense :false } }), / not known / ); 47} finally { cleanup ( dir ); } 48}); 49 50test ( 'Tools: a search key is saved for its service only, is never shown again, and is refused when it looks wrong' , () => { 51const dir = tmp (); 52try { 53const { tools, saved} = make ( dir ); 54tools . update ({ search :{ provider :'exa' } }); 55assert . throws (() => tools . update ({ search :{ key :'has a space' } }), / does not look right / ); 56const v = tools . update ({ search :{ key :'exa-key-123456' } }); 57assert . deepEqual ( v . search , { provider :'exa' , keySet :true }); 58assert . ok ( ! JSON . stringify ( v ). includes ( 'exa-key-123456' ), 'the screen never gets the key back' ); 59assert . equal ( tools . profileView (). search . key , 'exa-key-123456' ); 60assert . equal ( tools . update ({ search :{ provider :'perplexity' } }). search . keySet , false , 'a key belongs to its service' ); 61assert . throws (() => tools . update ({ search :{ provider :'bing' } }), / listed search services / ); 62assert . equal ( saved (). search . provider , 'perplexity' ); 63} finally { cleanup ( dir ); } 64}); 65 66test ( 'Tools: the person\'s own tools are checked in plain words and saved with the three ways of working' , () => { 67const dir = tmp (); 68try { 69const { tools} = make ( dir ); 70assert . throws (() => tools . addCustom ({ name :'' , about :'x' , kind :'instructions' , instructions :'y' }), / short name / ); 71assert . throws (() => tools . addCustom ({ name :'Notes' , about :'' , kind :'instructions' , instructions :'y' }), / what the tool does / ); 72assert . throws (() => tools . addCustom ({ name :'Notes' , about :'a' , kind :'instructions' , instructions :' ' }), / instructions / ); 73assert . throws (() => tools . addCustom ({ name :'Run' , about :'a' , kind :'command' , command :'a\nb' }), / one line / ); 74assert . throws (() => tools . addCustom ({ name :'Srv' , about :'a' , kind :'server' , address :'https://u:p@x.example/mcp' }), / user name or password / ); 75let v = tools . addCustom ({ name :'Release notes' , about :'Write release notes in our house style.' , kind :'instructions' , instructions :'Start with one line.' }); 76v = tools . addCustom ({ name :'Check site' , about :'Check that the site answers.' , kind :'command' , command :'curl -I https://example.com' }); 77v = tools . addCustom ({ name :'Issue tracker' , about :'Look up issues.' , kind :'server' , address :'https://issues.example/mcp' }); 78assert . deepEqual ( v . custom . map ( t => [ t . id , t . kind ]), [[ 'release_notes' , 'instructions' ], [ 'check_site' , 'command' ], [ 'issue_tracker' , 'server' ]]); 79assert . throws (() => tools . addCustom ({ name :'release notes' , about :'a' , kind :'instructions' , instructions :'y' }), / already have a tool / ); 80const p = tools . profileView (); 81assert . equal ( p . hasInstructionTools && p . hasCommandTools , true ); 82assert . deepEqual ( p . servers , { 'custom-issue-tracker' :{ url :'https://issues.example/mcp' } }); 83const file = JSON . parse ( readFileSync ( tools . filePath , 'utf8' )); 84assert . deepEqual ( Object . keys ( file . instructions ), [ 'release_notes' ]); assert . deepEqual ( Object . keys ( file . commands ), [ 'check_site' ]); 85v = tools . update ({ custom :{ check_site :false } }); 86assert . equal ( tools . profileView (). hasCommandTools , false ); assert . deepEqual ( JSON . parse ( readFileSync ( tools . filePath , 'utf8' )). commands , {}); 87v = tools . editCustom ( 'release_notes' , { name :'Release notes' , about :'Changed.' , kind :'instructions' , instructions :'New text.' }); 88assert . equal ( v . custom [ 0 ]. about , 'Changed.' ); 89v = tools . removeCustom ( 'issue_tracker' ); 90assert . equal ( v . custom . length , 2 ); 91assert . throws (() => tools . removeCustom ( 'nope' ), / not in your list / ); 92} finally { cleanup ( dir ); } 93}); 94 95// ---------------------------------------------------------------------------------------------- what the agent gets 96 97const entriesOf = profile => JSON . parse ( profile . patch . split ( '\n' ). slice ( 1 ). join ( '\n' )); 98const toolWeb = entries => entries . find ( e => e . id === 'preset-standard' ). config . plugins . find ( p => p . id === 'tool-web' ); 99 100test ( 'profile: web search is on with no key (DuckDuckGo), pinned so a second backend cannot make the choice ambiguous' , () => { 101const e = entriesOf ( buildProfile ({ local :[], connections :[] })); 102assert . equal ( toolWeb ( e ). config . search , true ); assert . equal ( toolWeb ( e ). config . fetch , true ); 103assert . deepEqual ( e . find ( x => x . id === 'web' ). config , { searchProvider :'strata-duckduckgo' , fetchProvider :'http' }); 104assert . equal ( e . find ( x => x . id === 'web-search-deepseek' ). disabled , true ); 105const plugin = e . flatMap ( x => x . insert ?? []). find ( x => x . id === 'strata-web-search' ); 106assert . ok ( existsSync ( plugin . name )); assert . equal ( plugin . config . provider , 'duckduckgo' ); 107}); 108 109test ( 'profile: a keyed service is used only with its key saved; the key travels in the environment and is in no file' , () => { 110const view = ( provider , key ) => ({ off :new Set (), search :{ provider, key}, servers :{}, hasInstructionTools :false , hasCommandTools :false , toolFile :null , browserEnabled :false }); 111const noKey = buildProfile ({ local :[], connections :[], tools :view ( 'exa' , '' ) }); 112assert . equal ( entriesOf ( noKey ). find ( x => x . id === 'web' ). config . searchProvider , 'strata-duckduckgo' , 'no key: DuckDuckGo, not a broken search' ); 113const exa = buildProfile ({ local :[], connections :[], tools :view ( 'exa' , 'exa-secret-key' ) }); 114assert . equal ( entriesOf ( exa ). find ( x => x . id === 'web' ). config . searchProvider , 'exa' ); 115assert . equal ( exa . env . STRATA_SEARCH_KEY , 'exa-secret-key' ); assert . ok ( ! exa . patch . includes ( 'exa-secret-key' )); 116const ds = buildProfile ({ local :[], connections :[], tools :view ( 'deepseek' , 'ds-secret' ) }); 117assert . deepEqual ( entriesOf ( ds ). find ( x => x . id === 'web-search-deepseek' ). config , { apiKeyEnv :'STRATA_SEARCH_KEY' }); 118assert . equal ( entriesOf ( ds ). find ( x => x . id === 'web' ). config . searchProvider , 'deepseek-official' ); 119assert . notEqual ( noKey . signature , exa . signature , 'a changed choice restarts the agent' ); 120}); 121 122test ( 'profile: the groups switched off are not loaded; both web halves off drops the web plugin' , () => { 123const base = { servers :{}, hasInstructionTools :false , hasCommandTools :false , toolFile :null , browserEnabled :false , search :{ provider :'builtin' , key :'' } }; 124const ids = off => standardPreset ({ off :new Set ( off ), search :true }). plugins . map ( p => p . id ); 125assert . ok ( ! ids ([ 'shell' ]). includes ( 'tool-pwsh' ) && ! ids ([ 'shell' ]). includes ( 'tool-bash' )); 126assert . ok ( ! ids ([ 'helpers' ]). includes ( 'delegation' ) && ids ([ 'helpers' ]). includes ( 'tool-fs' )); 127assert . ok ( ! ids ([ 'goals' ]). includes ( 'tool-goal' ) && ! ids ([ 'goals' ]). includes ( 'command-goal' )); 128assert . ok ( ids ([ 'fetch' ]). includes ( 'tool-web' ) && ! ids ([ 'fetch' , 'search' ]). includes ( 'tool-web' )); 129const e = entriesOf ( buildProfile ({ local :[], connections :[], tools :{ ...base , off :new Set ([ 'search' ]) } })); 130assert . equal ( toolWeb ( e ). config . search , false ); 131assert . equal ( e . find ( x => x . id === 'web' ), undefined , 'no search service is set up when search is off' ); 132}); 133 134test ( 'profile: the person\'s instruction and command tools are the app\'s own tool server; a person\'s server is a connected tool' , () => { 135const dir = tmp (); 136try { 137const { tools} = make ( dir ); 138tools . addCustom ({ name :'Notes' , about :'a' , kind :'instructions' , instructions :'text' }); 139tools . addCustom ({ name :'Run it' , about :'a' , kind :'command' , command :'echo hi' }); 140tools . addCustom ({ name :'Remote' , about :'a' , kind :'server' , address :'https://r.example/mcp' }); 141const e = entriesOf ( buildProfile ({ local :[], connections :[], tools :tools . profileView () })); 142const rows = e . flatMap ( x => x . insert ?? []). filter ( r => r . name === '@deepseek-ai/dsh-mcp-client' ); 143assert . deepEqual ( rows . map ( r => r . config . serverName ). sort (), [ 'custom-remote' , 'strata-commands' , 'strata-instructions' ]); 144const own = rows . find ( r => r . config . serverName === 'strata-commands' ). config ; 145assert . deepEqual ([ own . command , own . args [ 0 ], own . args [ 1 ]], [ process . execPath , CUSTOM_TOOLS_SCRIPT , 'commands' ]); 146} finally { cleanup ( dir ); } 147}); 148 149test ( 'the gate: instruction tools only hand back text, so they do not ask; commands, servers and the browser ask in Manual and are refused in Plan' , () => { 150assert . equal ( manualDecision ({ name :'mcp__strata-instructions__notes' , arguments :{} }), null ); 151assert . equal ( manualDecision ({ name :'mcp__strata-commands__run_it' , arguments :{} })?. kind , 'ask' ); 152assert . equal ( manualDecision ({ name :'mcp__strata-commands__check_site' , arguments :{ input :'example.com' } }). reason , 'Run your tool “check site” with: example.com' ); 153assert . equal ( manualDecision ({ name :'mcp__custom-remote__lookup' , arguments :{} })?. kind , 'ask' ); 154assert . equal ( planDecision ({ name :'mcp__strata-instructions__notes' }), null ); 155assert . equal ( planDecision ({ name :'read' }), null ); 156for ( const name of [ 'mcp__strata-commands__run_it' , 'mcp__custom-remote__lookup' , 'mcp__browser__browser_navigate' ]) assert . equal ( planDecision ({ name})?. kind , 'deny' , name ); 157assert . match ( planDecision ({ name :'mcp__x__y' }). reason , / Plan mode only looks / ); 158}); 159 160// ------------------------------------------------------------------------------------------------- web search alone 161 162const HTML = `<div class="result results_links results_links_deep web-result"> 163<div class="links_main links_deep result__body"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1&rut=abc">Example <b>Domain</b> & more</a></h2> 164<a class="result__snippet" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa">A <b>short</b> snippet 'quoted'.</a></div></div> 165<div class="result result--ad"><h2 class="result__title"><a rel="nofollow" class="result__a" href="https://duckduckgo.com/y.js?ad_domain=ad.example">An ad</a></h2></div> 166<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fsecond.example%2F">Second</a></h2> 167<a class="result__snippet" href="x">Second snippet</a></div>` ; 168const LITE = `<table><tr><td>1. </td><td><a rel="nofollow" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Flite.example%2F" class='result-link'>Lite <b>title</b></a></td></tr> 169<tr><td class='result-snippet'>Lite snippet text</td></tr> 170<tr><td>2. </td><td><a rel="nofollow" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Flite2.example%2F" class='result-link'>Lite two</a></td></tr></table>` ; 171 172test ( 'search: the DuckDuckGo result list is read into titles, addresses and snippets; ads and internal links are dropped' , () => { 173const rows = parseHtmlResults ( HTML ); 174assert . deepEqual ( rows , [ 175{ url :'https://example.com/a?x=1' , title :'Example Domain & more' , snippet :"A short snippet 'quoted'." }, 176{ url :'https://second.example/' , title :'Second' , snippet :'Second snippet' }, 177]); 178assert . deepEqual ( parseLiteResults ( LITE ). map ( r => [ r . url , r . title , r . snippet ]), [[ 'https://lite.example/' , 'Lite title' , 'Lite snippet text' ], [ 'https://lite2.example/' , 'Lite two' , undefined ]]); 179assert . equal ( realUrl ( '//duckduckgo.com/l/?uddg=https%3A%2F%2Fa.example%2F' ), 'https://a.example/' ); 180assert . equal ( realUrl ( 'https://duckduckgo.com/y.js?x=1' ), null ); 181assert . equal ( realUrl ( 'javascript:alert(1)' ), null ); 182}); 183 184test ( 'search: a human check or a refusal is told in plain words, and a real search with no hits is an answer, not an error' , async () => { 185assert . equal ( looksBlocked ( 202 , '' ), true ); assert . equal ( looksBlocked ( 429 , '' ), true ); 186assert . equal ( looksBlocked ( 200 , '<div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too</div>' ), true ); 187assert . equal ( looksBlocked ( 200 , HTML ), false ); 188const sleeps = []; 189const tick = () => { let t = 1_000_000 ; return { now :() => t , sleep :async ms => { sleeps . push ( ms ); t += ms ; } }; }; 190const blocked = createDuckDuckGoSearch ({ ...tick (), fetch :async () => new Response ( '<html>captcha anomaly-modal</html>' , { status :200 }) }); 191await assert . rejects ( blocked . search ({ query :'x' }), e => e . message === BLOCKED_MESSAGE && e . code === 'WEB_RATE_LIMITED' ); 192const empty = createDuckDuckGoSearch ({ ...tick (), fetch :async () => new Response ( '<html><body>No results.</body></html>' , { status :200 }) }); 193assert . deepEqual ( await empty . search ({ query :'zzzz' }), { sources :[], truncated :false }); 194const offline = createDuckDuckGoSearch ({ ...tick (), fetch :async () => { throw new TypeError ( 'fetch failed' ); } }); 195await assert . rejects ( offline . search ({ query :'x' }), / could not reach the internet / ); 196}); 197 198test ( 'search: polite by design: one request at a time, spaced out, a minute limit, and the same query is answered from a short cache' , async () => { 199let clock = 1_000_000 , calls = 0 ; 200const waits = []; 201const provider = createDuckDuckGoSearch ({ 202now :() => clock , sleep :async ms => { waits . push ( ms ); clock += ms ; }, 203fetch :async ( url , init ) => { calls ++ ; assert . equal ( init . method , 'POST' ); assert . match ( init . headers [ 'user-agent' ], / Mozilla / ); assert . match ( String ( url ), / duckduckgo\.com / ); return new Response ( HTML , { status :200 }); }, 204}); 205const a = await provider . search ({ query :'Strata engine' , maxResults :1 }); 206assert . equal ( a . sources . length , 1 ); 207await provider . search ({ query :'strata ENGINE' }); // same words: from the cache 208assert . equal ( calls , 1 ); 209await provider . search ({ query :'another one' }); 210assert . equal ( calls , 2 ); assert . ok ( waits . some ( ms => ms >= 1400 ), 'the second request waited for the gap' ); 211for ( let i = 0 ; i < 25 ; i ++ ) { try { await provider . search ({ query :`q ${ i } ` }); } catch ( e ) { assert . equal ( e . code , 'WEB_RATE_LIMITED' ); break ; } } 212assert . ok ( calls <= 23 , 'no more than about 20 a minute' ); 213}); 214 215test ( 'search: Exa and Perplexity use the person\'s key, map their answers, and say plainly when the key is refused' , async () => { 216const real = globalThis . fetch ; 217try { 218globalThis . fetch = async ( url , init ) => { 219assert . equal ( init . headers . authorization , 'Bearer the-key' ); 220if ( String ( url ). includes ( 'exa.ai' )) return new Response ( JSON . stringify ({ results :[{ url :'https://e.example' , title :'E' , highlights :[ 'hl' ] }, { url :'https://no-snippet.example' , highlights :[] }] })); 221return new Response ( JSON . stringify ({ choices :[{ message :{ content :'Answer.' } }], search_results :[{ url :'https://p.example' , title :'P' , snippet :'s' }] })); 222}; 223assert . deepEqual (( await createExaSearch ({ key :'the-key' }). search ({ query :'q' })). sources , [{ url :'https://e.example' , title :'E' , snippet :'hl' }]); 224const p = await createPerplexitySearch ({ key :() => 'the-key' }). search ({ query :'q' }); 225assert . equal ( p . content , 'Answer.' ); assert . equal ( p . sources [ 0 ]. url , 'https://p.example' ); 226assert . equal ( createExaSearch ({ key :() => '' }). available (), false ); 227globalThis . fetch = async () => new Response ( '{}' , { status :401 }); 228await assert . rejects ( createExaSearch ({ key :'the-key' }). search ({ query :'q' }), / did not accept the key / ); 229} finally { globalThis . fetch = real ; } 230}); 231 232// ------------------------------------------------------------------------------------------------------- browser probe 233 234test ( 'browser: Chrome, then Edge, then Chromium; nothing found says so' , () => { 235const win = { PROGRAMFILES :'C:\\Program Files' , LOCALAPPDATA :'C:\\Users\\x\\AppData\\Local' }; 236assert . equal ( browserCandidates ( 'win32' , win )[ 0 ]. name , 'Google Chrome' ); 237assert . deepEqual ( findBrowser ({ platform :'win32' , env :win , exists :p => / msedge\.exe$ / . test ( p ) }). name , 'Microsoft Edge' ); 238assert . equal ( findBrowser ({ platform :'win32' , env :win , exists :() => false }). found , false ); 239assert . equal ( findBrowser ({ platform :'darwin' , exists :p => p . includes ( 'Google Chrome' ) }). found , true ); 240}); 241 242// ------------------------------------------------------------------------------------ the app's own tool server (MCP) 243 244function mcpSession ( dir , mode ) { 245const child = spawn ( process . execPath , [ CUSTOM_TOOLS_SCRIPT , mode , join ( dir , 'agent' , 'custom-tools.json' )], { stdio :[ 'pipe' , 'pipe' , 'inherit' ], windowsHide :true }); 246const waiting = new Map (); 247createInterface ({ input :child . stdout }). on ( 'line' , line => { const m = JSON . parse ( line ); waiting . get ( m . id )?.( m ); }); 248let id = 0 ; 249const ask = ( method , params ) => new Promise ( resolve => { const n = ++ id ; waiting . set ( n , resolve ); child . stdin . write ( JSON . stringify ({ jsonrpc :'2.0' , id :n , method, params}) + '\n' ); }); 250return { ask, close :() => child . kill () }; 251} 252 253test ( 'tool server: instruction tools return the person\'s text; command tools run their command with the assistant\'s text only in STRATA_INPUT' , async () => { 254const dir = tmp (); 255try { 256const script = join ( dir , 'show.mjs' ); 257writeFileSync ( script , "console.log('got:' + process.env.STRATA_INPUT); if (process.env.STRATA_INPUT === 'fail') process.exit(3);" ); 258const { tools} = make ( dir ); 259tools . addCustom ({ name :'Notes' , about :'House style.' , kind :'instructions' , instructions :'Start with one line.' }); 260tools . addCustom ({ name :'Show' , about :'Shows its input.' , kind :'command' , command :`" ${ process . execPath } " " ${ script } "` }); 261const instr = mcpSession ( dir , 'instructions' ); 262try { 263assert . equal (( await instr . ask ( 'initialize' , { protocolVersion :'2024-11-05' })). result . serverInfo . name , 'strata-instructions' ); 264const list = ( await instr . ask ( 'tools/list' )). result . tools ; 265assert . deepEqual ( list . map ( t => [ t . name , t . description ]), [[ 'notes' , 'House style.' ]]); 266assert . equal (( await instr . ask ( 'tools/call' , { name :'notes' , arguments :{} })). result . content [ 0 ]. text , 'Start with one line.' ); 267} finally { instr . close (); } 268const cmd = mcpSession ( dir , 'commands' ); 269try { 270await cmd . ask ( 'initialize' , {}); 271assert . deepEqual (( await cmd . ask ( 'tools/list' )). result . tools . map ( t => t . name ), [ 'show' ]); 272const ok = ( await cmd . ask ( 'tools/call' , { name :'show' , arguments :{ input :'hello; echo HACKED' } })). result ; 273assert . equal ( ok . isError , false ); assert . equal ( ok . content [ 0 ]. text , 'got:hello; echo HACKED' , 'the text is data, never a command' ); 274const bad = ( await cmd . ask ( 'tools/call' , { name :'show' , arguments :{ input :'fail' } })). result ; 275assert . equal ( bad . isError , true ); 276assert . match (( await cmd . ask ( 'tools/call' , { name :'gone' , arguments :{} })). result . content [ 0 ]. text , / no longer available / ); 277tools . update ({ custom :{ show :false } }); 278assert . deepEqual (( await cmd . ask ( 'tools/list' )). result . tools , [], 'a change in Settings is seen without a restart' ); 279} finally { cmd . close (); } 280} finally { cleanup ( dir ); } 281}); 282 283// ------------------------------------------------------------------------------------------------- real Harness 284 285async function rig ( t , setup ) { 286const worker = await startScriptedWorker ({}); 287const dir = tmp (); 288const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 289const { tools} = make ( dir ); 290setup ?.( tools , dir ); 291const local = [{ id :'inst-1' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots :2 }]; 292const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => [], tools :() => tools . profileView (), env :process . env , startTimeoutMs :90_000 }); 293t . after ( async () => { await bridge . close (); await worker . close (); cleanup ( dir ); }); 294const run = async ( chatId , tool , args , { mode= 'bypass' , answer} = {}) => { 295const frames = []; 296await bridge . runTurn ({ chatId, message :`SCRIPT:call ${ tool } ${ JSON . stringify ( args )} ` , workspacePath :ws , mode, onFrame :f => { 297frames . push ( f ); 298if ( answer && f . type === 'agent-tool' && f . tool . state === 'proposed' ) void bridge . approve ({ chatId, callId :f . tool . id , decision :answer }). catch (() => {}); 299} }); 300return frames . filter ( f => f . type === 'agent-tool' ). map ( f => f . tool ); 301}; 302return { worker, bridge, tools, dir, ws, run, offered :() => [ ...worker . requests ]. reverse (). find ( q => q . toolNames . length )?. toolNames . sort () }; 303} 304 305test ( 'real Harness: the person\'s own tools are offered; an instruction tool never asks, a command asks in Manual and is refused in Plan' , { skip}, async ( t ) => { 306const r = await rig ( t , ( tools , dir ) => { 307const script = join ( dir , 'touch.mjs' ); 308writeFileSync ( script , "import { writeFileSync } from 'node:fs'; writeFileSync(process.argv[2], 'ran'); console.log('ok:' + process.env.STRATA_INPUT);" ); 309tools . addCustom ({ name :'House style' , about :'Write in our house style.' , kind :'instructions' , instructions :'Always start with one line.' }); 310tools . addCustom ({ name :'Make marker' , about :'Writes a marker file.' , kind :'command' , command :`" ${ process . execPath } " " ${ script } " " ${ join ( dir , 'marker.txt' )} "` }); 311}); 312const marker = join ( r . dir , 'marker.txt' ); 313const first = await r . run ( 'c1' , 'mcp__strata-instructions__house_style' , {}, { mode :'manual' }); 314assert . ok ( r . offered (). includes ( 'mcp__strata-instructions__house_style' ) && r . offered (). includes ( 'mcp__strata-commands__make_marker' ), 'both of the person\'s tools are offered' ); 315assert . ok ( ! first . some ( c => c . state === 'proposed' ), 'an instruction tool never asks' ); 316assert . match ( first . at ( - 1 ). result , / Always start with one line / ); 317const plan = await r . run ( 'c2' , 'mcp__strata-commands__make_marker' , { input :'p' }, { mode :'plan' }); 318assert . ok ( ! existsSync ( marker ), 'Plan mode refused the command' ); 319assert . ok ( ! plan . some ( c => c . state === 'done' && / ok: / . test ( c . result ?? '' ))); 320const denied = await r . run ( 'c3' , 'mcp__strata-commands__make_marker' , { input :'d' }, { mode :'manual' , answer :'deny' }); 321assert . ok ( denied . some ( c => c . state === 'proposed' ) && ! existsSync ( marker ), 'Manual asked first, and a No ran nothing' ); 322const approved = await r . run ( 'c4' , 'mcp__strata-commands__make_marker' , { input :'yes' }, { mode :'manual' , answer :'approve' }); 323assert . ok ( approved . some ( c => c . state === 'proposed' )); 324assert . equal ( approved . at ( - 1 ). state , 'done' ); assert . match ( approved . at ( - 1 ). result , / ok:yes / ); assert . ok ( existsSync ( marker )); 325}); 326 327test ( 'real Harness: switching a tool off in Settings takes it away from the next message; web search is there with no key' , { skip}, async ( t ) => { 328const r = await rig ( t ); 329await r . run ( 'o1' , 'read' , { file_path :join ( r . ws , 'nothing.txt' ) }); 330const before = r . offered (); 331assert . ok ( before . includes ( 'web_search' ) && before . includes ( 'web_fetch' ) && before . includes ( 'subagent' ) && before . includes ( 'job_list' )); 332r . tools . update ({ groups :{ jobs :false , helpers :false , search :false } }); 333await r . run ( 'o2' , 'read' , { file_path :join ( r . ws , 'nothing.txt' ) }); 334const after = r . offered (); 335assert . ok ( ! after . includes ( 'web_search' ) && ! after . includes ( 'subagent' ) && ! after . includes ( 'job_list' ), 'the three groups are gone' ); 336assert . ok ( after . includes ( 'web_fetch' ) && after . includes ( 'read' ) && after . includes ( 'pwsh' ) !== after . includes ( 'bash' ), 'the rest stays' ); 337}); 338 339// ------------------------------------------------------------------------------------------------------------ browser 340 341test ( 'gate: in Manual the browser asks before opening a page, clicking or typing, and not before looking; Plan refuses it' , () => { 342const nav = manualDecision ({ name :'mcp__browser__browser_navigate' , arguments :{ url :'https://example.com/a' } }); 343assert . equal ( nav . kind , 'ask' ); assert . equal ( nav . reason , 'Open the web page https://example.com/a' ); 344assert . match ( manualDecision ({ name :'mcp__browser__browser_click' , arguments :{ element :'Sign in button' } }). reason , / ^Click on the page: Sign in button / ); 345assert . match ( manualDecision ({ name :'mcp__browser__browser_type' , arguments :{ element :'Search box' } }). reason , / ^Type into the page / ); 346assert . equal ( manualDecision ({ name :'mcp__browser__browser_file_upload' , arguments :{} }). kind , 'ask' ); 347assert . match ( manualDecision ({ name :'mcp__browser__browser_evaluate' , arguments :{} }). reason , / small program / ); 348for ( const name of [ 'browser_snapshot' , 'browser_take_screenshot' , 'browser_console_messages' , 'browser_network_requests' , 'browser_wait_for' ]) assert . equal ( manualDecision ({ name :`mcp__browser__ ${ name } ` , arguments :{} }), null , name ); 349assert . equal ( manualDecision ({ name :'mcp__browser__browser_tabs' , arguments :{ action :'list' } }), null ); 350assert . equal ( manualDecision ({ name :'mcp__browser__browser_tabs' , arguments :{ action :'close' } }). kind , 'ask' ); 351assert . equal ( planDecision ({ name :'mcp__browser__browser_snapshot' }). kind , 'deny' ); 352}); 353 354test ( 'browser: the tool server is found in the agent component; the screen can say what is missing' , () => { 355const exists = p => p . replaceAll ( String . fromCharCode ( 92 ), '/' ). endsWith ( '/node_modules/@playwright/mcp/cli.js' ) && p . replaceAll ( String . fromCharCode ( 92 ), '/' ). includes ( '/pkg/node_modules/@playwright/' ); 356assert . equal ( findPlaywrightMcp ( '' , {}), null ); 357assert . ok ( findPlaywrightMcp ( '/pkg' , { exists}). replaceAll ( String . fromCharCode ( 92 ), '/' ). endsWith ( '/pkg/node_modules/@playwright/mcp/cli.js' )); 358assert . equal ( findPlaywrightMcp ( '/nowhere' , { exists :() => false , list :() => { throw new Error ( 'none' ); } }), null ); 359const dir = tmp (); 360try { 361const only = createAgentTools ({ read :() => ({ browser :{ enabled :true } }), write :() => {}, dataDir :dir , browser :() => ({ found :true , name :'Google Chrome' , path :'C:/chrome.exe' , cli :null }) }); 362assert . deepEqual ( only . view (). browser , { enabled :true , found :false , name :'Google Chrome' , missing :'component' }); 363assert . equal ( only . profileView (). browserEnabled , false , 'no tool server, no browser rows' ); 364const ready = createAgentTools ({ read :() => ({ browser :{ enabled :true } }), write :() => {}, dataDir :dir , browser :() => ({ found :true , name :'Google Chrome' , path :'C:/chrome.exe' , cli :'C:/pw/cli.js' }) }); 365assert . equal ( ready . view (). browser . found , true ); 366const rows = entriesOf ( buildProfile ({ local :[], connections :[], tools :ready . profileView () })). flatMap ( x => x . insert ?? []). filter ( r => r . config ?. serverName === 'browser' ); 367assert . equal ( rows . length , 1 ); 368assert . deepEqual ( rows [ 0 ]. config . args , [ 'C:/pw/cli.js' , '--browser' , 'chromium' , '--isolated' , '--executable-path' , 'C:/chrome.exe' ]); 369const off = createAgentTools ({ read :() => ({ browser :{ enabled :false } }), write :() => {}, dataDir :dir , browser :() => ({ found :true , name :'x' , path :'p' , cli :'c' }) }); 370assert . equal ( entriesOf ( buildProfile ({ local :[], connections :[], tools :off . profileView () })). flatMap ( x => x . insert ?? []). some ( r => r . config ?. serverName === 'browser' ), false ); 371} finally { cleanup ( dir ); } 372}); 373 374const browserNow = findBrowser (); 375const playwrightCli = HARNESS ?findPlaywrightMcp ( HARNESS ) :null ; 376// Opt-in: it starts a real (headless) Chrome, which a test run must not do on someone's PC unasked. 377const browserSkip = process . env . STRATA_TEST_BROWSER !== '1' ?'starts a real browser: set STRATA_TEST_BROWSER=1' :skip || ! browserNow . found || ! playwrightCli ?'needs STRATA_HARNESS_DIR with the browser tool server and Chrome or Edge on this computer' :false ; 378 379test ( 'real browser: the assistant opens a local page in the person\'s Chrome or Edge and reads it; Manual asks before opening it, Plan refuses' , { skip :browserSkip , timeout :240000 }, async ( t ) => { 380const http = await import ( 'node:http' ); 381const page = http . createServer (( req , res ) => { res . setHeader ( 'content-type' , 'text/html' ); res . end ( '<html><head><title>Strata browser test</title></head><body><h1>Hello from the browser test</h1><button>Press me</button></body></html>' ); }); 382await new Promise ( r => page . listen ( 0 , '127.0.0.1' , r )); 383t . after (() => page . close ()); 384const url = `http://127.0.0.1: ${ page . address (). port } /` ; 385const previous = process . env . STRATA_BROWSER_HEADLESS ; 386process . env . STRATA_BROWSER_HEADLESS = '1' ; 387t . after (() => { if ( previous === undefined ) delete process . env . STRATA_BROWSER_HEADLESS ; else process . env . STRATA_BROWSER_HEADLESS = previous ; }); 388const worker = await startScriptedWorker ({}); 389const dir = tmp (); 390const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 391const real = createAgentTools ({ read :() => ({ browser :{ enabled :true } }), write :() => {}, dataDir :dir , browser :() => ({ ...browserNow , cli :playwrightCli }) }); 392const local = [{ id :'inst-b' , label :'Scripted' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots :2 }]; 393const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => local , connections :() => [], tools :() => real . profileView (), env :process . env , startTimeoutMs :120_000 }); 394t . after ( async () => { await bridge . close (); await worker . close (); cleanup ( dir ); }); 395const go = async ( chatId , tool , args , mode , answer ) => { 396const frames = []; 397await bridge . runTurn ({ chatId, message :`SCRIPT:call ${ tool } ${ JSON . stringify ( args )} ` , workspacePath :ws , mode, onFrame :f => { 398frames . push ( f ); 399if ( answer && f . type === 'agent-tool' && f . tool . state === 'proposed' ) void bridge . approve ({ chatId, callId :f . tool . id , decision :answer }). catch (() => {}); 400} }); 401return frames . filter ( f => f . type === 'agent-tool' ). map ( f => f . tool ); 402}; 403const plan = await go ( 'b0' , 'mcp__browser__browser_navigate' , { url}, 'plan' ); 404assert . ok ( ! plan . some ( c => c . state === 'done' && / Hello from the browser test / . test ( c . result ?? '' )), 'Plan did not open the page' ); 405const denied = await go ( 'b1' , 'mcp__browser__browser_navigate' , { url}, 'manual' , 'deny' ); 406assert . ok ( denied . some ( c => c . state === 'proposed' && / Open the web page / . test ( c . effect ?? '' )), 'Manual asked first' ); 407const opened = await go ( 'b2' , 'mcp__browser__browser_navigate' , { url}, 'manual' , 'approve' ); 408assert . ok ( opened . some ( c => c . state === 'proposed' )); 409assert . equal ( opened . at ( - 1 ). state , 'done' ); 410const looked = await go ( 'b2' , 'mcp__browser__browser_snapshot' , {}, 'manual' , 'approve' ); 411assert . ok ( ! looked . some ( c => c . state === 'proposed' ), 'looking at the page does not ask' ); 412assert . match ( looked . at ( - 1 ). result , / Hello from the browser test / ); 413});