okami.mom/strata

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

Niko1221merge f-split-agent3 c99896ae6 (status, goal and time-skip events and backend, time-skip keepalive and stop, atomic.py) into f-split-intf9bfe8bc1

main
7.9 KiB130 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 } = {}) {
36  const res = await fetch(BASE + '/api/chat/stream', { 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        if (f.type === 'delta') { text += (f.text ?? '').length; continue; }
49        if (f.type === 'reasoning') { reasoning += (f.text ?? '').length; continue; }
50        if (f.type === 'stats') continue;
51        flushCounters();
52        let out = f.type;
53        if (f.type === 'status') out = `status[${f.seq}] ${f.phase}/${f.code}: ${f.text}${f.tokens !== undefined ? ` (tokens ${f.tokens})` : ''} +${f.elapsedMs}ms`;
54        else if (f.type === 'goal') out = `goal ${JSON.stringify(f.goal)}`;
55        else if (f.type === 'agent-tool') out = `tool ${f.tool.state} ${f.tool.verb} ${f.tool.target ?? ''}`;
56        else if (f.type === 'done') out = `done ${f.finishReason} tokensOut=${f.tokensOut}`;
57        else if (f.type === 'error') out = `ERROR ${f.message}`;
58        if (!quiet && out !== lastLine) console.log(`${stamp()}  ${out}`);
59        lastLine = out;
60      }
61    }
62    if (done) break;
63  }
64  flushCounters();
65  return frames;
66}
67
68if (command === 'connect') {
69  const [baseUrl, modelId] = rest;
70  await j('/api/model-providers', { kind: 'custom', name: 'Cloud model', baseUrl, protocol: 'openai-chat', apiKey: '', models: [{ id: modelId, name: 'Test model' }] });
71  console.log('saved');
72} else if (command === 'stream') {
73  const [message, mode = 'bypass'] = rest;
74  const chat = process.env.CHAT ?? `c-${Date.now()}`;
75  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 } : {}) });
76} else if (command === 'goal') {
77  const [objective] = rest;
78  const chat = process.env.CHAT ?? `g-${Date.now()}`;
79  const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
80  console.log(`${stamp()}  -- /goal run`);
81  const frames = await stream({ ...common, message: `/goal ${objective}` });
82  const last = frames.filter(f => f.type === 'goal').at(-1);
83  console.log(`${stamp()}  -- goal bar: state`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
84  console.log(`${stamp()}  -- pause`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
85  console.log(`${stamp()}  -- edit`, JSON.stringify(await j('/api/goal/edit', { chatId: chat, text: `${objective} (edited)` })));
86  console.log(`${stamp()}  -- resume (stream)`);
87  await stream({ ...common, goalAction: 'resume' });
88  console.log(`${stamp()}  -- clear`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
89  console.log(`${stamp()}  -- state after clear`, JSON.stringify(await j(`/api/goal?chatId=${chat}`)));
90  void last;
91} else if (command === 'goalbar') {
92  // Pause from the goal bar while a round runs, then resume through the chat stream.
93  const [objective, pauseAfter = '6'] = rest;
94  const chat = process.env.CHAT ?? `gb-${Date.now()}`;
95  const common = { sessionId: chat, mode: 'bypass', remoteModel: await model() };
96  const running = stream({ ...common, message: `/goal ${objective}` });
97  await sleep(Number(pauseAfter) * 1000);
98  console.log(`${stamp()}  -- pause from the bar`, JSON.stringify(await j('/api/goal/pause', { chatId: chat })));
99  await running;
100  console.log(`${stamp()}  -- state after the run`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
101  console.log(`${stamp()}  -- resume (stream, no message)`);
102  await stream({ ...common, goalAction: 'resume' });
103  console.log(`${stamp()}  -- state after resume`, JSON.stringify((await j(`/api/goal?chatId=${chat}`)).goal));
104  console.log(`${stamp()}  -- remove`, JSON.stringify(await j('/api/goal/clear', { chatId: chat })));
105} else if (command === 'timeskip') {
106  const [request, stopAfter] = rest;
107  const chat = process.env.CHAT ?? `t-${Date.now()}`;
108  const started = await j('/api/timeskip/start', { prompt: request, sessionId: chat, attempts: 1, workspaceId: process.env.WORKSPACE_ID, remoteModel: await model() });
109  const id = started.run.id;
110  console.log(`${stamp()}  started ${id} activity=${JSON.stringify(started.run.activity)}`);
111  let last = '', stopped = false;
112  for (;;) {
113    const { run } = await j(`/api/timeskip/status?id=${id}`);
114    const line = `${run.phase}${run.activity ? ` | ${run.activity.text}${run.activity.args?.step ? ` | assistant: ${run.activity.args.step}` : ''}` : ''}`;
115    if (line !== last) { console.log(`${stamp()}  ${line}`); last = line; }
116    if (stopAfter && !stopped && (Date.now() - t0) / 1000 >= Number(stopAfter)) {
117      console.log(`${stamp()}  -- pressing Stop (the chat Stop route)`);
118      console.log(`${stamp()}  `, JSON.stringify(await j('/api/chat/stop', { sessionId: chat })));
119      stopped = true;
120    }
121    if (['completed', 'cancelled', 'failed', 'interrupted'].includes(run.phase)) {
122      console.log(`${stamp()}  END ${run.phase}${run.error ? ` error=${run.error}` : ''} needsReview=${run.needsUserReview}`);
123      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}`); }
124      break;
125    }
126    await sleep(4000);
127  }
128} else {
129  console.error('commands: connect | stream | goal | timeskip'); process.exit(2);
130}