okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1631a9fde
main
1/** 2* Manual mode asks once per chat before the first web search or web page. Approve holds for the rest of that chat, Deny gives the model a 3* readable refusal, Plan and Bypass are unchanged, and a switch in Settings -> Tools (off by default) skips the question. 4* 5* The gate is plain ESM, so most of this drives its plugin with a pretend Harness context. The bridge-level tests at the end use the real 6* Harness with a scripted model and skip without STRATA_HARNESS_DIR. 7*/ 8import test from 'node:test' ; 9import assert from 'node:assert/strict' ; 10import { mkdtempSync , mkdirSync , rmSync } from 'node:fs' ; 11import { tmpdir } from 'node:os' ; 12import { join } from 'node:path' ; 13import { build } from 'esbuild' ; 14import { apply , manualDecision , planDecision , READ_ONLY_TOOLS , MANUAL_PRESET , PLAN_PRESET , WEB_REFUSAL } from '../server/agent/plugins/strata-gate.mjs' ; 15import { buildProfile } from '../server/agent/profile.mjs' ; 16import { createAgentTools } from '../server/agent/tools-settings.mjs' ; 17import { startScriptedWorker } from './helpers/scripted-worker.mjs' ; 18import { createAgentBridge } from '../server/agent/agent-bridge.mjs' ; 19import { createAgentTaskRunner } from '../server/agent/task-run.mjs' ; 20import { resolveHarness } from '../server/agent/harness-runtime.mjs' ; 21 22const HARNESS = process . env . STRATA_HARNESS_DIR ; 23const skip = ! HARNESS || ! resolveHarness ({ env :process . env }). ok ?'STRATA_HARNESS_DIR is not set to a built Harness' :false ; 24 25const SEARCH = { name :'web_search' , arguments :{ queries :[ 'heat pump prices' ] } }; 26const FETCH = { name :'web_fetch' , arguments :{ url :'https://example.com/a' } }; 27 28// ---------------------------------------------------------------------------------------------- the question 29 30test ( 'the question says what leaves this computer and where it goes' , () => { 31const ask = manualDecision ( SEARCH , { provider :'DuckDuckGo' }); 32assert . equal ( ask . kind , 'ask' ); 33assert . equal ( ask . reason , 'The assistant wants to search the web for: heat pump prices. Search words go to DuckDuckGo.' ); 34assert . equal ( manualDecision ({ name :'web_search' , arguments :{ queries :[ 'a' , 'b' ] } }, { provider :'Exa' }). reason , 'The assistant wants to search the web for: a; b. Search words go to Exa.' ); 35assert . equal ( manualDecision ( FETCH ). reason , "The assistant wants to open the web page https://example.com/a. The page's site sees the request." ); 36assert . ok ( ! READ_ONLY_TOOLS . has ( 'web_search' ) && ! READ_ONLY_TOOLS . has ( 'web_fetch' ), 'the web is no longer "look only"' ); 37// a very long query is cut, not pasted whole into the card 38assert . ok ( manualDecision ({ name :'web_search' , arguments :{ queries :[ 'x' . repeat ( 900 )] } }). reason . length < 300 ); 39}); 40 41test ( 'Plan keeps its rules: the web needs no question there' , () => { 42assert . equal ( planDecision ( SEARCH ), null ); 43assert . equal ( planDecision ( FETCH ), null ); 44}); 45 46// ---------------------------------------------------------------------------------------------- the gate 47 48/** A pretend Harness: enough of the context for the gate. `answers` is what the person says to each question, in order. */ 49function rig ({ preset= MANUAL_PRESET , answers= [ 'allowed-once' ], config= {} } = {}) { 50const handlers = []; 51const sessions = new Map (); 52const asked = []; 53let policy = new Map (); 54const ctx = { 55sessions :{ get :id => sessions . get ( id ) }, 56permissionPresets :{ current :session => session . preset ?? preset }, 57approval :{ 58overrideOf :session => policy . get ( session . id ) ?? null , 59request :async req => { asked . push ( req . reason ); await new Promise ( r => setTimeout ( r , 5 )); return answers [ Math . min ( asked . length - 1 , answers . length - 1 )]; }, 60}, 61on :( event , handler ) => { if ( event === 'tools/pre-execute' ) handlers . push ( handler ); }, 62inject :() => {}, 63}; 64apply ( ctx , config ); 65const session = ( id , extra = {}) => { const s = { id, header :{}, append :( type , data ) => { if ( type === 'approval/policy' ) policy . set ( id , data . policy ); }, ...extra }; sessions . set ( id , s ); return s ; }; 66const call = async ( sessionObj , exec ) => { 67let n = 0 ; 68const result = await handlers [ 0 ]({ ...exec , callId :`c ${ ++ n } ${ Math . random ()} ` , agent :{ session :sessionObj } }, async () => ({ kind :'allow' })); 69return result ; 70}; 71return { ctx, session, call, asked}; 72} 73 74test ( 'Manual: the first search asks, Approve lets the rest of that chat search and open pages without asking again' , async () => { 75const r = rig ({ config :{ web :{ provider :'DuckDuckGo' } } }); 76const chat = r . session ( 'chat-1' ); 77const first = await r . call ( chat , SEARCH ); 78assert . deepEqual ( r . asked , [ 'The assistant wants to search the web for: heat pump prices. Search words go to DuckDuckGo.' ]); 79assert . equal ( first . kind , 'allow' , 'approved, so the search runs' ); 80assert . equal (( await r . call ( chat , { name :'web_search' , arguments :{ queries :[ 'another' ] } })). kind , 'allow' ); 81assert . equal (( await r . call ( chat , FETCH )). kind , 'allow' ); 82assert . equal ( r . asked . length , 1 , 'one question for the chat' ); 83// another chat asks for itself 84await r . call ( r . session ( 'chat-2' ), SEARCH ); 85assert . equal ( r . asked . length , 2 ); 86}); 87 88test ( 'Manual: Deny gives the model a readable refusal, and the next try asks again' , async () => { 89const r = rig ({ answers :[ 'rejected' , 'allowed-once' ] }); 90const chat = r . session ( 'chat-1' ); 91const refused = await r . call ( chat , SEARCH ); 92assert . equal ( refused . kind , 'deny' ); 93assert . equal ( refused . reason , WEB_REFUSAL ); 94assert . match ( refused . reason , / did not allow web access / ); 95assert . match ( refused . reason , / Go on without it and say so / ); 96assert . doesNotMatch ( refused . reason , / tool " | web_search / , 'no tool names in what the model reads' ); 97assert . equal (( await r . call ( chat , SEARCH )). kind , 'allow' , 'asked again, and this time yes' ); 98assert . equal ( r . asked . length , 2 ); 99// an unavailable approval channel is a refusal too, not a silent allow 100const none = rig ({ answers :[ 'unavailable' ] }); 101assert . equal (( await none . call ( none . session ( 'c' ), SEARCH )). reason , WEB_REFUSAL ); 102}); 103 104test ( 'two searches started together share one question' , async () => { 105const r = rig (); 106const chat = r . session ( 'chat-1' ); 107const [ a , b ] = await Promise . all ([ r . call ( chat , SEARCH ), r . call ( chat , { name :'web_search' , arguments :{ queries :[ 'second' ] } })]); 108assert . equal ( r . asked . length , 1 ); 109assert . equal ( a . kind , 'allow' ); assert . equal ( b . kind , 'allow' ); 110}); 111 112test ( 'a helper agent works under the chat that started it: one yes covers both, and its question can reach the person' , async () => { 113const r = rig (); 114const chat = r . session ( 'chat-1' ); 115const helper = r . session ( 'helper-1' , { header :{ origin :'subagent' , parentSession :'chat-1' } }); 116assert . equal (( await r . call ( helper , SEARCH )). kind , 'allow' ); 117assert . equal ( r . ctx . approval . overrideOf ( helper ), 'ask' , 'the helper is set to ask so the card reaches the person' ); 118assert . equal (( await r . call ( chat , SEARCH )). kind , 'allow' ); 119assert . equal ( r . asked . length , 1 ); 120}); 121 122test ( 'Bypass never asks, Plan is unchanged, and the Settings switch skips the question in Manual' , async () => { 123const bypass = rig ({ preset :'strata-bypass' }); 124assert . equal (( await bypass . call ( bypass . session ( 'c' ), SEARCH )). kind , 'allow' ); 125assert . equal ( bypass . asked . length , 0 ); 126const plan = rig ({ preset :PLAN_PRESET }); 127assert . equal (( await plan . call ( plan . session ( 'c' ), SEARCH )). kind , 'allow' ); 128assert . equal ( plan . asked . length , 0 ); 129const switchedOn = rig ({ config :{ web :{ provider :'DuckDuckGo' , skipAsk :true } } }); 130assert . equal (( await switchedOn . call ( switchedOn . session ( 'c' ), SEARCH )). kind , 'allow' ); 131assert . equal ( switchedOn . asked . length , 0 ); 132// other things still ask with the switch on 133const write = await switchedOn . call ( switchedOn . session ( 'c2' ), { name :'write' , arguments :{ file_path :'a.txt' } }); 134assert . equal ( write . kind , 'ask' ); 135}); 136 137// ---------------------------------------------------------------------------------------------- the setting and the profile 138 139test ( 'Settings -> Tools: "search the web without asking" is off at first, remembered, and reaches the gate' , () => { 140const dir = mkdtempSync ( join ( tmpdir (), 'strata-web-ask-' )); 141try { 142let saved = {}; 143const tools = createAgentTools ({ read :() => saved , write :v => { saved = v ; }, dataDir :dir }); 144assert . equal ( tools . view (). webWithoutAsking , false ); 145assert . equal ( tools . profileView (). webWithoutAsking , false ); 146assert . equal ( tools . update ({ webWithoutAsking :true }). webWithoutAsking , true ); 147assert . equal ( saved . webWithoutAsking , true , 'saved in the settings file' ); 148assert . equal ( tools . profileView (). webWithoutAsking , true ); 149assert . equal ( tools . update ({ search :{ provider :'exa' } }). webWithoutAsking , true , 'other changes keep it' ); 150assert . equal ( tools . update ({ webWithoutAsking :false }). webWithoutAsking , false ); 151assert . equal ( tools . update ({ webWithoutAsking :'yes' }). webWithoutAsking , false , 'only a real on/off counts' ); 152} finally { rmSync ( dir , { recursive :true , force :true }); } 153}); 154 155test ( 'the profile names the search service in the gate\'s question, and carries the switch' , () => { 156const gateOf = tools => JSON . parse ( buildProfile ({ local :[], tools}). patch . split ( '\n' ). slice ( 1 ). join ( '\n' )). flatMap ( e => e . insert ?? []). find ( e => e . id === 'strata-gate' ). config . web ; 157const base = { off :new Set (), search :{ provider :'builtin' , key :'' }, servers :{}, webWithoutAsking :false }; 158assert . deepEqual ( gateOf ( base ), { provider :'DuckDuckGo, or Bing when DuckDuckGo is busy' , skipAsk :false }); 159assert . deepEqual ( gateOf ({ ...base , search :{ provider :'exa' , key :'k' }, webWithoutAsking :true }), { provider :'Exa' , skipAsk :true }); 160assert . equal ( gateOf ({ ...base , search :{ provider :'perplexity' , key :'' } }). provider , 'DuckDuckGo, or Bing when DuckDuckGo is busy' , 'a service without its key is not used, so it is not named' ); 161}); 162 163// ---------------------------------------------------------------------------------------------- the words, in every language 164 165test ( 'the card text and the Settings switch exist in all nine languages' , async () => { 166const compiled = await build ({ stdin :{ contents :"export * from './src/lib/i18n';" , resolveDir :process . cwd () }, bundle :true , write :false , platform :'node' , format :'esm' }); 167const { tr, setTranslationLanguage, loadCatalog} = await import ( `data:text/javascript;base64, ${ Buffer . from ( compiled . outputFiles [ 0 ]. text ). toString ( 'base64' )} ` ); 168for ( const l of [ 'zh' , 'ja' , 'de' , 'es' , 'ru' , 'pt' , 'ko' , 'fr' ]) await loadCatalog ( l ); // the non-English catalogs load on first use (src/lib/i18n.ts loadCatalog); load them before the first tr() 169const search = manualDecision ( SEARCH , { provider :'DuckDuckGo, or Bing when DuckDuckGo is busy' }). reason ; 170const open = manualDecision ( FETCH ). reason ; 171const english = [ search , open , 'Let the assistant search the web without asking' ]; 172for ( const language of [ 'zh' , 'ja' , 'de' , 'es' , 'ru' , 'pt' , 'ko' , 'fr' ]) { 173setTranslationLanguage ( language ); 174for ( const text of english ) assert . notEqual ( tr ( text ), text , ` ${ language } : ${ text } ` ); 175const translated = tr ( search ); 176assert . ok ( translated . includes ( 'heat pump prices' ), ` ${ language } : the person's own words stay as typed` ); 177assert . ok ( ! translated . includes ( 'Bing when DuckDuckGo is busy' ), ` ${ language } : the service's description is translated too` ); 178assert . ok ( ! /\{\d\} / . test ( translated ), language ); 179} 180setTranslationLanguage ( 'en' ); 181assert . equal ( tr ( search ), search ); 182}); 183 184// ---------------------------------------------------------------------------------------------- with the real Harness 185 186async function bridgeRig ( t ) { 187const worker = await startScriptedWorker ({ chunkDelayMs :5 }); 188const dir = mkdtempSync ( join ( tmpdir (), 'strata-webask-' )); 189const ws = join ( dir , 'ws' ); mkdirSync ( ws , { recursive :true }); 190const local = [{ id :'i' , label :'S' , baseUrl :worker . url , modelId :'scripted-model' , context :32768 , slots :2 }]; 191let n = 0 ; // one data folder per bridge: two bridges on one folder share a pid file and end each other's Harness 192const make = ( tools = () => undefined ) => createAgentBridge ({ dataDir :join ( dir , 'bridge-' + ( ++ n )), localInstances :() => local , connections :() => [], tools, env :process . env , startTimeoutMs :90_000 , searchMock :'limited' }); 193const bridges = []; 194t . after ( async () => { for ( const b of bridges ) await b . close (); await worker . close (); try { rmSync ( dir , { recursive :true , force :true , maxRetries :3 }); } catch { /* best effort */ } }); 195const open = tools => { const b = make ( tools ); bridges . push ( b ); return b ; }; 196const run = ( bridge , chatId , message , { mode= 'manual' , answer} = {}) => { 197const frames = []; 198return bridge . runTurn ({ 199 chatId, message, workspacePath :ws , mode, onFrame :f => { 200frames . push ( f ); 201if ( answer && f . type === 'agent-tool' && f . tool . state === 'proposed' ) void bridge . approve ({ chatId, callId :f . tool . id , decision :answer }). catch (() => {}); 202}, 203}). then (() => frames ); 204}; 205return { open, run, ws, local}; 206} 207const searchCards = frames => frames . filter ( f => f . type === 'agent-tool' && f . tool . name === 'web_search' ); 208const stateList = frames => searchCards ( frames ). map ( f => f . tool . state ); 209const CALL = 'SCRIPT:call web_search {"queries":["heat pump prices"]}' ; 210 211test ( 'real Harness, Manual: the first search shows the Approve/Deny card with the plain question, and Approve lets it run' , { skip}, async t => { 212const r = await bridgeRig ( t ); 213const bridge = r . open (); 214const asked = []; 215const frames = []; 216await bridge . runTurn ({ 217chatId :'w1' , message :CALL , workspacePath :r . ws , mode :'manual' , 218onFrame :f => { 219frames . push ( f ); 220if ( f . type === 'agent-tool' && f . tool . state === 'proposed' ) { asked . push ( f . tool . effect ); void bridge . approve ({ chatId :'w1' , callId :f . tool . id , decision :'approve' }). catch (() => {}); } 221}, 222}); 223assert . equal ( asked . length , 1 ); 224assert . match ( asked [ 0 ], / ^The assistant wants to search the web for: heat pump prices\. Search words go to DuckDuckGo, or Bing when DuckDuckGo is busy\.$ / ); 225const last = searchCards ( frames ). at ( - 1 ). tool ; 226assert . equal ( last . approved , true ); 227assert . ok ([ 'done' , 'error' ]. includes ( last . state ), `the search ran ( ${ last . state } ); the pretend web is rate limited` ); 228// second search in the same chat: no card 229const again = await r . run ( bridge , 'w1' , CALL , { answer :'deny' }); 230assert . ok ( ! stateList ( again ). includes ( 'proposed' ), 'no second question in the same chat' ); 231assert . ok ( ! stateList ( again ). includes ( 'denied' )); 232}); 233 234test ( 'real Harness, Manual: Deny gives a readable refusal and the search does not run' , { skip}, async t => { 235const r = await bridgeRig ( t ); 236const bridge = r . open (); 237const frames = await r . run ( bridge , 'w2' , CALL , { answer :'deny' }); 238const states = stateList ( frames ); 239assert . ok ( states . includes ( 'proposed' ), 'it asked' ); 240const card = searchCards ( frames ). at ( - 1 ). tool ; 241assert . equal ( card . state , 'denied' ); 242assert . doesNotMatch ( String ( card . result ?? '' ), / rate limit | limited right now / , 'nothing was searched' ); 243assert . equal ( frames . at ( - 1 ). type , 'done' ); 244}); 245 246test ( 'real Harness: Bypass and Plan do not ask, and the Settings switch skips the question in Manual' , { skip}, async t => { 247const r = await bridgeRig ( t ); 248const bridge = r . open (); 249for ( const mode of [ 'bypass' , 'plan' ]) { 250const frames = await r . run ( bridge , `w3- ${ mode } ` , CALL , { mode, answer :'deny' }); 251assert . ok ( ! stateList ( frames ). includes ( 'proposed' ), ` ${ mode } did not ask` ); 252} 253const tools = { off :new Set (), search :{ provider :'builtin' , key :'' }, servers :{}, webWithoutAsking :true }; 254const switched = r . open (() => tools ); 255const frames = await r . run ( switched , 'w4' , CALL , { answer :'deny' }); 256assert . ok ( ! stateList ( frames ). includes ( 'proposed' ), 'the switch is on, so no question' ); 257assert . ok ( searchCards ( frames ). length > 0 ); 258}); 259 260test ( 'real Harness: a scheduled task in Manual is answered "no" at once, so it cannot search unless the switch is on' , { skip}, async t => { 261const r = await bridgeRig ( t ); 262const task = { id :'t1' , prompt :CALL , mode :'manual' }; 263const bridge = r . open (); 264const off = await createAgentTaskRunner ({ agent :bridge , choice :() => ({ instanceId :'i' }), workspace :r . ws })( task ); 265assert . ok ( off , 'the task ran' ); 266const offCards = JSON . stringify ( off ); 267assert . doesNotMatch ( offCards , / rate limit | limited right now / , 'no search happened' ); 268assert . match ( offCards , / did not allow web access / , 'the model was told' ); 269assert . match ( offCards , / needed a yes, which nobody could give / , 'the report says why' ); 270const tools = { off :new Set (), search :{ provider :'builtin' , key :'' }, servers :{}, webWithoutAsking :true }; 271const on = await createAgentTaskRunner ({ agent :r . open (() => tools ), choice :() => ({ instanceId :'i' }), workspace :r . ws })({ ...task , id :'t2' }); 272assert . ok ( on ); 273assert . doesNotMatch ( JSON . stringify ( on ), / did not allow web access | nobody could give / , 'with the switch on the search was not refused' ); 274});