okami.mom/strata

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

Niko1221Merge branch 'f-split-agent8' into f-split-vision788e0b731

main
16.9 KiB223 linesraw
1/**
2 * Drive the host over HTTP (no browser) against a real model and print what the page would receive.
3 *
4 *   STRATA_URL=http://127.0.0.1:8899 node scripts/agent3-http.mjs <command> [args]
5 *
6 *   connect <baseUrl> <modelId>        save an API connection to a model server (once per STRATA_HOME)
7 *   stream "<message>" [mode]          one chat turn; prints every frame compactly with its time (status, goal, tools, deltas counted)
8 *   goal "<objective>"                 /goal run, then the goal bar calls: state, pause, edit, clear, resume
9 *   timeskip "<request>" [stopAfterS]  a Time-skip job; polls status (phase + activity); with stopAfterS, presses Stop that many seconds in
10 *
11 * Environment: STRATA_URL (required), CHAT (chat id, default a fresh one), WORKSPACE_ID.
12 */
13const BASE = process.env.STRATA_URL;
14if (!BASE) { console.error('STRATA_URL is required'); process.exit(2); }
15const [command, ...rest] = process.argv.slice(2);
16const t0 = Date.now();
17const stamp = () => `${String(Math.round((Date.now() - t0) / 1000)).padStart(4)}s`;
18const j = async (path, body, method = body ? 'POST' : 'GET') => {
19  const res = await fetch(BASE + path, { method, headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
20  const text = await res.text();
21  let data; try { data = JSON.parse(text); } catch { data = { raw: text }; }
22  if (!res.ok) throw new Error(`${path} -> ${res.status} ${data.error ?? text.slice(0, 200)}`);
23  return data;
24};
25const sleep = ms => new Promise(r => setTimeout(r, ms));
26
27async function model() {
28  const providers = await j('/api/model-providers');
29  const c = providers.connections.at(-1);
30  if (!c) throw new Error('no API connection saved: run "connect" first');
31  return { connectionId: c.id, modelId: c.models[0].id };
32}
33
34/** One chat stream; returns the frames. `print` shows a compact line per frame, deltas and reasoning as counters. */
35async function stream(body, { quiet = false, path = '/api/chat/stream', onFrame = null } = {}) {
36  const res = await fetch(BASE + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
37  if (!res.ok) throw new Error(`stream -> ${res.status} ${await res.text()}`);
38  const frames = []; let buffer = '', text = 0, reasoning = 0, lastLine = '';
39  const flushCounters = () => { if (text || reasoning) { console.log(`${stamp()}  ... ${reasoning} reasoning chars, ${text} answer chars`); text = 0; reasoning = 0; } };
40  const reader = res.body.getReader(); const dec = new TextDecoder();
41  for (;;) {
42    const { value, done } = await reader.read();
43    if (value) {
44      buffer += dec.decode(value, { stream: true });
45      const lines = buffer.split('\n'); buffer = lines.pop() ?? '';
46      for (const line of lines.filter(Boolean)) {
47        const f = JSON.parse(line); f._at = Date.now(); frames.push(f);
48        try { onFrame?.(f); } catch (e) { console.log('onFrame error', e.message); }
49        if (f.type === 'delta') { text += (f.text ?? '').length; continue; }
50        if (f.type === 'reasoning') { reasoning += (f.text ?? '').length; continue; }
51        if (f.type === 'stats') continue;
52        flushCounters();
53        let out = f.type;
54        if (f.type === 'status') out = `status[${f.seq}] ${f.phase}/${f.code}: ${f.text}${f.tokens !== undefined ? ` (tokens ${f.tokens})` : ''} +${f.elapsedMs}ms`;
55        else if (f.type === 'goal') out = `goal ${JSON.stringify(f.goal)}`;
56        else if (f.type === 'agent-tool') {
57          out = `tool ${f.tool.state} ${f.tool.verb} ${f.tool.target ?? ''}${f.tool.state === 'proposed' ? `  [asks: ${f.tool.effect}]` : ''}`;
58          // ANSWER=approve|deny answers every card that asks (the card is the real Approve/Deny card of Manual mode)
59          if (f.tool.state === 'proposed' && process.env.ANSWER) void j('/api/chat/approval', { sessionId: body.sessionId, toolId: f.tool.id, decision: process.env.APPROVE_MATCH && new RegExp(process.env.APPROVE_MATCH, 'i').test(`${f.tool.target} ${f.tool.effect}`) ? 'approve' : process.env.ANSWER }).then(() => console.log(`${stamp()}  -> ${process.env.ANSWER} ${f.tool.id}`), e => console.log(`${stamp()}  answer failed: ${e.message}`));
60        }
61        else if (f.type === 'plan') out = `PLAN ${f.event} ${f.plan.state} "${f.plan.title}" steps=${f.plan.steps.map(x => x.state[0] + ':' + x.text.slice(0, 40)).join(' | ')}`;
62        else if (f.type === 'plan-step') out = `PLAN-STEP ${f.line}${f.summary ? ' | summary: ' + f.summary : ''}`;
63        else if (f.type === 'queued-message') out = `QUEUED-MESSAGE ${f.state} "${f.message.text.slice(0, 50)}" deliverAt=${f.message.deliverAt}${f.afterStep ? ' afterStep=' + f.afterStep : ''} queue=${f.queue.length}`;
64        else if (f.type === 'queued-release') out = `QUEUED-RELEASE ${f.messages.map(m => m.text.slice(0, 40)).join(' | ')}`;
65        else if (f.type === 'research') out = `RESEARCH sources=${f.sources.map(x => x.n + ':' + x.url).join(' ')}`;
66        else if (f.type === 'done') out = `done ${f.finishReason} tokensOut=${f.tokensOut}`;
67        else if (f.type === 'error') out = `ERROR ${f.message}`;
68        if (!quiet && out !== lastLine) console.log(`${stamp()}  ${out}`);
69        lastLine = out;
70      }
71    }
72    if (done) break;
73  }
74  flushCounters();
75  if (process.env.SHOWTEXT && !quiet) console.log(['---- answer text ----', frames.filter(f => f.type === 'delta').map(f => f.text).join(''), '---- end ----'].join(String.fromCharCode(10)));
76  return frames;
77}
78
79if (command === 'connect') {
80  const [baseUrl, modelId] = rest;
81  await j('/api/model-providers', { kind: 'custom', name: 'Cloud model', baseUrl, protocol: 'openai-chat', apiKey: '', models: [{ id: modelId, name: 'Test model', ...(process.env.CTX ? { contextMax: Number(process.env.CTX) } : {}), ...(process.env.MAXOUT ? { maxOutput: Number(process.env.MAXOUT) } : {}) }] });
82  console.log('saved');
83} else if (command === 'stream') {
84  const [message, mode = 'bypass'] = rest;
85  const chat = process.env.CHAT ?? `c-${Date.now()}`;
86  await stream({ sessionId: chat, message, mode, remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID, ...(process.env.PLAIN ? { agent: false } : {}), ...(process.env.THINK ? { thinking: process.env.THINK } : {}) });
87} else if (command === 'skill') {
88  // create a skill through the Skills page route: skill "Name" "description" "instructions"
89  const [name, description, instructions] = rest;
90  const out = await j('/api/skills', { name, description, body: instructions });
91  console.log('saved', out.id, '| skills now:', out.skills.map(s => `${s.id}(${s.source})`).join(', '));
92} else if (command === 'goal') {
93  const [objective] = rest;
94  const chat = process.env.CHAT ?? `g-${Date.now()}`;
95  const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
96  console.log(`${stamp()}  -- /goal run`);
97  const frames = await stream({ ...common, message: `/goal ${objective}` });
98  const last = frames.filter(f => f.type === 'goal').at(-1);
99  console.log(`${stamp()}  -- goal bar: state`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
100  console.log(`${stamp()}  -- pause`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
101  console.log(`${stamp()}  -- edit`, JSON.stringify(await j('/api/goal/edit', { chatId: chat, text: `${objective} (edited)` })));
102  console.log(`${stamp()}  -- resume (stream)`);
103  await stream({ ...common, goalAction: 'resume' });
104  console.log(`${stamp()}  -- clear`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
105  console.log(`${stamp()}  -- state after clear`, JSON.stringify(await j(`/api/goal?chatId=${chat}`)));
106  void last;
107} else if (command === 'goalbar') {
108  // Pause from the goal bar while a round runs, then resume through the chat stream.
109  const [objective, pauseAfter = '6'] = rest;
110  const chat = process.env.CHAT ?? `gb-${Date.now()}`;
111  const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
112  const running = stream({ ...common, message: `/goal ${objective}` });
113  await sleep(Number(pauseAfter) * 1000);
114  console.log(`${stamp()}  -- pause from the bar`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
115  await running;
116  console.log(`${stamp()}  -- state after the run`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
117  console.log(`${stamp()}  -- resume (stream, no message)`);
118  await stream({ ...common, goalAction: 'resume' });
119  console.log(`${stamp()}  -- state after resume`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
120  console.log(`${stamp()}  -- remove`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
121} else if (command === 'timeskip') {
122  const [request, stopAfter] = rest;
123  const chat = process.env.CHAT ?? `t-${Date.now()}`;
124  const started = await j('/api/timeskip/start', { prompt: request, sessionId: chat, attempts: 1, workspaceId: process.env.WORKSPACE_ID, remoteModel: await model() });
125  const id = started.run.id;
126  console.log(`${stamp()}  started ${id} activity=${JSON.stringify(started.run.activity)}`);
127  let last = '', stopped = false;
128  for (;;) {
129    const { run } = await j(`/api/timeskip/status?id=${id}`);
130    const line = `${run.phase}${run.activity ? ` | ${run.activity.text}${run.activity.args?.step && typeof run.activity.args.step === 'string' ? ` | assistant: ${run.activity.args.step}` : ''}` : ''}${run.lever ? ` | lever: step ${run.lever.step}/${run.lever.total} ${run.lever.defaulted ? '(default) ' : ''}- ${run.lever.why}` : ''}${run.a?.line ? ` | A: ${run.a.state} ${run.a.line.slice(0, 50)}` : ''}${run.b?.state ? ` | B: ${run.b.state} ${(run.b.line ?? '').slice(0, 50)}` : ''}`;
131    if (line !== last) { console.log(`${stamp()}  ${line}`); last = line; }
132    if (stopAfter && !stopped && (Date.now() - t0) / 1000 >= Number(stopAfter)) {
133      console.log(`${stamp()}  -- pressing Stop (the chat Stop route)`);
134      console.log(`${stamp()}  `, JSON.stringify(await j('/api/chat/stop', { sessionId: chat })));
135      stopped = true;
136    }
137    if (['completed', 'cancelled', 'failed', 'interrupted'].includes(run.phase)) {
138      console.log(`${stamp()}  END ${run.phase}${run.error ? ` error=${run.error}` : ''} needsReview=${run.needsUserReview}`);
139      try { const files = await j(`/api/timeskip/files?id=${id}`); console.log(`${stamp()}  files: ${files.files.map(f => `${f.status} ${f.path}`).join(', ') || '(none)'}`); } catch (e) { console.log(`${stamp()}  files: ${e.message}`); }
140      break;
141    }
142    await sleep(4000);
143  }
144} else if (command === 'plan') {
145  // /plan <task>, then (unless STOP_AT_PLAN) Start as goal with an optional queued message: plan "<task>" ["<queued message>"]
146  const [task, queued] = rest;
147  const chat = process.env.CHAT ?? `pl-${Date.now()}`;
148  const common = { sessionId: chat, mode: process.env.MODE ?? 'manual', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID };
149  console.log(`${stamp()}  -- /plan`);
150  const frames = await stream({ ...common, message: `/plan ${task}`});
151  const plan = frames.find(f => f.type === 'plan')?.plan;
152  if (!plan) { console.log('NO PLAN FRAME (the reply stays plain text)'); process.exit(1); }
153  console.log(JSON.stringify(plan.steps.map(x => x.text)));
154  console.log(`${stamp()}  -- GET /api/plan`, (await j(`/api/plan?sessionId=${chat}`)).plan?.state);
155  if (process.env.EDIT_LAST) { const steps = plan.steps.map(x => x.text); steps.push(process.env.EDIT_LAST); console.log(`${stamp()}  -- edit`, (await j('/api/plan/edit', { sessionId: chat, planId: plan.id, steps })).plan.steps.length, 'steps'); }
156  if (process.env.STOP_AT_PLAN) { console.log(`${stamp()}  -- ${process.env.STOP_AT_PLAN}`, JSON.stringify((await j('/api/plan/' + process.env.STOP_AT_PLAN, { sessionId: chat, planId: plan.id })).plan.state)); process.exit(0); }
157  console.log(`${stamp()}  -- start as goal`);
158  let sent = false;
159  const run = stream({ ...common, planId: plan.id }, { path: '/api/plan/start-goal', onFrame: f => {
160    if (queued && !sent && f.type === 'plan-step' && f.state === 'running') { sent = true; setTimeout(async () => { try { console.log(`${stamp()}  -- queue`, JSON.stringify((await j('/api/chat/queue', { sessionId: chat, message: queued })).message)); } catch (e) { console.log('queue failed', e.message); } }, Number(process.env.QUEUE_AFTER ?? 8) * 1000); }
161  } });
162  await run;
163  console.log(`${stamp()}  -- final plan`, JSON.stringify((await j(`/api/plan?sessionId=${chat}`)).plan?.steps.map(x => x.state + ':' + x.text.slice(0, 30))));
164} else if (command === 'modeswitch') {
165  // Manual run that needs several approvals; after the first card the chat is switched to Bypass: no further card may ask.
166  const [message] = rest;
167  const chat = process.env.CHAT ?? `ms-${Date.now()}`;
168  const common = { sessionId: chat, mode: 'manual', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID };
169  let asked = 0, switched = false;
170  const frames = await stream({ ...common, message }, { onFrame: async f => {
171    if (f.type === 'agent-tool' && f.tool.state === 'proposed') {
172      asked++;
173      if (!switched) { switched = true; console.log(`${stamp()}  -- switching to Bypass`, JSON.stringify(await j('/api/chat/mode', { sessionId: chat, mode: 'bypass' }))); }
174    }
175  } });
176  const done = frames.filter(f => f.type === 'agent-tool' && f.tool.state === 'done').length;
177  console.log(`${stamp()}  RESULT cards that asked=${asked} (expected 1), tools done=${done}`);
178} else if (command === 'long') {
179  // Fill the context with long pastes so the Harness has to compact, then ask about the first one: long <rounds> <chars>
180  const [rounds = '6', chars = '16000'] = rest;
181  const chat = process.env.CHAT ?? `lg-${Date.now()}`;
182  const common = { sessionId: chat, mode: 'bypass', remoteModel: await model(), workspaceId: process.env.WORKSPACE_ID };
183  const filler = n => Array.from({ length: Math.ceil(Number(chars) / 60) }, (_, i) => `Entry ${n}-${i}: the quick brown fox number ${i * 7 + n} jumps over the lazy dog.`).join('\n');
184  let frames = await stream({ ...common, message: 'Remember this code word for later: PAGODA-7731. Reply with just OK.' }, { quiet: true });
185  console.log(`${stamp()}  round 0 done, ctx=${frames.at(-1).contextTokens ?? "?"}`);
186  for (let n = 1; n <= Number(rounds); n++) {
187    frames = await stream({ ...common, message: `Here is log chunk ${n}. Reply with just the word OK.
188
189${filler(n)}`}, { quiet: true });
190    const d = frames.at(-1);
191    console.log(`${stamp()}  round ${n} ${d.type} ${d.finishReason ?? d.message ?? ""} tokensIn=${d.tokensIn} ctx=${d.contextTokens ?? d.context ?? "?"}`);
192  }
193  frames = await stream({ ...common, message: 'What was the code word I asked you to remember at the very start? Answer with the code word only.' }, { quiet: true });
194  console.log(`${stamp()}  ANSWER: ${frames.filter(f => f.type === "delta").map(f => f.text).join("").trim().slice(0, 120)}`);
195} else if (command === 'effort') {
196  // The same question at each reasoning level (and optional thinking budget): what really changes is the thinking the model did.
197  const [question = 'What is 17 times 23, and is the result divisible by 3? Explain briefly.', budget = '0'] = rest;
198  const rows = [];
199  for (const level of (process.env.LEVELS ? process.env.LEVELS.split(',') : ['Off', 'Low', 'Medium', 'High', 'Max'])) {
200    const t = Date.now();
201    const frames = await stream({ sessionId: `ef-${level}-${Date.now()}`, message: question, mode: 'bypass', remoteModel: await model(), thinking: level, thinkingBudget: Number(budget), agent: process.env.PLAIN ? false : undefined }, { quiet: true });
202    const reasoning = frames.filter(x => x.type === 'reasoning').map(x => x.text ?? '').join('').length;
203    const answer = frames.filter(x => x.type === 'delta').map(x => x.text ?? '').join('');
204    const done = frames.at(-1);
205    rows.push({ level, budget: Number(budget), reasoningChars: reasoning, answerChars: answer.length, tokensOut: done.tokensOut, seconds: Math.round((Date.now() - t) / 1000), answer: answer.replace(/\s+/g, ' ').slice(0, 90) });
206    console.log(JSON.stringify(rows.at(-1)));
207  }
208} else if (command === 'sampling') {
209  // Set Expert sampling through the engine settings route (as the Response settings dialog does), then ask for a random word a few times.
210  const [temp = '0', seed = '1', n = '3'] = rest;
211  const before = await j('/api/engine');
212  const set = async values => j('/api/engine', { expert: Object.entries(values).map(([id, value]) => ({ id, value })) }, 'PATCH');
213  await set({ 'sample.temp': Number(temp), 'sample.seed': Number(seed) });
214  const words = [];
215  for (let i = 0; i < Number(n); i++) {
216    const frames = await stream({ sessionId: `sm-${Date.now()}-${i}`, message: 'Reply with one random everyday English word and nothing else.', mode: 'bypass', remoteModel: await model(), thinking: 'Off' }, { quiet: true });
217    words.push(frames.filter(x => x.type === 'delta').map(x => x.text ?? '').join('').trim().slice(0, 30));
218  }
219  console.log(JSON.stringify({ temp: Number(temp), seed: Number(seed), words }));
220  await set({ 'sample.temp': 0.6, 'sample.seed': -1 });
221} else {
222  console.error('commands: connect | stream | goal | timeskip | plan | modeswitch | long | effort | sampling'); process.exit(2);
223}