okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
20.5 KiB294 linesraw
1/**
2 * A scripted OpenAI-compatible chat-completions worker, for the agent-bridge tests.
3 *
4 * It stands in for the Strata API worker so that the Harness agent loop, the tool executor, the
5 * approval gate and the host bridge are all real while the model is scripted. A scripted model proves
6 * the integration path, not model quality; the real-model run is a separate step.
7 *
8 * Script selection is by a directive in the last user message (`SCRIPT:<name> <args>`), never by
9 * request count: the Harness makes requests a script author does not plan for (a session title, a
10 * re-ask after a tool result), and a counter would shift every later reply.
11 *
12 *   SCRIPT:hello                    reasoning then a short text reply
13 *   SCRIPT:slow [n]                 n (default 400) text chunks, 40 ms apart: a window for Stop
14 *   SCRIPT:tool <file> <text>       one shell call that appends <text> to <file>; it asks the sandbox for
15 *                                   wider access, so the approval gate is exercised
16 *   SCRIPT:plain <file> <text>      the same call without the escalation (no approval needed)
17 *   SCRIPT:echo <text>              replies with <text>
18 *   SCRIPT:ask                      one ask_user_question call (the agent asking the person something)
19 *   SCRIPT:envdump <file>           one shell call that writes the shell's environment to <file>
20 *   SCRIPT:retrywrite <file> <text> the `write` tool, like a careful model: when the sandbox denies it and offers
21 *                                   an escalation, retry once with `sandbox_permissions: workspace-write`
22 *   SCRIPT:retryshell <file> <text> the same with the shell tool (an in-workspace append)
23 *   SCRIPT:read <file>              the `read` tool on <file>
24 *   SCRIPT:spawn <n> <script...>    n `subagent` calls in one reply; each child's prompt is SCRIPT:<script...>. When a child's
25 *                                   completion notice wakes the parent, it answers with a short text quoting the notice.
26 *   SCRIPT:goalstep                 one goal round: get_goal, then update_goal complete, then a short closing text
27 *   SCRIPT:planreply                a reply ending with a numbered plan of three steps (each step's text carries SCRIPT:goalstep)
28 *   SCRIPT:call <tool> <json>       one call to any tool with the given JSON arguments
29 *   SCRIPT:multi <json>             {"calls":[[tool,args],...],"say":"final text"}: all the calls in one reply, then the text once their results are in
30 *   SCRIPT:searchloop               a model that never stops: every reply rewrites a numbered plan and calls web_search again with a new query
31 *   SCRIPT:bloat <prompt tokens>    a reply that is only thinking (no answer text), with usage reporting that many prompt tokens (a context at 100%)
32 *
33 * A request whose last message is a tool result is answered with a text that quotes the result.
34 */
35import { createServer } from 'node:http';
36import { createHash } from 'node:crypto';
37
38const delay = ms => new Promise(r => setTimeout(r, ms));
39
40export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model = 'scripted-model', serial = false, window = 0, charsPerToken = 0, noCount = false } = {}) {
41  // `window` + `charsPerToken` make it behave like the engine: every request's prompt is counted (its size over charsPerToken), the usage it
42  // reports is that count, and a prompt that leaves no room to answer is refused with the engine's own 400 ("requests are never truncated").
43  // `serial` stands in for an engine with one request slot: the next request waits until the one before it has finished.
44  let tail = Promise.resolve();
45  const turn = () => { let release; const mine = new Promise(r => { release = r; }); const wait = tail; tail = tail.then(() => mine); return wait.then(() => release); };
46  const requests = [];
47  const counts = [];
48  let aborted = 0;
49  const server = createServer(async (req, res) => {
50    const url = new URL(req.url, 'http://x');
51    const json = (code, body) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
52    if (req.method === 'GET' && url.pathname === '/health') return json(200, { ok: true });
53    if (req.method === 'GET' && url.pathname === '/v1/models') return json(200, { object: 'list', data: [{ id: model, object: 'model' }] });
54    if (req.method === 'GET' && url.pathname === '/__requests') return json(200, { requests, aborted });
55    // The engine's own token count of a message (Anthropic style): characters over the density, plus the template's few tokens.
56    if (req.method === 'POST' && url.pathname.endsWith('/messages/count_tokens')) {
57      if (noCount) return json(404, { error: 'no count here' });   // an older engine: the message cannot be counted before it is sent
58      let text = '';
59      for await (const c of req) text += c;
60      const sent = JSON.parse(text);
61      const chars = (sent.messages ?? []).reduce((n, m) => n + (typeof m.content === 'string' ? m.content.length : JSON.stringify(m.content).length), 0);
62      counts.push(chars);
63      return json(200, { input_tokens: Math.ceil(chars / (charsPerToken || 4)) + 12 });
64    }
65    if (req.method !== 'POST' || !url.pathname.endsWith('/chat/completions')) return json(404, { error: 'no route' });
66    const release = serial ? await turn() : () => {};
67    res.on('close', release);
68    let raw = '';
69    for await (const c of req) raw += c;
70    const body = JSON.parse(raw);
71    const messages = body.messages ?? [];
72    const last = messages[messages.length - 1] ?? {};
73    const text = m => typeof m?.content === 'string' ? m.content : Array.isArray(m?.content) ? m.content.map(p => p.text ?? '').join(' ') : '';
74    // The Harness appends runtime-context messages after the prompt, so the newest user message is not
75    // the prompt: take the newest one that carries a directive.
76    const directive = [...messages].reverse().filter(m => m.role === 'user')
77      .map(m => /SCRIPT:(\w+)([^\n]*)/.exec(text(m))).find(Boolean);
78    requests.push({
79      at: Date.now(), model: body.model, stream: body.stream === true,
80      toolNames: (body.tools ?? []).map(t => t.function?.name),
81      // everything the client sent besides the conversation (sampling, limits, stream options)
82      params: Object.fromEntries(Object.entries(body).filter(([k]) => !['messages', 'tools', 'model'].includes(k))),
83      lastRole: last.role, directive: directive?.[1] ?? null, messageCount: messages.length,
84      authorization: req.headers.authorization ? 'present' : 'absent',
85      authSha: req.headers.authorization ? createHash('sha256').update(req.headers.authorization).digest('hex') : null,
86      promptChars: raw.length, raw,
87    });
88    const counted = charsPerToken > 0 ? Math.ceil(raw.length / charsPerToken) : 0;
89    if (window > 0 && counted > 0 && counted > window - 64) {
90      requests.at(-1).refused = counted;
91      return json(400, { error: { type: 'invalid_request_error', message: `request exceeds the context window: prompt (${counted} tokens) leaves no room to answer in the context (${window}); requests are never truncated` } });
92    }
93    const shellName = () => (body.tools ?? []).find(t => ['bash', 'pwsh'].includes(t.function?.name))?.function?.name ?? 'bash';
94    const shellCommand = (file, value) => (shellName() === 'pwsh' ? `Add-Content -Path '${file}' -Value '${value}'` : `echo ${value} >> ${file}`);
95    let closed = false;
96    res.on('close', () => { if (!res.writableEnded) { closed = true; aborted++; } });
97
98    res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
99    const id = `chatcmpl-${requests.length}`;
100    const send = (delta, finish = null, extra = {}) => res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
101    let promptTokens = counted || 100 + messages.length;
102    const finish = (reason, tokens = 10) => {
103      send({}, reason);
104      res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: promptTokens, completion_tokens: tokens, total_tokens: promptTokens + tokens } })}\n\n`);
105      res.write('data: [DONE]\n\n'); res.end();
106    };
107    const toolCall = async (name, call) => {
108      send({ role: 'assistant', content: '', reasoning_content: `I will use ${name}.` });
109      await delay(chunkDelayMs);
110      const argsJson = JSON.stringify(call);
111      send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name, arguments: '' } }] });
112      for (let i = 0; i < argsJson.length; i += 17) { send({ tool_calls: [{ index: 0, function: { arguments: argsJson.slice(i, i + 17) } }] }); await delay(5); }
113      return finish('tool_calls', 30);
114    };
115    const say = async (parts, tokens) => {
116      send({ role: 'assistant', content: '' });
117      for (const p of parts) { if (closed) return; send({ content: p }); await delay(chunkDelayMs); }
118      if (!closed) finish('stop', tokens ?? parts.length);
119    };
120
121    // A model that read "[sandbox: escalation available ...]" retries the exact call once with the narrowest wider mode.
122    // Only this prompt's own tool results count: a chat that has run tools before carries older ones.
123    const promptAt = messages.findLastIndex(m => m.role === 'user' && /SCRIPT:/.test(text(m)));
124    const toolMessages = messages.slice(promptAt + 1).filter(m => m.role === 'tool');
125    if (last.role === 'tool' && ['retrywrite', 'retryshell'].includes(directive?.[1]) && toolMessages.length === 1 && /escalation available/.test(text(last))) {
126      const [file, ...rest] = (directive[2] ?? '').trim().split(/\s+/);
127      const value = rest.join(' ') || 'run';
128      return toolCall(directive[1] === 'retrywrite' ? 'write' : shellName(), directive[1] === 'retrywrite'
129        ? { file_path: file, content: `${value}
130`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' }
131        : { command: shellCommand(file, value), description: `Append one line to ${file}`, sandbox_permissions: 'workspace-write', justification: 'The user asked for this file to be written.' });
132    }
133    // Time-skip's two own questions (they quote the plan, whose steps carry directives, so they are recognised by their words first).
134    {
135      const t = messages.filter(m => m.role === 'user').map(text).join(' ');
136      const answered = messages.some(m => m.role === 'assistant');
137      if (/biggest lever/.test(t) && !answered && last.role !== 'tool') return say(['{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}']);
138      if (/IMPROVEMENT PLAN/.test(t) && !answered && last.role !== 'tool') return say(['## Better path\n\n', '1. Improve the first attempt SCRIPT:goalstep\n', '2. Polish and check SCRIPT:goalstep\n']);
139    }
140    if (directive?.[1] === 'searchloop') {
141      const n = requests.filter(r => r.directive === 'searchloop').length;
142      send({ role: 'assistant', content: `Plan, version ${n}:
143
144## Search plan
145
1461. Search for the topic
1472. Read the best result
1483. Write the summary
149
150` });
151      const argsJson = JSON.stringify({ queries: [`topic search number ${n}`] });
152      send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] });
153      return finish('tool_calls', 60);
154    }
155    if (directive?.[1] === 'cutwrite' || directive?.[1] === 'cutalways') {
156      // A reply the length limit cuts inside a tool call (AGENT-LOST): some words, then `write` arguments that never close, finish "length".
157      // `cutwrite` is cut once and then, asked to carry on, writes the file in a small call; `cutalways` is cut every time.
158      const nudged = messages.some(m => m.role === 'user' && /cut off by the output limit/.test(text(m)));
159      if (directive[1] === 'cutwrite' && nudged) {
160        if (last.role === 'tool') return say(['Written in parts. The file is complete.']);
161        return toolCall('write', { file_path: (directive[2] ?? '').trim() || 'big.txt', content: 'entry 0001\nentry 0002\n' });
162      }
163      send({ role: 'assistant', content: 'Writing the whole file in one call now. ' });
164      await delay(chunkDelayMs);
165      const file = (directive[2] ?? '').trim() || 'big.txt';
166      send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'write', arguments: '' } }] });
167      const head = `{"file_path":"${file}","content":"`;
168      for (let i = 0; i < head.length; i += 11) { send({ tool_calls: [{ index: 0, function: { arguments: head.slice(i, i + 11) } }] }); await delay(2); }
169      for (let n = 1; n <= 60; n++) { send({ tool_calls: [{ index: 0, function: { arguments: `entry ${String(n).padStart(4, '0')}: alpha beta gamma delta\\n` } }] }); await delay(2); }
170      return finish('length', 19660);
171    }
172    if (directive?.[1] === 'bloat') {
173      promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100;
174      send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' });
175      return finish('stop', 20);
176    }
177    if (directive?.[1] === 'goalstep') {
178      // A goal round: read the goal, mark it complete, then say so.
179      if (!toolMessages.length) return toolCall('get_goal', {});
180      if (toolMessages.length === 1 && last.role === 'tool') {
181        const t = text(last); const id = /"id"\s*:\s*"([^"]+)"/.exec(t)?.[1]; const revision = Number(/"revision"\s*:\s*(\d+)/.exec(t)?.[1] ?? 1);
182        if (id) return toolCall('update_goal', { goal_id: id, revision, action: 'complete' });
183      }
184      return say(['Step finished. The result is checked.']);
185    }
186    if (directive?.[1] === 'planslow') return say(['## Slow plan\n\n', '1. First thing SCRIPT:goalstep\n', '2. A step that never finishes SCRIPT:slow 4000\n', '3. Third thing SCRIPT:goalstep\n']);
187    if (directive?.[1] === 'planreply') return say(['I looked around the folder first.\n\n## The pagoda plan\n\n', '1. First thing SCRIPT:goalstep\n', '2. Second thing SCRIPT:goalstep\n', '3. Third thing SCRIPT:goalstep\n']);
188    if (directive?.[1] === 'multi' && last.role === 'tool') {
189      let cfg = {};
190      try { cfg = JSON.parse((directive[2] ?? '').trim()); } catch { /* a test bug */ }
191      return say([String(cfg.say ?? 'Done.')]);
192    }
193    if (last.role === 'tool') {
194      const result = text(last).replace(/\s+/g, ' ').slice(0, 120);
195      return say(['Tool finished. ', `Result: ${result}`]);
196    }
197    const [name, args] = [directive?.[1], (directive?.[2] ?? '').trim()];
198    // The Harness's compaction request (its summarizer prompt asks for the person's evolving goals): answer with a short summary.
199    if (messages.some(m => /evolving goals/.test(text(m)))) { requests.at(-1).summary = true; return say(['Summary of the earlier conversation: the person asked for echoes of a word and got them.']); }
200    // The Harness's session-title request carries the same user text but offers no tools.
201    if (!(body.tools ?? []).length && messages.some(m => /concise title/i.test(text(m)))) return say(['Scripted title']);
202    if (name === 'slow') {
203      const n = parseInt(args, 10) || 400;
204      return say(Array.from({ length: n }, (_, i) => `w${i} `));
205    }
206    if (name === 'hang') { send({ role: 'assistant', content: '' }); return; }   // headers sent, then silence: a model server that went quiet
207    if (name === 'echo') return say([args]);
208    if (name === 'retrywrite' || name === 'retryshell') {
209      const [file, ...rest] = args.split(/\s+/);
210      const value = rest.join(' ') || 'run';
211      return name === 'retrywrite'
212        ? toolCall('write', { file_path: file, content: `${value}
213` })
214        : toolCall(shellName(), { command: shellCommand(file, value), description: `Append one line to ${file}` });
215    }
216    if (name === 'read') return toolCall('read', { file_path: args });
217    if (name === 'call') {
218      // This prompt's one call already ran (the Harness may add a context message after its result): answer, never call twice.
219      if (toolMessages.length) return say(['Tool finished. ', `Result: ${text(toolMessages[toolMessages.length - 1]).replace(/\s+/g, ' ').slice(0, 120)}`]);
220      const at = args.indexOf(' ');
221      let callArgs = {};
222      try { callArgs = JSON.parse(at < 0 ? '{}' : args.slice(at + 1).replace(/\s+#\d+.*$/, '')); } catch { /* an unparsable script argument is a test bug; send no arguments */ }
223      return toolCall(at < 0 ? args : args.slice(0, at), callArgs);
224    }
225    if (name === 'multi') {
226      let cfg = {};
227      try { cfg = JSON.parse(args.trim()); } catch { /* a test bug: no calls */ }
228      if (toolMessages.length) return say([String(cfg.say ?? 'Done.')]);
229      send({ role: 'assistant', content: '', reasoning_content: 'I will use the tools.' });
230      await delay(chunkDelayMs);
231      (cfg.calls ?? []).forEach(([tool, callArgs], i) => send({ tool_calls: [{ index: i, id: `call_${requests.length}_${i}`, type: 'function', function: { name: tool, arguments: JSON.stringify(callArgs ?? {}) } }] }));
232      return finish('tool_calls', 20);
233    }
234    if (name === 'spawn') {
235      // A settlement notice (or any later user-role message) after this prompt already got its tool round: just answer.
236      if (messages.slice(promptAt + 1).some(m => m.role === 'assistant') && last.role === 'user') {
237        return say(['Noted: ', text(last).replace(/\s+/g, ' ').slice(0, 90)]);
238      }
239      const [count, ...script] = args.split(/\s+/);
240      const n = Math.max(1, Number(count) || 1);
241      send({ role: 'assistant', content: '', reasoning_content: `I will start ${n} helper agents.` });
242      await delay(chunkDelayMs);
243      for (let i = 0; i < n; i++) {
244        const argsJson = JSON.stringify({ description: `Helper ${i + 1}`, prompt: `SCRIPT:${script.join(' ') || 'echo done'} #${i + 1}` });
245        send({ tool_calls: [{ index: i, id: `call_${requests.length}_${i}`, type: 'function', function: { name: 'subagent', arguments: '' } }] });
246        for (let k = 0; k < argsJson.length; k += 23) { send({ tool_calls: [{ index: i, function: { arguments: argsJson.slice(k, k + 23) } }] }); await delay(2); }
247      }
248      return finish('tool_calls', 40 * n);
249    }
250    if (name === 'ask') {
251      send({ role: 'assistant', content: '' });
252      send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'ask_user_question', arguments: JSON.stringify({ questions: [{ id: 'q1', question: 'Which colour?', options: [{ label: 'Red' }, { label: 'Blue' }] }] }) } }] });
253      return finish('tool_calls', 20);
254    }
255    if (name === 'tool' || name === 'plain' || name === 'envdump') {
256      const [file, ...rest] = args.split(/\s+/);
257      const shell = (body.tools ?? []).find(t => ['bash', 'pwsh'].includes(t.function?.name))?.function?.name ?? 'bash';
258      const value = rest.join(' ') || 'run';
259      let command = shell === 'pwsh' ? `Add-Content -Path '${file}' -Value '${value}'` : `echo ${value} >> ${file}`;
260      if (name === 'envdump') command = shell === 'pwsh' ? `Get-ChildItem Env: | ForEach-Object { $_.Name + '=' + $_.Value } | Set-Content -Path '${file}'` : `env > ${file}`;
261      const call = { command, description: `Append one line to ${file}` };
262      if (name === 'tool') {
263        call.sandbox_permissions = 'danger-full-access';
264        call.justification = 'The write must not be refused by the file sandbox.';
265      }
266      send({ role: 'assistant', content: '', reasoning_content: 'I will write the file with the shell.' });
267      await delay(chunkDelayMs);
268      const argsJson = JSON.stringify(call);
269      send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: shell, arguments: '' } }] });
270      // Fragment the arguments the way real servers do.
271      for (let i = 0; i < argsJson.length; i += 17) {
272        send({ tool_calls: [{ index: 0, function: { arguments: argsJson.slice(i, i + 17) } }] });
273        await delay(5);
274      }
275      return finish('tool_calls', 30);
276    }
277    // hello, and the default for anything unscripted (including the Harness's own title request)
278    send({ role: 'assistant', content: '', reasoning_content: 'Considering a greeting.' });
279    await delay(chunkDelayMs);
280    return say(['Hello ', 'from ', 'the ', 'scripted ', 'worker.']);
281  });
282  await new Promise(r => server.listen(port, '127.0.0.1', r));
283  return {
284    port: server.address().port,
285    url: `http://127.0.0.1:${server.address().port}/v1`,
286    requests, counts, get aborted() { return aborted; },
287    close: () => new Promise(r => { server.closeAllConnections?.(); server.close(r); }),
288  };
289}
290
291if (import.meta.url === `file://${process.argv[1].replace(/\\/g, '/')}` || process.argv[1]?.endsWith('scripted-worker.mjs')) {
292  const w = await startScriptedWorker({ port: Number(process.env.PORT ?? 0) });
293  console.log(`scripted worker on ${w.url}`);
294}