okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-7 (045843071): the app loads screens, languages, Prism and Time-skip on first use; main chunk 3,123,528 -> 755,418 B, start screen 248.5 -> 143.4 ms (p2006 Chrome, median of 10); nothing users see changes (cleanup step 7)1631a9fde

main
16.5 KiB274 linesraw
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', () => {
31  const ask = manualDecision(SEARCH, { provider: 'DuckDuckGo' });
32  assert.equal(ask.kind, 'ask');
33  assert.equal(ask.reason, 'The assistant wants to search the web for: heat pump prices. Search words go to DuckDuckGo.');
34  assert.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.');
35  assert.equal(manualDecision(FETCH).reason, "The assistant wants to open the web page https://example.com/a. The page's site sees the request.");
36  assert.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
38  assert.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', () => {
42  assert.equal(planDecision(SEARCH), null);
43  assert.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 = {} } = {}) {
50  const handlers = [];
51  const sessions = new Map();
52  const asked = [];
53  let policy = new Map();
54  const ctx = {
55    sessions: { get: id => sessions.get(id) },
56    permissionPresets: { current: session => session.preset ?? preset },
57    approval: {
58      overrideOf: session => policy.get(session.id) ?? null,
59      request: async req => { asked.push(req.reason); await new Promise(r => setTimeout(r, 5)); return answers[Math.min(asked.length - 1, answers.length - 1)]; },
60    },
61    on: (event, handler) => { if (event === 'tools/pre-execute') handlers.push(handler); },
62    inject: () => {},
63  };
64  apply(ctx, config);
65  const 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; };
66  const call = async (sessionObj, exec) => {
67    let n = 0;
68    const result = await handlers[0]({ ...exec, callId: `c${++n}${Math.random()}`, agent: { session: sessionObj } }, async () => ({ kind: 'allow' }));
69    return result;
70  };
71  return { 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 () => {
75  const r = rig({ config: { web: { provider: 'DuckDuckGo' } } });
76  const chat = r.session('chat-1');
77  const first = await r.call(chat, SEARCH);
78  assert.deepEqual(r.asked, ['The assistant wants to search the web for: heat pump prices. Search words go to DuckDuckGo.']);
79  assert.equal(first.kind, 'allow', 'approved, so the search runs');
80  assert.equal((await r.call(chat, { name: 'web_search', arguments: { queries: ['another'] } })).kind, 'allow');
81  assert.equal((await r.call(chat, FETCH)).kind, 'allow');
82  assert.equal(r.asked.length, 1, 'one question for the chat');
83  // another chat asks for itself
84  await r.call(r.session('chat-2'), SEARCH);
85  assert.equal(r.asked.length, 2);
86});
87
88test('Manual: Deny gives the model a readable refusal, and the next try asks again', async () => {
89  const r = rig({ answers: ['rejected', 'allowed-once'] });
90  const chat = r.session('chat-1');
91  const refused = await r.call(chat, SEARCH);
92  assert.equal(refused.kind, 'deny');
93  assert.equal(refused.reason, WEB_REFUSAL);
94  assert.match(refused.reason, /did not allow web access/);
95  assert.match(refused.reason, /Go on without it and say so/);
96  assert.doesNotMatch(refused.reason, /tool "|web_search/, 'no tool names in what the model reads');
97  assert.equal((await r.call(chat, SEARCH)).kind, 'allow', 'asked again, and this time yes');
98  assert.equal(r.asked.length, 2);
99  // an unavailable approval channel is a refusal too, not a silent allow
100  const none = rig({ answers: ['unavailable'] });
101  assert.equal((await none.call(none.session('c'), SEARCH)).reason, WEB_REFUSAL);
102});
103
104test('two searches started together share one question', async () => {
105  const r = rig();
106  const chat = r.session('chat-1');
107  const [a, b] = await Promise.all([r.call(chat, SEARCH), r.call(chat, { name: 'web_search', arguments: { queries: ['second'] } })]);
108  assert.equal(r.asked.length, 1);
109  assert.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 () => {
113  const r = rig();
114  const chat = r.session('chat-1');
115  const helper = r.session('helper-1', { header: { origin: 'subagent', parentSession: 'chat-1' } });
116  assert.equal((await r.call(helper, SEARCH)).kind, 'allow');
117  assert.equal(r.ctx.approval.overrideOf(helper), 'ask', 'the helper is set to ask so the card reaches the person');
118  assert.equal((await r.call(chat, SEARCH)).kind, 'allow');
119  assert.equal(r.asked.length, 1);
120});
121
122test('Bypass never asks, Plan is unchanged, and the Settings switch skips the question in Manual', async () => {
123  const bypass = rig({ preset: 'strata-bypass' });
124  assert.equal((await bypass.call(bypass.session('c'), SEARCH)).kind, 'allow');
125  assert.equal(bypass.asked.length, 0);
126  const plan = rig({ preset: PLAN_PRESET });
127  assert.equal((await plan.call(plan.session('c'), SEARCH)).kind, 'allow');
128  assert.equal(plan.asked.length, 0);
129  const switchedOn = rig({ config: { web: { provider: 'DuckDuckGo', skipAsk: true } } });
130  assert.equal((await switchedOn.call(switchedOn.session('c'), SEARCH)).kind, 'allow');
131  assert.equal(switchedOn.asked.length, 0);
132  // other things still ask with the switch on
133  const write = await switchedOn.call(switchedOn.session('c2'), { name: 'write', arguments: { file_path: 'a.txt' } });
134  assert.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', () => {
140  const dir = mkdtempSync(join(tmpdir(), 'strata-web-ask-'));
141  try {
142    let saved = {};
143    const tools = createAgentTools({ read: () => saved, write: v => { saved = v; }, dataDir: dir });
144    assert.equal(tools.view().webWithoutAsking, false);
145    assert.equal(tools.profileView().webWithoutAsking, false);
146    assert.equal(tools.update({ webWithoutAsking: true }).webWithoutAsking, true);
147    assert.equal(saved.webWithoutAsking, true, 'saved in the settings file');
148    assert.equal(tools.profileView().webWithoutAsking, true);
149    assert.equal(tools.update({ search: { provider: 'exa' } }).webWithoutAsking, true, 'other changes keep it');
150    assert.equal(tools.update({ webWithoutAsking: false }).webWithoutAsking, false);
151    assert.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', () => {
156  const 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;
157  const base = { off: new Set(), search: { provider: 'builtin', key: '' }, servers: {}, webWithoutAsking: false };
158  assert.deepEqual(gateOf(base), { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false });
159  assert.deepEqual(gateOf({ ...base, search: { provider: 'exa', key: 'k' }, webWithoutAsking: true }), { provider: 'Exa', skipAsk: true });
160  assert.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 () => {
166  const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' });
167  const { tr, setTranslationLanguage, loadCatalog } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`);
168  for (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()
169  const search = manualDecision(SEARCH, { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy' }).reason;
170  const open = manualDecision(FETCH).reason;
171  const english = [search, open, 'Let the assistant search the web without asking'];
172  for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) {
173    setTranslationLanguage(language);
174    for (const text of english) assert.notEqual(tr(text), text, `${language}: ${text}`);
175    const translated = tr(search);
176    assert.ok(translated.includes('heat pump prices'), `${language}: the person's own words stay as typed`);
177    assert.ok(!translated.includes('Bing when DuckDuckGo is busy'), `${language}: the service's description is translated too`);
178    assert.ok(!/\{\d\}/.test(translated), language);
179  }
180  setTranslationLanguage('en');
181  assert.equal(tr(search), search);
182});
183
184// ---------------------------------------------------------------------------------------------- with the real Harness
185
186async function bridgeRig(t) {
187  const worker = await startScriptedWorker({ chunkDelayMs: 5 });
188  const dir = mkdtempSync(join(tmpdir(), 'strata-webask-'));
189  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
190  const local = [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }];
191  let n = 0;   // one data folder per bridge: two bridges on one folder share a pid file and end each other's Harness
192  const make = (tools = () => undefined) => createAgentBridge({ dataDir: join(dir, 'bridge-' + (++n)), localInstances: () => local, connections: () => [], tools, env: process.env, startTimeoutMs: 90_000, searchMock: 'limited' });
193  const bridges = [];
194  t.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 */ } });
195  const open = tools => { const b = make(tools); bridges.push(b); return b; };
196  const run = (bridge, chatId, message, { mode = 'manual', answer } = {}) => {
197    const frames = [];
198    return bridge.runTurn({
199      chatId, message, workspacePath: ws, mode, onFrame: f => {
200        frames.push(f);
201        if (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  };
205  return { 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 => {
212  const r = await bridgeRig(t);
213  const bridge = r.open();
214  const asked = [];
215  const frames = [];
216  await bridge.runTurn({
217    chatId: 'w1', message: CALL, workspacePath: r.ws, mode: 'manual',
218    onFrame: f => {
219      frames.push(f);
220      if (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  });
223  assert.equal(asked.length, 1);
224  assert.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\.$/);
225  const last = searchCards(frames).at(-1).tool;
226  assert.equal(last.approved, true);
227  assert.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
229  const again = await r.run(bridge, 'w1', CALL, { answer: 'deny' });
230  assert.ok(!stateList(again).includes('proposed'), 'no second question in the same chat');
231  assert.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 => {
235  const r = await bridgeRig(t);
236  const bridge = r.open();
237  const frames = await r.run(bridge, 'w2', CALL, { answer: 'deny' });
238  const states = stateList(frames);
239  assert.ok(states.includes('proposed'), 'it asked');
240  const card = searchCards(frames).at(-1).tool;
241  assert.equal(card.state, 'denied');
242  assert.doesNotMatch(String(card.result ?? ''), /rate limit|limited right now/, 'nothing was searched');
243  assert.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 => {
247  const r = await bridgeRig(t);
248  const bridge = r.open();
249  for (const mode of ['bypass', 'plan']) {
250    const frames = await r.run(bridge, `w3-${mode}`, CALL, { mode, answer: 'deny' });
251    assert.ok(!stateList(frames).includes('proposed'), `${mode} did not ask`);
252  }
253  const tools = { off: new Set(), search: { provider: 'builtin', key: '' }, servers: {}, webWithoutAsking: true };
254  const switched = r.open(() => tools);
255  const frames = await r.run(switched, 'w4', CALL, { answer: 'deny' });
256  assert.ok(!stateList(frames).includes('proposed'), 'the switch is on, so no question');
257  assert.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 => {
261  const r = await bridgeRig(t);
262  const task = { id: 't1', prompt: CALL, mode: 'manual' };
263  const bridge = r.open();
264  const off = await createAgentTaskRunner({ agent: bridge, choice: () => ({ instanceId: 'i' }), workspace: r.ws })(task);
265  assert.ok(off, 'the task ran');
266  const offCards = JSON.stringify(off);
267  assert.doesNotMatch(offCards, /rate limit|limited right now/, 'no search happened');
268  assert.match(offCards, /did not allow web access/, 'the model was told');
269  assert.match(offCards, /needed a yes, which nobody could give/, 'the report says why');
270  const tools = { off: new Set(), search: { provider: 'builtin', key: '' }, servers: {}, webWithoutAsking: true };
271  const on = await createAgentTaskRunner({ agent: r.open(() => tools), choice: () => ({ instanceId: 'i' }), workspace: r.ws })({ ...task, id: 't2' });
272  assert.ok(on);
273  assert.doesNotMatch(JSON.stringify(on), /did not allow web access|nobody could give/, 'with the switch on the search was not refused');
274});