Add GUI agent mode: the model acts via a universal shell_exec tool

- agent:🐚 native shell_exec (bash -lc, cwd, timeout, 64 KiB output cap)
  behind a ShellRunner seam — base/host mode now; an isolated Docker-MCP runner
  plugs in later without touching the loop. OpenAI function declaration included.
- agent::run_loop: bounded model<->tool orchestration, generic over the model
  step so it is unit-testable without the engine. Persists the full trajectory
  (assistant tool-call turns + role:tool results + final answer) and emits
  tool_call / tool_result / final / error progress events.
- api::sessions: POST .../chat with agent:true drives the loop and streams the
  events as SSE; the GUI shows commands + output inline (observability, no gate).
- store: messages gains tool_call_id; an idempotent migration adds the column to
  pre-existing databases (CREATE TABLE IF NOT EXISTS does not alter them).
- web: robot agent toggle, tool-call/output blocks, history rendering of tool
  turns; inline favicon to silence the favicon 404.

Validated LIVE on engine 0.1.67: the model called shell_exec('uname -a'), the
host executed it, and the model reported the output; trajectory persisted; GUI
verified by browser (toggle, tool block, output, final answer). 106 tests +
2 ignored green, clippy/fmt clean. Isolated mode (user-provided Docker container)
is the next step.
This commit is contained in:
adm committed 2026-11-25 02:06:45 +01:00
1 parent e29878bb3d
commit 8979201139
10 files changed
+994 -43

No files matched your search

+135 -35
View File
@@ -5,7 +5,7 @@
const $ = (sel) => document.querySelector(sel);
const state = { sessions: [], current: null, busy: false };
const state = { sessions: [], current: null, busy: false, agent: false };
// ---- API helpers ----------------------------------------------------------
async function getJSON(url) {
@@ -81,6 +81,37 @@ function scrollDown() {
t.scrollTop = t.scrollHeight;
}
function usageText(u) {
return u ? `${u.prompt_tokens} + ${u.completion_tokens} token` : null;
}
// A tool-call block (command + an output area filled when the result arrives).
function toolCallNode(name, argsJson) {
let cmd = argsJson;
try {
const a = JSON.parse(argsJson);
if (a && a.command !== undefined) cmd = a.command;
} catch { /* keep raw */ }
const wrap = el("div", "msg tool");
wrap.appendChild(el("div", "role", `\u{1F527} ${name || "tool"}`));
const bubble = el("div", "bubble");
bubble.appendChild(el("code", "tool-cmd", cmd));
const out = el("pre", "tool-out", "");
bubble.appendChild(out);
wrap.appendChild(bubble);
wrap._out = out;
return wrap;
}
function toolResultNode(output) {
const wrap = el("div", "msg tool");
wrap.appendChild(el("div", "role", "\u{1F527} output"));
const bubble = el("div", "bubble");
bubble.appendChild(el("pre", "tool-out", output));
wrap.appendChild(bubble);
return wrap;
}
// ---- Rendering ------------------------------------------------------------
function renderSessions() {
const list = $("#session-list");
@@ -95,15 +126,31 @@ function renderSessions() {
function renderTranscript(messages) {
const t = $("#transcript");
t.textContent = "";
const visible = messages.filter((m) => m.role === "user" || m.role === "assistant");
if (visible.length === 0) {
if (!messages.length) {
t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
return;
}
for (const m of visible) {
const usage = m.role === "assistant" && m.completion_tokens
? `${m.prompt_tokens} + ${m.completion_tokens} token` : null;
t.appendChild(messageNode(m.role, m.content, m.reasoning_content, usage));
for (const m of messages) {
if (m.role === "user") {
t.appendChild(messageNode("user", m.content));
} else if (m.role === "tool") {
t.appendChild(toolResultNode(m.content));
} else if (m.role === "assistant") {
if (m.tool_calls_json) {
let calls = [];
try { calls = JSON.parse(m.tool_calls_json); } catch { /* ignore */ }
for (const tc of calls) {
const f = tc.function || {};
t.appendChild(toolCallNode(f.name, f.arguments));
}
}
if (m.content) {
const usage = m.completion_tokens
? usageText({ prompt_tokens: m.prompt_tokens, completion_tokens: m.completion_tokens })
: null;
t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage));
}
}
}
scrollDown();
}
@@ -160,8 +207,25 @@ async function sendMessage() {
const empty = t.querySelector(".empty");
if (empty) empty.remove();
t.appendChild(messageNode("user", content));
scrollDown();
// Live assistant bubble.
try {
if (state.agent) await agentTurn(content, t);
else await chatTurn(content, t);
state.sessions = await getJSON("/api/sessions");
renderSessions();
} catch (e) {
t.appendChild(messageNode("assistant", `Errore: ${e.message}`));
} finally {
state.busy = false;
$("#send").disabled = false;
input.focus();
scrollDown();
}
}
// Plain chat: stream OpenAI chunks into a live assistant bubble.
async function chatTurn(content, t) {
const wrap = el("div", "msg assistant");
wrap.appendChild(el("div", "role", "Assistente"));
const bubble = el("div", "bubble");
@@ -178,35 +242,65 @@ async function sendMessage() {
scrollDown();
let reasoning = "", text = "", usage = null;
try {
await streamChat(state.current, content, (chunk) => {
const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta;
if (d && d.reasoning_content) {
reasoning += d.reasoning_content;
reasoningNode.textContent = reasoning;
det.hidden = false;
}
if (d && d.content) {
text += d.content;
contentNode.textContent = text;
}
if (chunk.usage) usage = chunk.usage;
scrollDown();
});
if (usage) {
bubble.appendChild(el("div", "usage",
`${usage.prompt_tokens} + ${usage.completion_tokens} token`));
await streamChat(state.current, content, (chunk) => {
const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta;
if (d && d.reasoning_content) {
reasoning += d.reasoning_content;
reasoningNode.textContent = reasoning;
det.hidden = false;
}
// Refresh ordering/titles without losing the live transcript.
state.sessions = await getJSON("/api/sessions");
renderSessions();
} catch (e) {
contentNode.textContent = text || `Errore: ${e.message}`;
} finally {
state.busy = false;
$("#send").disabled = false;
input.focus();
if (d && d.content) {
text += d.content;
contentNode.textContent = text;
}
if (chunk.usage) usage = chunk.usage;
scrollDown();
});
if (usage) bubble.appendChild(el("div", "usage", usageText(usage)));
}
// Agent mode: stream tool_call / tool_result / final events (observability, no gate).
async function agentTurn(content, t) {
const r = await fetch(`/api/sessions/${state.current}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, agent: true }),
});
if (!r.ok) throw new Error(await r.text());
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "";
const toolNodes = {};
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const block = buf.slice(0, idx);
buf = buf.slice(idx + 2);
for (const line of block.split("\n")) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") return;
let ev;
try { ev = JSON.parse(data); } catch { continue; }
if (ev.type === "tool_call") {
const n = toolCallNode(ev.name, ev.arguments);
toolNodes[ev.id] = n;
t.appendChild(n);
} else if (ev.type === "tool_result") {
const n = toolNodes[ev.id];
if (n) n._out.textContent = ev.output;
} else if (ev.type === "final") {
const m = ev.response.choices[0].message;
t.appendChild(messageNode("assistant", m.content || "", m.reasoning_content, usageText(ev.response.usage)));
} else if (ev.type === "error") {
t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`));
}
scrollDown();
}
}
}
}
@@ -290,6 +384,12 @@ function wire() {
$("#new-session").addEventListener("click", newSession);
$("#delete-session").addEventListener("click", deleteSession);
$("#send").addEventListener("click", sendMessage);
$("#agent-toggle").addEventListener("click", () => {
state.agent = !state.agent;
const b = $("#agent-toggle");
b.classList.toggle("active", state.agent);
b.setAttribute("aria-pressed", String(state.agent));
});
$("#show-stats").addEventListener("click", showStats);
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; });
const input = $("#input");