feat(agent): tools on by default, personal-folder cwd, streamed final answer
- GUI: agent mode (tools) enabled by default; the 🤖 toggle still turns it off.
- shell_exec defaults to the session's personal folder (~/.strata-ctl/sessions/<name>)
when the model omits cwd, so the agent's home base matches its identity reminder;
full host access retained (cd / absolute paths). run_loop gains a LoopContext
(runner/store/default_cwd/max_iters/progress) to stay within the arg-count lint.
- Agent final answer now streams live: the model step uses service.stream, emits
AgentEvent::Delta (reasoning + content) while generating, and returns the
accumulated response for tool detection + persistence. The GUI renders a live
assistant bubble (thinking auto-opens, folds when the answer starts) instead of
receiving the whole final answer at once.
- Verified live: 76 delta events over 10.75s, pwd -> sessions/<name>, correct answer.
- 122 tests + 2 ignored; clippy/fmt clean.
This commit is contained in:
1 parent
ebbd9e72e8
commit
5117ecad7a
5 files changed
+259
-40
No files matched your search
@@ -144,20 +144,23 @@ copied into `data/` once on first run (the original is left in place).
|
|||||||
|
|
||||||
## Agent mode
|
## Agent mode
|
||||||
|
|
||||||
The GUI model can **act**, not just chat. Toggle the 🤖 button and the model runs as
|
The GUI model can **act**, not just chat. Tools are **on by default** (the 🤖 button
|
||||||
an agent with a single universal tool, **`shell_exec`** (a shell is universal: file
|
toggles them): the framework is meant to act, not just chat. The agent has a single
|
||||||
ops, programs, system inspection, web via curl, git, …). A bounded server-side loop
|
universal tool, **`shell_exec`** (a shell is universal: file ops, programs, system
|
||||||
drives `model → shell_exec → result → model → … → final answer`, persisting the whole
|
inspection, web via curl, git, …). A bounded server-side loop drives
|
||||||
trajectory and streaming progress events (`tool_call` / `tool_result` / `final`) so
|
`model → shell_exec → result → model → … → final answer`, persisting the whole
|
||||||
the GUI shows every command and its output inline — **observability without a
|
trajectory and streaming progress events — `delta` (the model's thinking and final
|
||||||
confirmation gate**.
|
answer, token by token), `tool_call` / `tool_result` (every command and its output
|
||||||
|
inline) and `final` — so the wait is always visible progress, **observability without
|
||||||
|
a confirmation gate**.
|
||||||
|
|
||||||
Two operating modes are planned, separated by the *environment* rather than per-call
|
Two operating modes are planned, separated by the *environment* rather than per-call
|
||||||
approval:
|
approval:
|
||||||
|
|
||||||
- **Base / host mode** (implemented): `shell_exec` runs directly on the host via
|
- **Base / host mode** (implemented): `shell_exec` runs directly on the host via
|
||||||
`bash -lc` (with `cwd`, a timeout and an output cap). This is a trusted machine;
|
`bash -lc`, starting in the session's **personal folder** by default (override with
|
||||||
the agent has the same freedom you would give a local operator.
|
`cwd`), with a timeout and an output cap. This is a trusted machine; the agent has
|
||||||
|
the same freedom you would give a local operator.
|
||||||
- **Isolated mode** (planned): the same tool routes to a sandboxed runner — the
|
- **Isolated mode** (planned): the same tool routes to a sandboxed runner — the
|
||||||
team's Docker-container MCP server. The user supplies the container; provisioning
|
team's Docker-container MCP server. The user supplies the container; provisioning
|
||||||
is on them. Execution sits behind a `ShellRunner` trait, so the isolated runner
|
is on them. Execution sits behind a `ShellRunner` trait, so the isolated runner
|
||||||
@@ -229,7 +232,7 @@ later adaptation round.
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Working and tested (121 tests, plus 2 real-file tests run on demand). Text, images,
|
Working and tested (122 tests, plus 2 real-file tests run on demand). Text, images,
|
||||||
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
|
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
|
||||||
context, streaming, stats, **file/image upload**) and **agent mode** (the model
|
context, streaming, stats, **file/image upload**) and **agent mode** (the model
|
||||||
using `shell_exec` on the host) have been validated live against the real Inkling
|
using `shell_exec` on the host) have been validated live against the real Inkling
|
||||||
|
|||||||
+121
-18
@@ -43,6 +43,13 @@ pub enum AgentEvent {
|
|||||||
name: String,
|
name: String,
|
||||||
output: String,
|
output: String,
|
||||||
},
|
},
|
||||||
|
/// Incremental model output (reasoning / answer text) while a step generates,
|
||||||
|
/// so the GUI streams the agent's thinking and final answer live instead of
|
||||||
|
/// receiving the whole answer at once.
|
||||||
|
Delta {
|
||||||
|
content: Option<String>,
|
||||||
|
reasoning: Option<String>,
|
||||||
|
},
|
||||||
Final {
|
Final {
|
||||||
response: ChatResponse,
|
response: ChatResponse,
|
||||||
},
|
},
|
||||||
@@ -58,7 +65,12 @@ fn emit(progress: &Option<UnboundedSender<AgentEvent>>, ev: AgentEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Execute one tool call, returning the text the model reads as the tool result.
|
/// Execute one tool call, returning the text the model reads as the tool result.
|
||||||
async fn execute_tool(runner: &Arc<dyn ShellRunner>, tc: &ToolCall) -> String {
|
/// `default_cwd` (the session's personal folder) is used when the model omits cwd.
|
||||||
|
async fn execute_tool(
|
||||||
|
runner: &Arc<dyn ShellRunner>,
|
||||||
|
tc: &ToolCall,
|
||||||
|
default_cwd: Option<&str>,
|
||||||
|
) -> String {
|
||||||
if tc.function.name != "shell_exec" {
|
if tc.function.name != "shell_exec" {
|
||||||
return format!("error: unknown tool '{}'", tc.function.name);
|
return format!("error: unknown tool '{}'", tc.function.name);
|
||||||
}
|
}
|
||||||
@@ -70,10 +82,8 @@ async fn execute_tool(runner: &Arc<dyn ShellRunner>, tc: &ToolCall) -> String {
|
|||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
Err(e) => return format!("error: {e}"),
|
Err(e) => return format!("error: {e}"),
|
||||||
};
|
};
|
||||||
match runner
|
let cwd = req.cwd.as_deref().or(default_cwd);
|
||||||
.run(&req.command, req.cwd.as_deref(), req.timeout)
|
match runner.run(&req.command, cwd, req.timeout).await {
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(out) => out.to_result_text(),
|
Ok(out) => out.to_result_text(),
|
||||||
Err(e) => format!("error: {e}"),
|
Err(e) => format!("error: {e}"),
|
||||||
}
|
}
|
||||||
@@ -114,6 +124,17 @@ fn envelope(msg: impl Into<String>, code: &str) -> ApiErrorEnvelope {
|
|||||||
ApiErrorEnvelope::new(msg, "invalid_request_error", Some(code.to_string()))
|
ApiErrorEnvelope::new(msg, "invalid_request_error", Some(code.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The fixed context of one agent loop: execution runner, persistence, the
|
||||||
|
/// session's personal folder (default cwd), the iteration cap and the progress
|
||||||
|
/// channel. Bundled so `run_loop` stays within the argument-count lint.
|
||||||
|
pub struct LoopContext {
|
||||||
|
pub runner: Arc<dyn ShellRunner>,
|
||||||
|
pub store: Arc<dyn Store>,
|
||||||
|
pub default_cwd: Option<String>,
|
||||||
|
pub max_iters: usize,
|
||||||
|
pub progress: Option<UnboundedSender<AgentEvent>>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Drive the model↔tool loop until the model produces a final answer (no tool
|
/// Drive the model↔tool loop until the model produces a final answer (no tool
|
||||||
/// calls) or `max_iters` is reached. Persists the whole trajectory (assistant
|
/// calls) or `max_iters` is reached. Persists the whole trajectory (assistant
|
||||||
/// tool-call turns + tool results + final answer) and emits progress events.
|
/// tool-call turns + tool results + final answer) and emits progress events.
|
||||||
@@ -122,17 +143,21 @@ fn envelope(msg: impl Into<String>, code: &str) -> ApiErrorEnvelope {
|
|||||||
/// supplies `req` already carrying the agent tool declarations.
|
/// supplies `req` already carrying the agent tool declarations.
|
||||||
pub async fn run_loop<M, Fut>(
|
pub async fn run_loop<M, Fut>(
|
||||||
mut model: M,
|
mut model: M,
|
||||||
runner: Arc<dyn ShellRunner>,
|
ctx: LoopContext,
|
||||||
store: Arc<dyn Store>,
|
|
||||||
session_id: &str,
|
session_id: &str,
|
||||||
mut req: ChatRequest,
|
mut req: ChatRequest,
|
||||||
max_iters: usize,
|
|
||||||
progress: Option<UnboundedSender<AgentEvent>>,
|
|
||||||
) -> Result<ChatResponse, ApiErrorEnvelope>
|
) -> Result<ChatResponse, ApiErrorEnvelope>
|
||||||
where
|
where
|
||||||
M: FnMut(ChatRequest) -> Fut,
|
M: FnMut(ChatRequest) -> Fut,
|
||||||
Fut: Future<Output = Result<ChatResponse, ApiErrorEnvelope>>,
|
Fut: Future<Output = Result<ChatResponse, ApiErrorEnvelope>>,
|
||||||
{
|
{
|
||||||
|
let LoopContext {
|
||||||
|
runner,
|
||||||
|
store,
|
||||||
|
default_cwd,
|
||||||
|
max_iters,
|
||||||
|
progress,
|
||||||
|
} = ctx;
|
||||||
for _ in 0..max_iters {
|
for _ in 0..max_iters {
|
||||||
let resp = model(req.clone()).await?;
|
let resp = model(req.clone()).await?;
|
||||||
let choice = resp
|
let choice = resp
|
||||||
@@ -193,7 +218,7 @@ where
|
|||||||
arguments: tc.function.arguments.clone(),
|
arguments: tc.function.arguments.clone(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let output = execute_tool(&runner, tc).await;
|
let output = execute_tool(&runner, tc, default_cwd.as_deref()).await;
|
||||||
emit(
|
emit(
|
||||||
&progress,
|
&progress,
|
||||||
AgentEvent::ToolResult {
|
AgentEvent::ToolResult {
|
||||||
@@ -345,12 +370,15 @@ mod tests {
|
|||||||
|
|
||||||
let resp = run_loop(
|
let resp = run_loop(
|
||||||
model,
|
model,
|
||||||
runner,
|
LoopContext {
|
||||||
store.clone(),
|
runner,
|
||||||
|
store: store.clone(),
|
||||||
|
default_cwd: None,
|
||||||
|
max_iters: 8,
|
||||||
|
progress: Some(tx),
|
||||||
|
},
|
||||||
&sess.id,
|
&sess.id,
|
||||||
base_req(),
|
base_req(),
|
||||||
8,
|
|
||||||
Some(tx),
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -374,6 +402,7 @@ mod tests {
|
|||||||
kinds.push(match ev {
|
kinds.push(match ev {
|
||||||
AgentEvent::ToolCall { .. } => "call",
|
AgentEvent::ToolCall { .. } => "call",
|
||||||
AgentEvent::ToolResult { .. } => "result",
|
AgentEvent::ToolResult { .. } => "result",
|
||||||
|
AgentEvent::Delta { .. } => "delta",
|
||||||
AgentEvent::Final { .. } => "final",
|
AgentEvent::Final { .. } => "final",
|
||||||
AgentEvent::Error { .. } => "error",
|
AgentEvent::Error { .. } => "error",
|
||||||
});
|
});
|
||||||
@@ -394,9 +423,20 @@ mod tests {
|
|||||||
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
||||||
// Model always asks for a tool -> never finishes.
|
// Model always asks for a tool -> never finishes.
|
||||||
let model = move |_req: ChatRequest| async { Ok(tool_call_response()) };
|
let model = move |_req: ChatRequest| async { Ok(tool_call_response()) };
|
||||||
let err = run_loop(model, runner, store, &sess.id, base_req(), 3, None)
|
let err = run_loop(
|
||||||
.await
|
model,
|
||||||
.unwrap_err();
|
LoopContext {
|
||||||
|
runner,
|
||||||
|
store,
|
||||||
|
default_cwd: None,
|
||||||
|
max_iters: 3,
|
||||||
|
progress: None,
|
||||||
|
},
|
||||||
|
&sess.id,
|
||||||
|
base_req(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
assert_eq!(err.error.code.as_deref(), Some("agent_step_limit"));
|
assert_eq!(err.error.code.as_deref(), Some("agent_step_limit"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -411,7 +451,70 @@ mod tests {
|
|||||||
arguments: "{}".into(),
|
arguments: "{}".into(),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let out = execute_tool(&runner, &tc).await;
|
let out = execute_tool(&runner, &tc, None).await;
|
||||||
assert!(out.contains("unknown tool"));
|
assert!(out.contains("unknown tool"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn default_cwd_is_used_when_model_omits_it() {
|
||||||
|
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||||
|
let sess = store
|
||||||
|
.create_session(
|
||||||
|
"Agent",
|
||||||
|
"test-model",
|
||||||
|
&crate::store::SessionSettings::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
||||||
|
// Model asks for `pwd` with no cwd, then finishes.
|
||||||
|
let n = Arc::new(AtomicUsize::new(0));
|
||||||
|
let model = move |_req: ChatRequest| {
|
||||||
|
let n = n.clone();
|
||||||
|
async move {
|
||||||
|
if n.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||||
|
Ok(response(
|
||||||
|
ChatMessage {
|
||||||
|
role: Role::Assistant,
|
||||||
|
content: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
tool_calls: Some(vec![ToolCall {
|
||||||
|
id: "c1".into(),
|
||||||
|
kind: "function".into(),
|
||||||
|
function: FunctionCall {
|
||||||
|
name: "shell_exec".into(),
|
||||||
|
arguments: json!({"command": "pwd"}).to_string(),
|
||||||
|
},
|
||||||
|
}]),
|
||||||
|
name: None,
|
||||||
|
reasoning_content: None,
|
||||||
|
},
|
||||||
|
FinishReason::ToolCalls,
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Ok(final_response())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
run_loop(
|
||||||
|
model,
|
||||||
|
LoopContext {
|
||||||
|
runner,
|
||||||
|
store: store.clone(),
|
||||||
|
default_cwd: Some("/tmp".into()),
|
||||||
|
max_iters: 8,
|
||||||
|
progress: None,
|
||||||
|
},
|
||||||
|
&sess.id,
|
||||||
|
base_req(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let msgs = store.messages(&sess.id).unwrap();
|
||||||
|
let tool = msgs.iter().find(|m| m.role == "tool").unwrap();
|
||||||
|
assert!(
|
||||||
|
tool.content.contains("/tmp"),
|
||||||
|
"pwd should run in the default cwd: {}",
|
||||||
|
tool.content
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+3
-2
@@ -168,8 +168,9 @@ pub fn shell_exec_declaration() -> Json {
|
|||||||
"description": "Execute a shell command on the host with bash -lc and return its \
|
"description": "Execute a shell command on the host with bash -lc and return its \
|
||||||
stdout, stderr and exit code. Use it for file operations, running programs, \
|
stdout, stderr and exit code. Use it for file operations, running programs, \
|
||||||
inspecting the system, web requests via curl, git, and so on. Chain steps with \
|
inspecting the system, web requests via curl, git, and so on. Chain steps with \
|
||||||
&& or ;. State (working directory, environment) does NOT persist between calls: \
|
&& or ;. Commands start in your personal session folder by default. State \
|
||||||
pass cwd or use absolute paths.",
|
(working directory, environment) does NOT persist between calls: pass cwd or \
|
||||||
|
use absolute paths.",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
|||||||
+67
-7
@@ -16,7 +16,10 @@ use futures::StreamExt;
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::routes::{AppState, Error};
|
use super::routes::{AppState, Error};
|
||||||
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
|
use super::types::{
|
||||||
|
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
|
||||||
|
FinishReason, FunctionCall, Role, ToolCall, Usage,
|
||||||
|
};
|
||||||
use super::uploads;
|
use super::uploads;
|
||||||
use crate::agent::shell::{HostShell, ShellRunner};
|
use crate::agent::shell::{HostShell, ShellRunner};
|
||||||
use crate::agent::{self, AgentEvent};
|
use crate::agent::{self, AgentEvent};
|
||||||
@@ -433,22 +436,79 @@ pub(crate) async fn session_chat(
|
|||||||
let svc = st.service.clone();
|
let svc = st.service.clone();
|
||||||
let store2 = store.clone();
|
let store2 = store.clone();
|
||||||
let sid = id.clone();
|
let sid = id.clone();
|
||||||
|
let folder = sess.folder.clone();
|
||||||
|
let tx_model = tx.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
// Streaming model step: emit Delta events while generating (so the GUI
|
||||||
|
// shows thinking + final answer live), then return the accumulated
|
||||||
|
// response for the loop's tool detection and persistence.
|
||||||
let model = move |r: ChatRequest| {
|
let model = move |r: ChatRequest| {
|
||||||
let svc = svc.clone();
|
let svc = svc.clone();
|
||||||
async move { svc.complete(&r).await }
|
let tx = tx_model.clone();
|
||||||
|
async move {
|
||||||
|
let (mut stream, prompt_len) = svc.stream(&r).await?;
|
||||||
|
let mut acc = Accum::default();
|
||||||
|
let mut finish = FinishReason::Stop;
|
||||||
|
while let Some(chunk) = stream.next().await {
|
||||||
|
if let Some(ch) = chunk.choices.first() {
|
||||||
|
let d = &ch.delta;
|
||||||
|
if d.content.is_some() || d.reasoning_content.is_some() {
|
||||||
|
let _ = tx.send(AgentEvent::Delta {
|
||||||
|
content: d.content.clone(),
|
||||||
|
reasoning: d.reasoning_content.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(f) = &ch.finish_reason {
|
||||||
|
finish = *f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
accumulate(&mut acc, &chunk);
|
||||||
|
}
|
||||||
|
let tools: Vec<ToolCall> = acc.tools.values().cloned().collect();
|
||||||
|
let has_tools = !tools.is_empty();
|
||||||
|
let usage = acc.usage.unwrap_or_else(|| Usage::new(prompt_len, 0));
|
||||||
|
Ok(ChatResponse {
|
||||||
|
id: completion_id(),
|
||||||
|
object: "chat.completion",
|
||||||
|
created: now_unix(),
|
||||||
|
model: r.model.clone(),
|
||||||
|
choices: vec![Choice {
|
||||||
|
index: 0,
|
||||||
|
message: ChatMessage {
|
||||||
|
role: Role::Assistant,
|
||||||
|
content: (!acc.content.is_empty())
|
||||||
|
.then_some(serde_json::Value::String(acc.content)),
|
||||||
|
tool_call_id: None,
|
||||||
|
tool_calls: has_tools.then_some(tools),
|
||||||
|
name: None,
|
||||||
|
reasoning_content: (!acc.reasoning.is_empty())
|
||||||
|
.then_some(acc.reasoning),
|
||||||
|
},
|
||||||
|
finish_reason: if has_tools {
|
||||||
|
FinishReason::ToolCalls
|
||||||
|
} else {
|
||||||
|
finish
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
usage,
|
||||||
|
})
|
||||||
|
}
|
||||||
};
|
};
|
||||||
// Base mode: the host shell. Isolated mode will swap in a Docker-MCP
|
// Base mode: the host shell. Isolated mode will swap in a Docker-MCP
|
||||||
// runner behind the same ShellRunner seam.
|
// runner behind the same ShellRunner seam. Commands default to the
|
||||||
|
// session's personal folder (its home base).
|
||||||
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
||||||
if let Err(env) = agent::run_loop(
|
if let Err(env) = agent::run_loop(
|
||||||
model,
|
model,
|
||||||
runner,
|
agent::LoopContext {
|
||||||
store2,
|
runner,
|
||||||
|
store: store2,
|
||||||
|
default_cwd: folder,
|
||||||
|
max_iters: agent::MAX_ITERS,
|
||||||
|
progress: Some(tx.clone()),
|
||||||
|
},
|
||||||
&sid,
|
&sid,
|
||||||
req,
|
req,
|
||||||
agent::MAX_ITERS,
|
|
||||||
Some(tx.clone()),
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
|
|||||||
+55
-3
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
const $ = (sel) => document.querySelector(sel);
|
const $ = (sel) => document.querySelector(sel);
|
||||||
|
|
||||||
const state = { sessions: [], current: null, busy: false, agent: false, attachments: [] };
|
const state = { sessions: [], current: null, busy: false, agent: true, attachments: [] };
|
||||||
|
|
||||||
// ---- i18n: new user-facing strings go through t(key, params) --------------
|
// ---- i18n: new user-facing strings go through t(key, params) --------------
|
||||||
// Catalogs are served at /assets/locales/<lang>.json; language follows the
|
// Catalogs are served at /assets/locales/<lang>.json; language follows the
|
||||||
@@ -405,6 +405,30 @@ async function agentTurn(content, t, attachments) {
|
|||||||
const dec = new TextDecoder();
|
const dec = new TextDecoder();
|
||||||
let buf = "";
|
let buf = "";
|
||||||
const toolNodes = {};
|
const toolNodes = {};
|
||||||
|
let live = null; // the assistant bubble currently being streamed
|
||||||
|
|
||||||
|
function ensureLive() {
|
||||||
|
if (live) return live;
|
||||||
|
const wrap = el("div", "msg assistant");
|
||||||
|
wrap.appendChild(el("div", "role", "Assistente"));
|
||||||
|
const bubble = el("div", "bubble");
|
||||||
|
const det = el("details", "thinking");
|
||||||
|
det.appendChild(el("summary", null, "Pensiero"));
|
||||||
|
const reasoningNode = el("div", "reasoning", "");
|
||||||
|
det.appendChild(reasoningNode);
|
||||||
|
det.hidden = true;
|
||||||
|
const contentNode = el("div", "content", "");
|
||||||
|
bubble.appendChild(det);
|
||||||
|
bubble.appendChild(contentNode);
|
||||||
|
wrap.appendChild(bubble);
|
||||||
|
t.appendChild(wrap);
|
||||||
|
live = { bubble, det, reasoningNode, contentNode, reasoning: "", text: "" };
|
||||||
|
return live;
|
||||||
|
}
|
||||||
|
function closeLive() {
|
||||||
|
if (live) { live.det.open = false; live = null; }
|
||||||
|
}
|
||||||
|
|
||||||
for (;;) {
|
for (;;) {
|
||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
@@ -419,7 +443,21 @@ async function agentTurn(content, t, attachments) {
|
|||||||
if (data === "[DONE]") return;
|
if (data === "[DONE]") return;
|
||||||
let ev;
|
let ev;
|
||||||
try { ev = JSON.parse(data); } catch { continue; }
|
try { ev = JSON.parse(data); } catch { continue; }
|
||||||
if (ev.type === "tool_call") {
|
if (ev.type === "delta") {
|
||||||
|
const L = ensureLive();
|
||||||
|
if (ev.reasoning) {
|
||||||
|
L.reasoning += ev.reasoning;
|
||||||
|
L.reasoningNode.textContent = L.reasoning;
|
||||||
|
L.det.hidden = false;
|
||||||
|
L.det.open = true;
|
||||||
|
}
|
||||||
|
if (ev.content) {
|
||||||
|
if (!L.text) L.det.open = false;
|
||||||
|
L.text += ev.content;
|
||||||
|
L.contentNode.textContent = L.text;
|
||||||
|
}
|
||||||
|
} else if (ev.type === "tool_call") {
|
||||||
|
closeLive();
|
||||||
const n = toolCallNode(ev.name, ev.arguments);
|
const n = toolCallNode(ev.name, ev.arguments);
|
||||||
toolNodes[ev.id] = n;
|
toolNodes[ev.id] = n;
|
||||||
t.appendChild(n);
|
t.appendChild(n);
|
||||||
@@ -427,9 +465,19 @@ async function agentTurn(content, t, attachments) {
|
|||||||
const n = toolNodes[ev.id];
|
const n = toolNodes[ev.id];
|
||||||
if (n) n._out.textContent = ev.output;
|
if (n) n._out.textContent = ev.output;
|
||||||
} else if (ev.type === "final") {
|
} else if (ev.type === "final") {
|
||||||
|
const L = ensureLive();
|
||||||
const m = ev.response.choices[0].message;
|
const m = ev.response.choices[0].message;
|
||||||
t.appendChild(messageNode("assistant", m.content || "", m.reasoning_content, usageText(ev.response.usage)));
|
if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = m.content; }
|
||||||
|
if (!L.reasoning && m.reasoning_content) {
|
||||||
|
L.reasoning = m.reasoning_content;
|
||||||
|
L.reasoningNode.textContent = m.reasoning;
|
||||||
|
L.det.hidden = false;
|
||||||
|
}
|
||||||
|
L.det.open = false;
|
||||||
|
if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage)));
|
||||||
|
live = null;
|
||||||
} else if (ev.type === "error") {
|
} else if (ev.type === "error") {
|
||||||
|
closeLive();
|
||||||
t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`));
|
t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`));
|
||||||
}
|
}
|
||||||
scrollDown();
|
scrollDown();
|
||||||
@@ -652,6 +700,10 @@ function wire() {
|
|||||||
b.classList.toggle("active", state.agent);
|
b.classList.toggle("active", state.agent);
|
||||||
b.setAttribute("aria-pressed", String(state.agent));
|
b.setAttribute("aria-pressed", String(state.agent));
|
||||||
});
|
});
|
||||||
|
// Tools are on by default: the framework is meant to act, not just chat.
|
||||||
|
const ab = $("#agent-toggle");
|
||||||
|
ab.classList.toggle("active", state.agent);
|
||||||
|
ab.setAttribute("aria-pressed", String(state.agent));
|
||||||
$("#show-stats").addEventListener("click", showStats);
|
$("#show-stats").addEventListener("click", showStats);
|
||||||
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; });
|
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; });
|
||||||
$("#show-settings").addEventListener("click", () => openSettings("session"));
|
$("#show-settings").addEventListener("click", () => openSettings("session"));
|
||||||
|
|||||||
Reference in new issue
Block a user