okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
16.3 KiB209 linesraw
1#!/usr/bin/env node
2/**
3 * AGENT-LOST end to end: a long single-file write through the real agent bridge, the real Harness and a real engine.
4 *
5 *   STRATA_HARNESS_DIR=<harness folder> node scripts/agent-lost-e2e.mjs [pagoda|long|cut ...]
6 *
7 * Scenarios (default: all)
8 *   pagoda  the owner's own prompt ("Write me a 100 voxel pagoda in one html file with garden."), thinking Medium, bypass mode
9 *   long    a deterministic long write: one file of N numbered lines (E2E_LINES, default 1800, about 22K tokens), thinking Off
10 *   mcp     Strata's own tool loop (serve runs an MCP tool itself): a call that finishes, and a call the reply is cut inside
11 *   raw     the model server alone: a reply cut inside a tool call, as the client receives it
12 *   cut     the same long write with the Harness told a small window (E2E_CUT_WINDOW, default 24000), so the reply budget is
13 *           about 7K tokens and the reply is cut inside the tool call: the turn must say so in words and the agent must carry on
14 *
15 * A model server that is already running is used when E2E_BASE_URL is set (nothing is started or stopped). Otherwise this
16 * starts serve/server.py as its own child with the engine named below and stops it by PID.
17 *
18 * Environment: E2E_ENGINE (strata executable), E2E_PACK, E2E_GGUF1, E2E_GGUF2, E2E_MTP, E2E_PROFILE, E2E_LIB (library folder),
19 * E2E_PORT (18590), E2E_WINDOW (65536), E2E_OUT (result folder), E2E_PYTHON.
20 *
21 * It prints one table and writes <E2E_OUT>/result.json with the frames summary of each scenario.
22 */
23import { spawn } from 'node:child_process';
24import { existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
25import { tmpdir } from 'node:os';
26import { join } from 'node:path';
27import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
28
29const REPO = join(import.meta.dirname, '..', '..', '..');
30const env = (name, fallback) => process.env[name] ?? fallback;
31const HOME = process.env.HOME ?? '';
32const PORT = Number(env('E2E_PORT', '18590'));
33const WINDOW = Number(env('E2E_WINDOW', '65536'));
34const EXISTING = process.env.E2E_BASE_URL ?? '';
35const PYTHON = env('E2E_PYTHON', 'python3');
36const OUT = env('E2E_OUT', mkdtempSync(join(tmpdir(), 'strata-agent-lost-')));
37const LINES = Number(env('E2E_LINES', '1100'));
38const REPEAT = Number(env('E2E_REPEAT', '1'));
39const TURN_S = Number(env('E2E_TURN_S', '900'));
40const wanted = process.argv.slice(2);
41const want = id => wanted.length === 0 || wanted.includes(id);
42mkdirSync(OUT, { recursive: true });
43
44if (!process.env.STRATA_HARNESS_DIR) { console.error('STRATA_HARNESS_DIR is not set'); process.exit(2); }
45const sleep = ms => new Promise(r => setTimeout(r, ms));
46
47let server = null, bridge = null;
48const finish = async (code) => {
49  try { await bridge?.close(); } catch { /* going away */ }
50  if (server?.pid) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { process.kill(server.pid, 'SIGTERM'); } catch { /* gone */ } } }
51  await sleep(1500);
52  console.log(`\nresult folder: ${OUT}`);
53  process.exit(code);
54};
55process.on('SIGINT', () => finish(130));
56process.on('SIGTERM', () => finish(143));
57
58if (!EXISTING) {
59  const pack = env('E2E_PACK', join(HOME, '026q/pack-iq3s'));
60  const g1 = env('E2E_GGUF1', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf'));
61  const g2 = env('E2E_GGUF2', join(HOME, 'models/IQ3_S/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf'));
62  const mtp = env('E2E_MTP', join(HOME, 'pr1426/mtp-rt'));
63  const profile = env('E2E_PROFILE', join(HOME, 'bwm/cnt3/data/expert-profile.bin'));
64  const exe = env('E2E_ENGINE', join(HOME, 'agentlost/eng/strata'));
65  const lib = env('E2E_LIB', join(HOME, 'agentlost/eng'));
66  for (const f of [pack, g1, g2, mtp, exe]) if (!existsSync(f)) { console.error(`missing: ${f}`); process.exit(2); }
67  const config = join(OUT, 'server.json');
68  writeFileSync(config, JSON.stringify({
69    exe, args: ['--pack', pack, '--native', g1, '--ple-gguf', g2, ...(existsSync(profile) ? ['--expert-profile', profile] : []),
70      '--prefill', 'auto', '--spec-min-p', '0.5', '--mtp', mtp, '--max-context', String(WINDOW), '--kv', 'int8', '--expert-cache', 'auto', '--spec', '4',
71      ...(process.env.E2E_ENGINE_ARGS ? process.env.E2E_ENGINE_ARGS.split(' ').filter(Boolean) : [])],
72    cwd: REPO, tokenizer: join(pack, 'tokenizer'), model_name: 'qwen3.8-flash-next-iq3_s', log: join(OUT, 'engine.log'), lib_dirs: [lib], port: PORT, gpu: 0,
73    fit_max_tokens: true,
74    // Strata's own tool loop (serve/server.py run_with_mcp): one small MCP server, offered only to requests that ask for it (strata_mcp).
75    mcp_servers: { fake: { command: PYTHON, args: [join(REPO, 'serve', 'mcp_fake_server.py')] } },
76  }, null, 2));
77  server = spawn(PYTHON, ['serve/server.py', '--engine', 'strata', '--config', config, '--port', String(PORT), '--no-api-key', '--ready-file', join(OUT, 'ready.json')], {
78    cwd: REPO, env: { ...process.env, LD_LIBRARY_PATH: `${lib}:${process.env.LD_LIBRARY_PATH ?? ''}`, STRATA_DATA_DIR: join(OUT, 'data'), PYTHONPATH: `${join(REPO, 'tools')}:${REPO}` }, stdio: ['ignore', 'pipe', 'pipe'], detached: true,
79  });
80  const sink = [];
81  server.stdout.on('data', d => sink.push(String(d)));
82  server.stderr.on('data', d => sink.push(String(d)));
83  server.on('exit', code => { sink.push(`[server exited ${code}]`); server = null; writeFileSync(join(OUT, 'server.log'), sink.join('')); });
84}
85
86const base = EXISTING || `http://127.0.0.1:${PORT}`;
87let ready = false;
88for (let i = 0; i < 360 && !ready; i++) {
89  if (!EXISTING && !server) break;
90  try { ready = (await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) })).ok; } catch { /* still loading */ }
91  if (!ready) await sleep(2000);
92}
93if (!ready) { console.error('the engine did not become ready'); await finish(4); }
94const model = (await (await fetch(`${base}/v1/models`)).json()).data[0].id;
95console.log(`engine ready: ${model}`);
96
97const rows = [];
98const note = (id, ok, detail) => { rows.push({ id, ok, detail }); console.log(`${ok ? 'PASS' : 'FAIL'}  ${id}  ${detail}`); };
99
100/** The bridge for a window as the host would tell it (the engine's own window stays WINDOW). */
101function makeBridge(window, dir) {
102  mkdirSync(join(OUT, dir), { recursive: true });
103  return createAgentBridge({
104    dataDir: join(OUT, dir), env: process.env, startTimeoutMs: 180_000, log: l => console.log('   bridge:', l),
105    localInstances: () => [{ id: 'e2e', label: 'iq3_s', baseUrl: `${base}/v1`, modelId: model, context: window, slots: 1, key: '' }], connections: () => [],
106  });
107}
108bridge = makeBridge(WINDOW, 'agent');
109
110/** One agent turn; every frame is kept in a compact timeline so the live data path can be read afterwards. */
111async function turn(name, message, { thinking = 'Medium', mode = 'bypass', chatId = name } = {}) {
112  const workspace = join(OUT, 'ws-' + name);
113  mkdirSync(workspace, { recursive: true });
114  const frames = [];
115  const t0 = Date.now();
116  let timedOut = false;
117  const stopTimer = setTimeout(() => { timedOut = true; void bridge.stop(chatId).catch(() => {}); }, TURN_S * 1000);
118  await bridge.runTurn({ chatId, message, workspacePath: workspace, mode, thinking, onFrame: f => frames.push({ at: Date.now() - t0, f }) });
119  clearTimeout(stopTimer);
120  const seconds = (Date.now() - t0) / 1000;
121  const byType = {};
122  for (const { f } of frames) byType[f.type] = (byType[f.type] ?? 0) + 1;
123  const done = frames.map(x => x.f).filter(f => f.type === 'done').at(-1) ?? null;
124  const error = frames.map(x => x.f).filter(f => f.type === 'error').at(-1) ?? null;
125  const prepare = frames.map(x => x.f).filter(f => f.type === 'status' && (f.phase === 'preparing' || f.code === 'preparing-tool'));
126  const cards = frames.map(x => x.f).filter(f => f.type === 'agent-tool').map(f => f.tool);
127  const text = frames.map(x => x.f).filter(f => f.type === 'delta').map(f => f.text).join('');
128  const files = readdirSync(workspace).map(n => ({ name: n, bytes: statSync(join(workspace, n)).size }));
129  const cutNotes = frames.map(x => x.f).filter(f => f.type === 'delta' && f.noteReason === 'cut').map(f => f.text.trim());
130  const drafts = frames.map(x => x.f).filter(f => f.type === 'agent-tool-draft').map(f => f.draft);
131  const writes = drafts.filter(d => d.name === 'write' && d.bytes > 0);
132  const draftStats = { frames: drafts.length, writeFrames: writes.length, lastWrite: writes.filter(d => !d.done).at(-1) ? { target: writes.filter(d => !d.done).at(-1).target, bytes: writes.filter(d => !d.done).at(-1).bytes, lines: writes.filter(d => !d.done).at(-1).lines } : null, previewSample: writes.filter(d => !d.done).at(-1)?.preview.slice(-80) ?? null };
133  const writesDone = cards.filter(c => c.name === 'write' && c.state === 'done').length;
134  const summary = { name, seconds, timedOut, writesDone, cutNotes, draftStats, byType, done, error, files, cards: cards.map(c => ({ name: c.name, state: c.state, target: c.target })), prepareStatuses: prepare.length, firstPrepare: prepare[0] ?? null, lastPrepare: prepare.at(-1) ?? null, text: text.slice(-1200) };
135  writeFileSync(join(OUT, `turn-${name}.json`), JSON.stringify({ summary, frames: frames.slice(0, 4000) }, null, 1));
136  return { ...summary, frames, workspace };
137}
138
139const longPrompt = `Create the file big.txt in the current folder with the write tool, in ONE call. It must hold exactly ${LINES} lines. Line N is "N: " followed by one short true sentence about a different city of the world (a new city on every line, no repeats, no pattern). Write every line out yourself, do not use a script or a loop, and do not shorten it.`;
140
141if (want('raw')) {
142  // What the model server itself sends when a reply is cut inside a tool call (no Harness): the stream of tool_calls pieces, then finish_reason "length".
143  const body = { model, stream: true, max_tokens: Number(env('E2E_RAW_CAP', '700')), temperature: 0.6,
144    chat_template_kwargs: { enable_thinking: false },
145    tools: [{ type: 'function', function: { name: 'write', description: 'Write a file.', parameters: { type: 'object', properties: { file_path: { type: 'string' }, content: { type: 'string' } }, required: ['file_path', 'content'] } } }],
146    messages: [{ role: 'user', content: longPrompt }] };
147  const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
148  const text = await res.text();
149  const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6)));
150  let args = '', name = '', content = '', finish = null, pieces = 0, ids = new Set();
151  for (const e of events) for (const c of e.choices ?? []) {
152    for (const tc of c.delta?.tool_calls ?? []) { pieces += 1; if (tc.id) ids.add(tc.id); if (tc.function?.name) name = tc.function.name; args += tc.function?.arguments ?? ''; }
153    content += c.delta?.content ?? '';
154    if (c.finish_reason) finish = c.finish_reason;
155  }
156  const usage = events.map(e => e.usage).filter(Boolean).at(-1);
157  writeFileSync(join(OUT, 'raw-sse.txt'), text);
158  note('raw: a reply cut inside a tool call reaches the client as pieces of the call and finish_reason length', finish === 'length' && name === 'write' && pieces > 5, `finish ${finish}; tool ${name}; ${pieces} call pieces, ${args.length} argument characters, closed JSON ${(() => { try { JSON.parse(args); return true; } catch { return false; } })()}; plain content ${JSON.stringify(content.slice(0, 80))}; ids ${ids.size}; usage ${JSON.stringify(usage)}`);
159}
160
161if (want('mcp')) {
162  // Strata's own tool loop: the server runs the MCP tool itself. A call that finishes is run; a call the reply is cut inside is announced and never run.
163  const ask = async (content, max_tokens) => {
164    const res = await fetch(`${base}/v1/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json' },
165      body: JSON.stringify({ model, stream: true, strata_mcp: true, max_tokens, temperature: 0.6, chat_template_kwargs: { enable_thinking: false }, messages: [{ role: 'user', content }] }) });
166    const text = await res.text();
167    const events = text.split(String.fromCharCode(10)).filter(l => l.startsWith('data: {')).map(l => JSON.parse(l.slice(6)));
168    const mcp = events.map(e => e.strata_mcp).filter(Boolean);
169    const finish = events.flatMap(e => e.choices ?? []).map(c => c.finish_reason).filter(Boolean).at(-1);
170    const said = events.flatMap(e => e.choices ?? []).map(c => c.delta?.content ?? '').join('');
171    return { mcp, finish, said };
172  };
173  const ok = await ask('Use the fake__echo tool to echo the text "hello from the tool", then tell me what it returned.', 600);
174  note('mcp: a short call is run by the server and answered', ok.mcp.some(m => m.event === 'result' && m.ok) && ok.finish === 'stop', `events ${JSON.stringify(ok.mcp.map(m => m.event))}; finish ${ok.finish}; said ${JSON.stringify(ok.said.slice(-120))}`);
175  const cut = await ask('Use the fake__echo tool once. Its text must be the sentence "the quick brown fox jumps over the lazy dog" written out 300 times in a row, separated by spaces.', 300);
176  note('mcp: a call the reply is cut inside is announced and never run (#211), and the stream says length', cut.mcp.some(m => m.event === 'start') && !cut.mcp.some(m => m.event === 'call') && cut.finish === 'length', `events ${JSON.stringify(cut.mcp.map(m => m.event))}; finish ${cut.finish}; said ${JSON.stringify(cut.said.slice(0, 100))}`);
177}
178
179if (want('pagoda')) {
180  const t = await turn('pagoda', 'Write me a 100 voxel pagoda in one html file with garden.');
181  const html = t.files.find(f => /\.html?$/i.test(f.name));
182  console.log(`   pagoda: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, files ${JSON.stringify(t.files)}`);
183  note('pagoda: a file was written or the turn says why not', !!html || /cut|too long|ran out|limit/i.test(t.text), `file ${html ? html.name + ' ' + html.bytes + ' B' : 'none'}; finish ${t.done?.finishReason}; text tail: ${JSON.stringify(t.text.slice(-240))}`);
184}
185if (want('long')) for (let rep = 1; rep <= REPEAT; rep++) {
186  const t = await turn(`long${rep}`, longPrompt, { thinking: 'Off' });
187  const f = t.files.find(x => x.name === 'big.txt');
188  const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0;
189  console.log(`   long${rep}: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason, tokensOut: t.done.tokensOut })}, draft ${JSON.stringify(t.draftStats)}, cut notes ${JSON.stringify(t.cutNotes)}`);
190  note(`long${rep}: big.txt written (${LINES} lines asked)`, lines >= LINES * 0.95 || t.writesDone > 0 || t.cutNotes.length > 0 && !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}; tokens out ${t.done?.tokensOut}; cards ${JSON.stringify(t.cards.filter(c => c.state !== 'running').map(c => c.name))}; writes done ${t.writesDone}; cut notes ${t.cutNotes.length}; draft frames ${t.draftStats.frames}`);
191  note(`long${rep}: the turn did not end silently`, !!f || t.cutNotes.length > 0 || t.text.trim().length > 0, `text tail ${JSON.stringify(t.text.slice(-160))}`);
192}
193
194if (want('cut')) {
195  // A small window told to the Harness (E2E_CUT_WINDOW, default 24000; the engine's own stays WINDOW) makes the reply budget about 7K tokens (raised to
196  // 12K by the fix), so the first reply is cut inside the tool call, as the pagoda's was at 19,660.
197  await bridge.close();
198  bridge = makeBridge(Number(env('E2E_CUT_WINDOW', '24000')), 'agent-cut');
199  const t = await turn('cut', longPrompt, { thinking: 'Off' });
200  const f = t.files.find(x => x.name === 'big.txt');
201  const lines = f ? readFileSync(join(t.workspace, 'big.txt'), 'utf8').split(String.fromCharCode(10)).filter(Boolean).length : 0;
202  console.log(`   cut: ${t.seconds.toFixed(0)} s, frames ${JSON.stringify(t.byType)}, done ${JSON.stringify(t.done && { finishReason: t.done.finishReason })}, files ${JSON.stringify(t.files)}, cut notes ${JSON.stringify(t.cutNotes)}, draft ${JSON.stringify(t.draftStats)}`);
203  note('cut: the chat said the reply was cut, in words', t.cutNotes.length > 0 && t.cutNotes.every(n => /length limit/.test(n)), JSON.stringify(t.cutNotes));
204  note('cut: the agent went on and the file exists', !!f, `file ${f ? f.bytes + ' B, ' + lines + ' lines' : 'none'}; finish ${t.done?.finishReason}`);
205}
206
207writeFileSync(join(OUT, 'result.json'), JSON.stringify(rows, null, 2));
208console.log('\n' + rows.map(r => `${r.ok ? 'PASS' : 'FAIL'}  ${r.id}`).join('\n'));
209await finish(rows.some(r => !r.ok) ? 1 : 0);