`;
test('search: the DuckDuckGo result list is read into titles, addresses and snippets; ads and internal links are dropped', () => {
const rows = parseHtmlResults(HTML);
assert.deepEqual(rows, [
{ url: 'https://example.com/a?x=1', title: 'Example Domain & more', snippet: "A short snippet 'quoted'." },
{ url: 'https://second.example/', title: 'Second', snippet: 'Second snippet' },
]);
assert.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]]);
assert.equal(realUrl('//duckduckgo.com/l/?uddg=https%3A%2F%2Fa.example%2F'), 'https://a.example/');
assert.equal(realUrl('https://duckduckgo.com/y.js?x=1'), null);
assert.equal(realUrl('javascript:alert(1)'), null);
});
test('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 () => {
assert.equal(looksBlocked(202, ''), true); assert.equal(looksBlocked(429, ''), true);
assert.equal(looksBlocked(200, '
Unfortunately, bots use DuckDuckGo too
'), true);
assert.equal(looksBlocked(200, HTML), false);
const sleeps = [];
const tick = () => { let t = 1_000_000; return { now: () => t, sleep: async ms => { sleeps.push(ms); t += ms; } }; };
const blocked = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('captcha anomaly-modal', { status: 200 }) });
await assert.rejects(blocked.search({ query: 'x' }), e => e.message === BLOCKED_MESSAGE && e.code === 'WEB_RATE_LIMITED');
const empty = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('No results.', { status: 200 }) });
assert.deepEqual(await empty.search({ query: 'zzzz' }), { sources: [], truncated: false });
const offline = createDuckDuckGoSearch({ ...tick(), fetch: async () => { throw new TypeError('fetch failed'); } });
await assert.rejects(offline.search({ query: 'x' }), /could not reach the internet/);
});
test('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 () => {
let clock = 1_000_000, calls = 0;
const waits = [];
const provider = createDuckDuckGoSearch({
now: () => clock, sleep: async ms => { waits.push(ms); clock += ms; },
fetch: 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 }); },
});
const a = await provider.search({ query: 'Strata engine', maxResults: 1 });
assert.equal(a.sources.length, 1);
await provider.search({ query: 'strata ENGINE' }); // same words: from the cache
assert.equal(calls, 1);
await provider.search({ query: 'another one' });
assert.equal(calls, 2); assert.ok(waits.some(ms => ms >= 1400), 'the second request waited for the gap');
for (let i = 0; i < 25; i++) { try { await provider.search({ query: `q${i}` }); } catch (e) { assert.equal(e.code, 'WEB_RATE_LIMITED'); break; } }
assert.ok(calls <= 23, 'no more than about 20 a minute');
});
test('search: Exa and Perplexity use the person\'s key, map their answers, and say plainly when the key is refused', async () => {
const real = globalThis.fetch;
try {
globalThis.fetch = async (url, init) => {
assert.equal(init.headers.authorization, 'Bearer the-key');
if (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: [] }] }));
return new Response(JSON.stringify({ choices: [{ message: { content: 'Answer.' } }], search_results: [{ url: 'https://p.example', title: 'P', snippet: 's' }] }));
};
assert.deepEqual((await createExaSearch({ key: 'the-key' }).search({ query: 'q' })).sources, [{ url: 'https://e.example', title: 'E', snippet: 'hl' }]);
const p = await createPerplexitySearch({ key: () => 'the-key' }).search({ query: 'q' });
assert.equal(p.content, 'Answer.'); assert.equal(p.sources[0].url, 'https://p.example');
assert.equal(createExaSearch({ key: () => '' }).available(), false);
globalThis.fetch = async () => new Response('{}', { status: 401 });
await assert.rejects(createExaSearch({ key: 'the-key' }).search({ query: 'q' }), /did not accept the key/);
} finally { globalThis.fetch = real; }
});
// ------------------------------------------------------------------------------------------------------- browser probe
test('browser: Chrome, then Edge, then Chromium; nothing found says so', () => {
const win = { PROGRAMFILES: 'C:\\Program Files', LOCALAPPDATA: 'C:\\Users\\x\\AppData\\Local' };
assert.equal(browserCandidates('win32', win)[0].name, 'Google Chrome');
assert.deepEqual(findBrowser({ platform: 'win32', env: win, exists: p => /msedge\.exe$/.test(p) }).name, 'Microsoft Edge');
assert.equal(findBrowser({ platform: 'win32', env: win, exists: () => false }).found, false);
assert.equal(findBrowser({ platform: 'darwin', exists: p => p.includes('Google Chrome') }).found, true);
});
// ------------------------------------------------------------------------------------ the app's own tool server (MCP)
function mcpSession(dir, mode) {
const child = spawn(process.execPath, [CUSTOM_TOOLS_SCRIPT, mode, join(dir, 'agent', 'custom-tools.json')], { stdio: ['pipe', 'pipe', 'inherit'], windowsHide: true });
const waiting = new Map();
createInterface({ input: child.stdout }).on('line', line => { const m = JSON.parse(line); waiting.get(m.id)?.(m); });
let id = 0;
const 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'); });
return { ask, close: () => child.kill() };
}
test('tool server: instruction tools return the person\'s text; command tools run their command with the assistant\'s text only in STRATA_INPUT', async () => {
const dir = tmp();
try {
const script = join(dir, 'show.mjs');
writeFileSync(script, "console.log('got:' + process.env.STRATA_INPUT); if (process.env.STRATA_INPUT === 'fail') process.exit(3);");
const { tools } = make(dir);
tools.addCustom({ name: 'Notes', about: 'House style.', kind: 'instructions', instructions: 'Start with one line.' });
tools.addCustom({ name: 'Show', about: 'Shows its input.', kind: 'command', command: `"${process.execPath}" "${script}"` });
const instr = mcpSession(dir, 'instructions');
try {
assert.equal((await instr.ask('initialize', { protocolVersion: '2024-11-05' })).result.serverInfo.name, 'strata-instructions');
const list = (await instr.ask('tools/list')).result.tools;
assert.deepEqual(list.map(t => [t.name, t.description]), [['notes', 'House style.']]);
assert.equal((await instr.ask('tools/call', { name: 'notes', arguments: {} })).result.content[0].text, 'Start with one line.');
} finally { instr.close(); }
const cmd = mcpSession(dir, 'commands');
try {
await cmd.ask('initialize', {});
assert.deepEqual((await cmd.ask('tools/list')).result.tools.map(t => t.name), ['show']);
const ok = (await cmd.ask('tools/call', { name: 'show', arguments: { input: 'hello; echo HACKED' } })).result;
assert.equal(ok.isError, false); assert.equal(ok.content[0].text, 'got:hello; echo HACKED', 'the text is data, never a command');
const bad = (await cmd.ask('tools/call', { name: 'show', arguments: { input: 'fail' } })).result;
assert.equal(bad.isError, true);
assert.match((await cmd.ask('tools/call', { name: 'gone', arguments: {} })).result.content[0].text, /no longer available/);
tools.update({ custom: { show: false } });
assert.deepEqual((await cmd.ask('tools/list')).result.tools, [], 'a change in Settings is seen without a restart');
} finally { cmd.close(); }
} finally { cleanup(dir); }
});
// ------------------------------------------------------------------------------------------------- real Harness
async function rig(t, setup) {
const worker = await startScriptedWorker({});
const dir = tmp();
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
const { tools } = make(dir);
setup?.(tools, dir);
const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }];
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], tools: () => tools.profileView(), env: process.env, startTimeoutMs: 90_000 });
t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
const run = async (chatId, tool, args, { mode = 'bypass', answer } = {}) => {
const frames = [];
await bridge.runTurn({ chatId, message: `SCRIPT:call ${tool} ${JSON.stringify(args)}`, workspacePath: ws, mode, onFrame: f => {
frames.push(f);
if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(() => {});
} });
return frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
};
return { worker, bridge, tools, dir, ws, run, offered: () => [...worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort() };
}
test('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) => {
const r = await rig(t, (tools, dir) => {
const script = join(dir, 'touch.mjs');
writeFileSync(script, "import { writeFileSync } from 'node:fs'; writeFileSync(process.argv[2], 'ran'); console.log('ok:' + process.env.STRATA_INPUT);");
tools.addCustom({ name: 'House style', about: 'Write in our house style.', kind: 'instructions', instructions: 'Always start with one line.' });
tools.addCustom({ name: 'Make marker', about: 'Writes a marker file.', kind: 'command', command: `"${process.execPath}" "${script}" "${join(dir, 'marker.txt')}"` });
});
const marker = join(r.dir, 'marker.txt');
const first = await r.run('c1', 'mcp__strata-instructions__house_style', {}, { mode: 'manual' });
assert.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');
assert.ok(!first.some(c => c.state === 'proposed'), 'an instruction tool never asks');
assert.match(first.at(-1).result, /Always start with one line/);
const plan = await r.run('c2', 'mcp__strata-commands__make_marker', { input: 'p' }, { mode: 'plan' });
assert.ok(!existsSync(marker), 'Plan mode refused the command');
assert.ok(!plan.some(c => c.state === 'done' && /ok:/.test(c.result ?? '')));
const denied = await r.run('c3', 'mcp__strata-commands__make_marker', { input: 'd' }, { mode: 'manual', answer: 'deny' });
assert.ok(denied.some(c => c.state === 'proposed') && !existsSync(marker), 'Manual asked first, and a No ran nothing');
const approved = await r.run('c4', 'mcp__strata-commands__make_marker', { input: 'yes' }, { mode: 'manual', answer: 'approve' });
assert.ok(approved.some(c => c.state === 'proposed'));
assert.equal(approved.at(-1).state, 'done'); assert.match(approved.at(-1).result, /ok:yes/); assert.ok(existsSync(marker));
});
test('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) => {
const r = await rig(t);
await r.run('o1', 'read', { file_path: join(r.ws, 'nothing.txt') });
const before = r.offered();
assert.ok(before.includes('web_search') && before.includes('web_fetch') && before.includes('subagent') && before.includes('job_list'));
r.tools.update({ groups: { jobs: false, helpers: false, search: false } });
await r.run('o2', 'read', { file_path: join(r.ws, 'nothing.txt') });
const after = r.offered();
assert.ok(!after.includes('web_search') && !after.includes('subagent') && !after.includes('job_list'), 'the three groups are gone');
assert.ok(after.includes('web_fetch') && after.includes('read') && after.includes('pwsh') !== after.includes('bash'), 'the rest stays');
});
// ------------------------------------------------------------------------------------------------------------ browser
test('gate: in Manual the browser asks before opening a page, clicking or typing, and not before looking; Plan refuses it', () => {
const nav = manualDecision({ name: 'mcp__browser__browser_navigate', arguments: { url: 'https://example.com/a' } });
assert.equal(nav.kind, 'ask'); assert.equal(nav.reason, 'Open the web page https://example.com/a');
assert.match(manualDecision({ name: 'mcp__browser__browser_click', arguments: { element: 'Sign in button' } }).reason, /^Click on the page: Sign in button/);
assert.match(manualDecision({ name: 'mcp__browser__browser_type', arguments: { element: 'Search box' } }).reason, /^Type into the page/);
assert.equal(manualDecision({ name: 'mcp__browser__browser_file_upload', arguments: {} }).kind, 'ask');
assert.match(manualDecision({ name: 'mcp__browser__browser_evaluate', arguments: {} }).reason, /small program/);
for (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);
assert.equal(manualDecision({ name: 'mcp__browser__browser_tabs', arguments: { action: 'list' } }), null);
assert.equal(manualDecision({ name: 'mcp__browser__browser_tabs', arguments: { action: 'close' } }).kind, 'ask');
assert.equal(planDecision({ name: 'mcp__browser__browser_snapshot' }).kind, 'deny');
});
test('browser: the tool server is found in the agent component; the screen can say what is missing', () => {
const exists = p => p.replaceAll(String.fromCharCode(92), '/').endsWith('/node_modules/@playwright/mcp/cli.js') && p.replaceAll(String.fromCharCode(92), '/').includes('/pkg/node_modules/@playwright/');
assert.equal(findPlaywrightMcp('', {}), null);
assert.ok(findPlaywrightMcp('/pkg', { exists }).replaceAll(String.fromCharCode(92), '/').endsWith('/pkg/node_modules/@playwright/mcp/cli.js'));
assert.equal(findPlaywrightMcp('/nowhere', { exists: () => false, list: () => { throw new Error('none'); } }), null);
const dir = tmp();
try {
const only = createAgentTools({ read: () => ({ browser: { enabled: true } }), write: () => {}, dataDir: dir, browser: () => ({ found: true, name: 'Google Chrome', path: 'C:/chrome.exe', cli: null }) });
assert.deepEqual(only.view().browser, { enabled: true, found: false, name: 'Google Chrome', missing: 'component' });
assert.equal(only.profileView().browserEnabled, false, 'no tool server, no browser rows');
const ready = createAgentTools({ read: () => ({ browser: { enabled: true } }), write: () => {}, dataDir: dir, browser: () => ({ found: true, name: 'Google Chrome', path: 'C:/chrome.exe', cli: 'C:/pw/cli.js' }) });
assert.equal(ready.view().browser.found, true);
const rows = entriesOf(buildProfile({ local: [], connections: [], tools: ready.profileView() })).flatMap(x => x.insert ?? []).filter(r => r.config?.serverName === 'browser');
assert.equal(rows.length, 1);
assert.deepEqual(rows[0].config.args, ['C:/pw/cli.js', '--browser', 'chromium', '--isolated', '--executable-path', 'C:/chrome.exe']);
const off = createAgentTools({ read: () => ({ browser: { enabled: false } }), write: () => {}, dataDir: dir, browser: () => ({ found: true, name: 'x', path: 'p', cli: 'c' }) });
assert.equal(entriesOf(buildProfile({ local: [], connections: [], tools: off.profileView() })).flatMap(x => x.insert ?? []).some(r => r.config?.serverName === 'browser'), false);
} finally { cleanup(dir); }
});
const browserNow = findBrowser();
const playwrightCli = HARNESS ? findPlaywrightMcp(HARNESS) : null;
// Opt-in: it starts a real (headless) Chrome, which a test run must not do on someone's PC unasked.
const 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;
test('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) => {
const http = await import('node:http');
const page = http.createServer((req, res) => { res.setHeader('content-type', 'text/html'); res.end('Strata browser test