Files
Strata/app/host/server/visual-agent-loop.mjs

373 lines
13 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Multi-step streaming OpenAI-compatible tool-calling loop for Strata's Live Sidebar Visual Browser
* when running standalone (without the external Agent Harness).
*
* Works seamlessly with local Strata engines (`Inkling-2-Mini`, `Qwen3.8-Flash-Next`, `Qwen3.6-35B-A3B`,
* `Hy4-Flash`) and OpenAI-compatible remote model connections, emitting the exact NDJSON frames
* (`start`, `status`, `reasoning`, `agent-tool`, `artifacts`, `deliverable`, `delta`, `stats`, `done`)
* that `Chat.tsx` renders into the unified thought/work-log trace and right-hand preview panel.
*/
import { randomUUID } from 'node:crypto';
import { basename } from 'node:path';
import {
VISUAL_BROWSER_TOOLS,
executeVisualBrowserTool,
extractLatestHtmlFromHistory,
visualToolLabel,
} from './visual-browser-tools.mjs';
const MAX_STEPS = 10;
const VISUAL_SYSTEM_GUIDANCE = [
'You have access to Strata’s Live Visual Browser in the right sidebar (`browser_*` tools).',
'Everything you open, click, hover, scroll, or update is shown live to the user with a moving cursor and highlight overlay:',
'- For web search / verification: call `browser_search`, then `browser_click` on a relevant `@eN` result link to read and verify the live page before answering.',
'- For visually inspecting or improving HTML / website designs: if this chat already has an HTML page, call `browser_open` with `{"url": "current_html"}` (or pass a URL/file), run `browser_inspect_design` (and optionally `browser_set_viewport` to `"mobile"` and `"desktop"`), then call `browser_update_html` with the complete improved `<!doctype html>...</html>` document so the user sees it hot-reload live in the sidebar and in the Preview tab.',
'- Keep your final chat reply concise: summarize what you checked or improved without pasting a giant duplicate HTML code block if you already called `browser_update_html`.',
].join('\n');
function openAiToolsSpec() {
return VISUAL_BROWSER_TOOLS.map(t => ({
type: 'function',
function: {
name: t.name,
description: t.description,
parameters: t.parameters,
},
}));
}
/** Stream one OpenAI `/v1/chat/completions` step and collect text, reasoning, tool calls, and token timings. */
async function streamOpenAiStep({
baseUrl,
apiKey,
modelId,
messages,
tools,
extra = {},
signal,
onReasoning,
onDelta,
fetcher = fetch,
}) {
const headers = {
'content-type': 'application/json',
...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
};
const response = await fetcher(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
method: 'POST',
headers,
signal,
body: JSON.stringify({
model: modelId,
messages,
tools,
tool_choice: 'auto',
stream: true,
stream_options: { include_usage: true },
...extra,
}),
});
if (!response.ok) {
const errText = await response.text().catch(() => '');
let parsedMsg = '';
try { parsedMsg = JSON.parse(errText)?.error?.message || ''; } catch {}
throw new Error(parsedMsg || `Model server returned HTTP ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let content = '';
let reasoning = '';
/** @type {Map<number, { id: string, name: string, arguments: string }>} */
const toolCallsByIndex = new Map();
let tokensIn = null;
let tokensOut = null;
let tps = null;
let promptTps = null;
let finishReason = null;
const handlePacket = packet => {
if (packet.usage) {
if (typeof packet.usage.prompt_tokens === 'number') tokensIn = packet.usage.prompt_tokens;
if (typeof packet.usage.completion_tokens === 'number') tokensOut = packet.usage.completion_tokens;
}
if (packet.timings) {
if (typeof packet.timings.predicted_per_second === 'number') tps = packet.timings.predicted_per_second;
if (typeof packet.timings.prompt_per_second === 'number') promptTps = packet.timings.prompt_per_second;
}
const choice = packet.choices?.[0];
if (!choice) return;
if (choice.finish_reason) finishReason = choice.finish_reason;
const delta = choice.delta ?? choice.message ?? {};
const rChunk = delta.reasoning_content ?? delta.reasoning ?? '';
if (typeof rChunk === 'string' && rChunk) {
reasoning += rChunk;
onReasoning?.(rChunk);
}
if (typeof delta.content === 'string' && delta.content) {
content += delta.content;
onDelta?.(delta.content);
}
if (Array.isArray(delta.tool_calls)) {
for (const tc of delta.tool_calls) {
const idx = typeof tc.index === 'number' ? tc.index : 0;
const cur = toolCallsByIndex.get(idx) ?? { id: tc.id || `call_${randomUUID().slice(0, 8)}`, name: '', arguments: '' };
if (tc.id) cur.id = tc.id;
if (tc.function?.name) cur.name += tc.function.name;
if (typeof tc.function?.arguments === 'string') cur.arguments += tc.function.arguments;
toolCallsByIndex.set(idx, cur);
}
}
};
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let nl;
while ((nl = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line.startsWith('data:')) continue;
const payload = line.slice(5).trim();
if (!payload || payload === '[DONE]') continue;
try { handlePacket(JSON.parse(payload)); } catch { /* ignore comment/partial */ }
}
}
} finally {
try { reader.releaseLock(); } catch {}
}
const toolCalls = [...toolCallsByIndex.entries()]
.sort((a, b) => a[0] - b[0])
.map(([, v]) => v)
.filter(v => v.name);
return { content, reasoning, toolCalls, tokensIn, tokensOut, tps, promptTps, finishReason };
}
export async function runVisualBrowserTurn({
visualBrowser,
sessionId,
message,
history = [],
savedHtml = null,
images = [],
systemPrompt = '',
workspacePath = null,
mode = 'manual',
endpoint,
onFrame,
signal,
skills = [],
fetcher = fetch,
}) {
const started = Date.now();
let firstTokenMs = null;
let totalTokensOut = 0;
let lastTokensIn = null;
let lastTps = null;
let lastPromptTps = null;
const artifacts = [];
const markFirstToken = () => {
if (firstTokenMs === null) firstTokenMs = Date.now() - started;
};
onFrame({
type: 'start',
agent: true,
model: endpoint.label,
contextMax: endpoint.contextMax,
remoteModel: endpoint.remoteModel === true,
skills,
});
const hasPriorHtml = Boolean(extractLatestHtmlFromHistory(history, visualBrowser.getState(sessionId)?.stageHtml ?? savedHtml ?? null));
const fullSystem = [
systemPrompt,
VISUAL_SYSTEM_GUIDANCE,
hasPriorHtml ? 'Note: This conversation already contains an HTML page (`"url": "current_html"`).' : '',
].filter(Boolean).join('\n\n');
const userContent = images.length && endpoint.vision
? [{ type: 'text', text: message }, ...images.map(img => ({ type: 'image_url', image_url: { url: img.dataUrl ?? img.url } }))]
: message;
const messages = [
{ role: 'system', content: fullSystem },
...history.map(m => ({ role: m.role, content: m.content })),
{ role: 'user', content: userContent },
];
const tools = openAiToolsSpec();
for (let step = 0; step < MAX_STEPS; step++) {
signal?.throwIfAborted?.();
onFrame({ type: 'status', phase: 'thinking', text: step === 0 ? 'Thinking…' : 'Reviewing browser view…' });
const turn = await streamOpenAiStep({
baseUrl: endpoint.baseUrl,
apiKey: endpoint.apiKey,
modelId: endpoint.modelId,
messages,
tools,
extra: endpoint.extra ?? {},
signal,
fetcher,
onReasoning: text => {
markFirstToken();
onFrame({ type: 'reasoning', text });
},
onDelta: text => {
markFirstToken();
onFrame({ type: 'delta', text });
},
});
if (typeof turn.tokensIn === 'number') lastTokensIn = turn.tokensIn;
if (typeof turn.tokensOut === 'number') totalTokensOut += turn.tokensOut;
if (typeof turn.tps === 'number') lastTps = turn.tps;
if (typeof turn.promptTps === 'number') lastPromptTps = turn.promptTps;
if (lastTps !== null || lastPromptTps !== null) {
onFrame({ type: 'stats', tokensOut: totalTokensOut || undefined, tps: lastTps ?? undefined, promptTps: lastPromptTps ?? undefined });
}
if (!turn.toolCalls.length) {
break;
}
messages.push({
role: 'assistant',
content: turn.content || '',
...(turn.reasoning ? { reasoning_content: turn.reasoning } : { reasoning_content: '' }),
tool_calls: turn.toolCalls.map(tc => ({
id: tc.id,
type: 'function',
function: { name: tc.name, arguments: tc.arguments || '{}' },
})),
});
for (const tc of turn.toolCalls) {
signal?.throwIfAborted?.();
let parsedArgs = {};
try { parsedArgs = JSON.parse(tc.arguments || '{}') ?? {}; } catch { parsedArgs = {}; }
const runningLabel = visualToolLabel(tc.name, parsedArgs, 'running');
const cardBase = {
id: tc.id,
name: `mcp__strata-visual-browser__${tc.name}`,
args: parsedArgs,
preview: runningLabel.target,
effect: 'Uses the live sidebar browser.',
scope: 'connected',
verb: runningLabel.verb,
target: runningLabel.target,
};
onFrame({ type: 'status', phase: 'tool', text: runningLabel.target ? `${runningLabel.verb} · ${runningLabel.target}` : runningLabel.verb });
onFrame({ type: 'agent-tool', tool: { ...cardBase, state: 'running' } });
const toolStart = Date.now();
try {
const out = await executeVisualBrowserTool(visualBrowser, {
sessionId,
name: tc.name,
args: parsedArgs,
workspacePath,
mode,
history,
savedHtml,
signal,
});
const doneLabel = visualToolLabel(tc.name, parsedArgs, 'done');
onFrame({
type: 'agent-tool',
tool: {
...cardBase,
verb: doneLabel.verb,
state: 'done',
durationMs: Date.now() - toolStart,
result: String(out?.text ?? 'Done.').slice(0, 1200),
},
});
if (tc.name === 'browser_update_html' && typeof parsedArgs.html === 'string') {
const title = String(parsedArgs.title || 'Improved HTML Design');
const art = {
id: `visual-html:${sessionId}`,
title: title.endsWith('.html') ? title : `${title}.html`,
kind: 'website',
content: parsedArgs.html,
};
const existingIdx = artifacts.findIndex(a => a.id === art.id);
if (existingIdx >= 0) artifacts[existingIdx] = art;
else artifacts.push(art);
onFrame({ type: 'artifacts', artifacts: [...artifacts] });
if (out?.savedFile) {
onFrame({
type: 'deliverable',
path: out.savedFile,
name: basename(out.savedFile),
action: 'wrote',
});
}
}
messages.push({
role: 'tool',
tool_call_id: tc.id,
content: String(out?.text ?? 'Done.'),
});
if (endpoint.vision && tc.name === 'browser_inspect_design' && typeof out?.frame === 'string' && out.frame.startsWith('data:image/')) {
messages.push({
role: 'user',
content: [
{ type: 'text', text: 'Rendered screenshot from browser_inspect_design for visual review:' },
{ type: 'image_url', image_url: { url: out.frame } },
],
});
}
} catch (err) {
const errText = String(err?.message ?? err);
const errLabel = visualToolLabel(tc.name, parsedArgs, 'error');
onFrame({
type: 'agent-tool',
tool: {
...cardBase,
verb: errLabel.verb,
state: 'error',
durationMs: Date.now() - toolStart,
result: errText,
},
});
messages.push({
role: 'tool',
tool_call_id: tc.id,
content: `Error: ${errText}`,
});
}
}
if (turn.content && !turn.content.endsWith('\n')) {
onFrame({ type: 'delta', text: '\n\n' });
}
}
const durationMs = Date.now() - started;
onFrame({
type: 'done',
tokensIn: lastTokensIn,
tokensOut: totalTokensOut || null,
usageSource: lastTokensIn !== null || totalTokensOut > 0 ? 'reported' : 'unavailable',
tps: lastTps,
promptTps: lastPromptTps,
ttftMs: firstTokenMs,
durationMs,
});
return { tokensIn: lastTokensIn, tokensOut: totalTokensOut || null, tps: lastTps, promptTps: lastPromptTps, durationMs };
}