Revert to tokio::sync::Mutex, fix lock-across-await bugs, move input ownership to InteractScreen
The std::sync::Mutex detour caught every place a MutexGuard lived across an await point in Agent::turn — the compiler enforced Send safety that tokio::sync::Mutex silently allows. With those fixed, switch back to tokio::sync::Mutex (std::sync blocks tokio worker threads and panics inside the runtime). Input and command dispatch now live in InteractScreen (chat.rs): - Enter pushes directly to SharedMindState.input (no app.submitted hop) - sync_from_agent displays pending input with dimmed color - Slash command table moved from event_loop.rs to chat.rs - cmd_switch_model kept as pub fn for tool-initiated switches Co-Authored-By: Proof of Concept <poc@bcachefs.org>
This commit is contained in:
parent
3e1be4d353
commit
48beb8b663
9 changed files with 404 additions and 370 deletions
|
|
@ -621,7 +621,7 @@ pub async fn collect_stream(
|
||||||
rx: &mut mpsc::UnboundedReceiver<StreamEvent>,
|
rx: &mut mpsc::UnboundedReceiver<StreamEvent>,
|
||||||
ui_tx: &UiSender,
|
ui_tx: &UiSender,
|
||||||
target: StreamTarget,
|
target: StreamTarget,
|
||||||
agent: &std::sync::Arc<std::sync::Mutex<super::Agent>>,
|
agent: &std::sync::Arc<tokio::sync::Mutex<super::Agent>>,
|
||||||
active_tools: &crate::user::ui_channel::SharedActiveTools,
|
active_tools: &crate::user::ui_channel::SharedActiveTools,
|
||||||
) -> StreamResult {
|
) -> StreamResult {
|
||||||
let mut content = String::new();
|
let mut content = String::new();
|
||||||
|
|
|
||||||
|
|
@ -232,14 +232,16 @@ impl Agent {
|
||||||
/// Takes Arc<Mutex<Agent>> and manages locking internally so the
|
/// Takes Arc<Mutex<Agent>> and manages locking internally so the
|
||||||
/// lock is never held across I/O (API streaming, tool dispatch).
|
/// lock is never held across I/O (API streaming, tool dispatch).
|
||||||
pub async fn turn(
|
pub async fn turn(
|
||||||
agent: Arc<std::sync::Mutex<Agent>>,
|
agent: Arc<tokio::sync::Mutex<Agent>>,
|
||||||
user_input: &str,
|
user_input: &str,
|
||||||
ui_tx: &UiSender,
|
ui_tx: &UiSender,
|
||||||
target: StreamTarget,
|
target: StreamTarget,
|
||||||
) -> Result<TurnResult> {
|
) -> Result<TurnResult> {
|
||||||
// --- Pre-loop setup (lock 1): agent cycle, memories, user input ---
|
// --- Pre-loop setup (lock 1): agent cycle, memories, user input ---
|
||||||
let active_tools = {
|
let active_tools = {
|
||||||
let mut me = agent.lock().unwrap();
|
let mut finished = Vec::new();
|
||||||
|
let tools = {
|
||||||
|
let mut me = agent.lock().await;
|
||||||
|
|
||||||
let cycle = me.run_agent_cycle();
|
let cycle = me.run_agent_cycle();
|
||||||
for key in &cycle.surfaced_keys {
|
for key in &cycle.surfaced_keys {
|
||||||
|
|
@ -261,32 +263,40 @@ impl Agent {
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Collect completed background tool calls
|
// Collect completed background tool handles — remove from active list
|
||||||
let mut bg_ds = DispatchState::new();
|
// but don't await yet (MutexGuard isn't Send).
|
||||||
let finished: Vec<_> = {
|
|
||||||
let mut tools = me.active_tools.lock().unwrap();
|
let mut tools = me.active_tools.lock().unwrap();
|
||||||
let mut done = Vec::new();
|
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
while i < tools.len() {
|
while i < tools.len() {
|
||||||
if tools[i].handle.is_finished() {
|
if tools[i].handle.is_finished() {
|
||||||
done.push(tools.remove(i));
|
finished.push(tools.remove(i));
|
||||||
} else {
|
} else {
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
done
|
|
||||||
|
me.active_tools.clone()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Await finished handles without holding the agent lock
|
||||||
|
let mut bg_results = Vec::new();
|
||||||
for entry in finished {
|
for entry in finished {
|
||||||
if let Ok((call, output)) = entry.handle.await {
|
if let Ok((call, output)) = entry.handle.await {
|
||||||
|
bg_results.push((call, output));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-acquire to apply results and push user input
|
||||||
|
{
|
||||||
|
let mut me = agent.lock().await;
|
||||||
|
let mut bg_ds = DispatchState::new();
|
||||||
|
for (call, output) in bg_results {
|
||||||
me.apply_tool_result(&call, output, ui_tx, &mut bg_ds);
|
me.apply_tool_result(&call, output, ui_tx, &mut bg_ds);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
me.push_message(Message::user(user_input));
|
me.push_message(Message::user(user_input));
|
||||||
let _ = ui_tx.send(UiMessage::AgentUpdate(me.agent_cycles.snapshots()));
|
let _ = ui_tx.send(UiMessage::AgentUpdate(me.agent_cycles.snapshots()));
|
||||||
|
}
|
||||||
|
|
||||||
let tools = me.active_tools.clone();
|
|
||||||
drop(me);
|
|
||||||
tools
|
tools
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -299,7 +309,7 @@ impl Agent {
|
||||||
|
|
||||||
// --- Lock 2: assemble messages, start stream ---
|
// --- Lock 2: assemble messages, start stream ---
|
||||||
let (mut rx, _stream_guard) = {
|
let (mut rx, _stream_guard) = {
|
||||||
let me = agent.lock().unwrap();
|
let me = agent.lock().await;
|
||||||
let api_messages = me.assemble_api_messages();
|
let api_messages = me.assemble_api_messages();
|
||||||
let sampling = api::SamplingParams {
|
let sampling = api::SamplingParams {
|
||||||
temperature: me.temperature,
|
temperature: me.temperature,
|
||||||
|
|
@ -328,8 +338,8 @@ impl Agent {
|
||||||
// --- Stream complete ---
|
// --- Stream complete ---
|
||||||
|
|
||||||
// --- Lock 3: process results ---
|
// --- Lock 3: process results ---
|
||||||
{
|
let (msg, pending) = {
|
||||||
let mut me = agent.lock().unwrap();
|
let mut me = agent.lock().await;
|
||||||
|
|
||||||
// Handle stream errors with retry logic
|
// Handle stream errors with retry logic
|
||||||
if let Some(e) = stream_error {
|
if let Some(e) = stream_error {
|
||||||
|
|
@ -409,7 +419,6 @@ impl Agent {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Collect non-background tool calls fired during streaming
|
// Collect non-background tool calls fired during streaming
|
||||||
let pending: Vec<_> = {
|
|
||||||
let mut tools_guard = active_tools.lock().unwrap();
|
let mut tools_guard = active_tools.lock().unwrap();
|
||||||
let mut non_bg = Vec::new();
|
let mut non_bg = Vec::new();
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
|
|
@ -420,13 +429,13 @@ impl Agent {
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
non_bg
|
(msg, non_bg)
|
||||||
};
|
};
|
||||||
|
|
||||||
if !pending.is_empty() {
|
if !pending.is_empty() {
|
||||||
me.push_message(msg.clone());
|
agent.lock().await.push_message(msg.clone());
|
||||||
|
|
||||||
// Drop lock before awaiting tool handles
|
// Drop lock before awaiting tool handles
|
||||||
drop(me);
|
|
||||||
let mut results = Vec::new();
|
let mut results = Vec::new();
|
||||||
for entry in pending {
|
for entry in pending {
|
||||||
if let Ok(r) = entry.handle.await {
|
if let Ok(r) = entry.handle.await {
|
||||||
|
|
@ -434,7 +443,7 @@ impl Agent {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Reacquire to apply results
|
// Reacquire to apply results
|
||||||
let mut me = agent.lock().unwrap();
|
let mut me = agent.lock().await;
|
||||||
for (call, output) in results {
|
for (call, output) in results {
|
||||||
me.apply_tool_result(&call, output, ui_tx, &mut ds);
|
me.apply_tool_result(&call, output, ui_tx, &mut ds);
|
||||||
}
|
}
|
||||||
|
|
@ -445,10 +454,9 @@ impl Agent {
|
||||||
// Tool calls (structured API path)
|
// Tool calls (structured API path)
|
||||||
if let Some(ref tool_calls) = msg.tool_calls {
|
if let Some(ref tool_calls) = msg.tool_calls {
|
||||||
if !tool_calls.is_empty() {
|
if !tool_calls.is_empty() {
|
||||||
me.push_message(msg.clone());
|
agent.lock().await.push_message(msg.clone());
|
||||||
let calls: Vec<ToolCall> = tool_calls.clone();
|
let calls: Vec<ToolCall> = tool_calls.clone();
|
||||||
// Drop lock before tool dispatch
|
// Drop lock before tool dispatch
|
||||||
drop(me);
|
|
||||||
for call in &calls {
|
for call in &calls {
|
||||||
Agent::dispatch_tool_call_unlocked(
|
Agent::dispatch_tool_call_unlocked(
|
||||||
&agent, &active_tools, call, ui_tx, &mut ds,
|
&agent, &active_tools, call, ui_tx, &mut ds,
|
||||||
|
|
@ -461,6 +469,7 @@ impl Agent {
|
||||||
// Genuinely text-only response
|
// Genuinely text-only response
|
||||||
let text = msg.content_text().to_string();
|
let text = msg.content_text().to_string();
|
||||||
let _ = ui_tx.send(UiMessage::Activity(String::new()));
|
let _ = ui_tx.send(UiMessage::Activity(String::new()));
|
||||||
|
let mut me = agent.lock().await;
|
||||||
me.push_message(msg);
|
me.push_message(msg);
|
||||||
|
|
||||||
// Drain pending control flags
|
// Drain pending control flags
|
||||||
|
|
@ -478,12 +487,11 @@ impl Agent {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Dispatch a tool call without holding the agent lock across I/O.
|
/// Dispatch a tool call without holding the agent lock across I/O.
|
||||||
/// Used by `turn()` which manages its own locking.
|
/// Used by `turn()` which manages its own locking.
|
||||||
async fn dispatch_tool_call_unlocked(
|
async fn dispatch_tool_call_unlocked(
|
||||||
agent: &Arc<std::sync::Mutex<Agent>>,
|
agent: &Arc<tokio::sync::Mutex<Agent>>,
|
||||||
active_tools: &crate::user::ui_channel::SharedActiveTools,
|
active_tools: &crate::user::ui_channel::SharedActiveTools,
|
||||||
call: &ToolCall,
|
call: &ToolCall,
|
||||||
ui_tx: &UiSender,
|
ui_tx: &UiSender,
|
||||||
|
|
@ -494,7 +502,7 @@ impl Agent {
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let err = format!("Error: malformed tool call arguments: {e}");
|
let err = format!("Error: malformed tool call arguments: {e}");
|
||||||
let _ = ui_tx.send(UiMessage::Activity(format!("rejected: {} (bad args)", call.function.name)));
|
let _ = ui_tx.send(UiMessage::Activity(format!("rejected: {} (bad args)", call.function.name)));
|
||||||
let mut me = agent.lock().unwrap();
|
let mut me = agent.lock().await;
|
||||||
me.apply_tool_result(call, err, ui_tx, ds);
|
me.apply_tool_result(call, err, ui_tx, ds);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -532,7 +540,7 @@ impl Agent {
|
||||||
};
|
};
|
||||||
if let Ok((call, output)) = entry.handle.await {
|
if let Ok((call, output)) = entry.handle.await {
|
||||||
// Brief lock to apply result
|
// Brief lock to apply result
|
||||||
let mut me = agent.lock().unwrap();
|
let mut me = agent.lock().await;
|
||||||
me.apply_tool_result(&call, output, ui_tx, ds);
|
me.apply_tool_result(&call, output, ui_tx, ds);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ pub(super) fn tools() -> [super::Tool; 3] {
|
||||||
.ok_or_else(|| anyhow::anyhow!("'model' parameter is required"))?;
|
.ok_or_else(|| anyhow::anyhow!("'model' parameter is required"))?;
|
||||||
if model.is_empty() { anyhow::bail!("'model' parameter cannot be empty"); }
|
if model.is_empty() { anyhow::bail!("'model' parameter cannot be empty"); }
|
||||||
if let Some(agent) = agent {
|
if let Some(agent) = agent {
|
||||||
let mut a = agent.lock().unwrap();
|
let mut a = agent.lock().await;
|
||||||
a.pending_model_switch = Some(model.to_string());
|
a.pending_model_switch = Some(model.to_string());
|
||||||
}
|
}
|
||||||
Ok(format!("Switching to model '{}' after this turn.", model))
|
Ok(format!("Switching to model '{}' after this turn.", model))
|
||||||
|
|
@ -24,7 +24,7 @@ pub(super) fn tools() -> [super::Tool; 3] {
|
||||||
parameters_json: r#"{"type":"object","properties":{}}"#,
|
parameters_json: r#"{"type":"object","properties":{}}"#,
|
||||||
handler: |agent, _v| Box::pin(async move {
|
handler: |agent, _v| Box::pin(async move {
|
||||||
if let Some(agent) = agent {
|
if let Some(agent) = agent {
|
||||||
let mut a = agent.lock().unwrap();
|
let mut a = agent.lock().await;
|
||||||
a.pending_yield = true;
|
a.pending_yield = true;
|
||||||
a.pending_dmn_pause = true;
|
a.pending_dmn_pause = true;
|
||||||
}
|
}
|
||||||
|
|
@ -36,7 +36,7 @@ pub(super) fn tools() -> [super::Tool; 3] {
|
||||||
handler: |agent, v| Box::pin(async move {
|
handler: |agent, v| Box::pin(async move {
|
||||||
let msg = v.get("message").and_then(|v| v.as_str()).unwrap_or("Waiting for input.");
|
let msg = v.get("message").and_then(|v| v.as_str()).unwrap_or("Waiting for input.");
|
||||||
if let Some(agent) = agent {
|
if let Some(agent) = agent {
|
||||||
let mut a = agent.lock().unwrap();
|
let mut a = agent.lock().await;
|
||||||
a.pending_yield = true;
|
a.pending_yield = true;
|
||||||
}
|
}
|
||||||
Ok(format!("Yielding. {}", msg))
|
Ok(format!("Yielding. {}", msg))
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ fn default_timeout() -> u64 { 120 }
|
||||||
/// Async tool handler function.
|
/// Async tool handler function.
|
||||||
/// Agent is None when called from contexts without an agent (MCP server, subconscious).
|
/// Agent is None when called from contexts without an agent (MCP server, subconscious).
|
||||||
pub type ToolHandler = fn(
|
pub type ToolHandler = fn(
|
||||||
Option<std::sync::Arc<std::sync::Mutex<super::Agent>>>,
|
Option<std::sync::Arc<tokio::sync::Mutex<super::Agent>>>,
|
||||||
serde_json::Value,
|
serde_json::Value,
|
||||||
) -> Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send>>;
|
) -> Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send>>;
|
||||||
|
|
||||||
|
|
@ -94,11 +94,11 @@ pub async fn dispatch(
|
||||||
pub async fn dispatch_with_agent(
|
pub async fn dispatch_with_agent(
|
||||||
name: &str,
|
name: &str,
|
||||||
args: &serde_json::Value,
|
args: &serde_json::Value,
|
||||||
agent: Option<std::sync::Arc<std::sync::Mutex<super::Agent>>>,
|
agent: Option<std::sync::Arc<tokio::sync::Mutex<super::Agent>>>,
|
||||||
) -> String {
|
) -> String {
|
||||||
// Look up in agent's tools if available, otherwise global
|
// Look up in agent's tools if available, otherwise global
|
||||||
let tool = if let Some(ref a) = agent {
|
let tool = if let Some(ref a) = agent {
|
||||||
let guard = a.lock().unwrap();
|
let guard = a.lock().await;
|
||||||
guard.tools.iter().find(|t| t.name == name).copied()
|
guard.tools.iter().find(|t| t.name == name).copied()
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,7 @@ pub fn tool() -> super::Tool {
|
||||||
parameters_json: r#"{"type":"object","properties":{"action":{"type":"string","enum":["push","pop","update","switch"],"description":"Stack operation"},"content":{"type":"string","description":"Task description (for push/update)"},"index":{"type":"integer","description":"Stack index (for switch, 0=bottom)"}},"required":["action"]}"#,
|
parameters_json: r#"{"type":"object","properties":{"action":{"type":"string","enum":["push","pop","update","switch"],"description":"Stack operation"},"content":{"type":"string","description":"Task description (for push/update)"},"index":{"type":"integer","description":"Stack index (for switch, 0=bottom)"}},"required":["action"]}"#,
|
||||||
handler: |agent, v| Box::pin(async move {
|
handler: |agent, v| Box::pin(async move {
|
||||||
if let Some(agent) = agent {
|
if let Some(agent) = agent {
|
||||||
let mut a = agent.lock().unwrap();
|
let mut a = agent.lock().await;
|
||||||
Ok(handle(&v, &mut a.context.working_stack))
|
Ok(handle(&v, &mut a.context.working_stack))
|
||||||
} else {
|
} else {
|
||||||
anyhow::bail!("working_stack requires agent context")
|
anyhow::bail!("working_stack requires agent context")
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,6 @@ use anyhow::Result;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
use crate::agent::{Agent, TurnResult};
|
use crate::agent::{Agent, TurnResult};
|
||||||
use crate::agent::api::ApiClient;
|
use crate::agent::api::ApiClient;
|
||||||
use crate::config::{AppConfig, SessionConfig};
|
use crate::config::{AppConfig, SessionConfig};
|
||||||
|
|
@ -191,8 +189,8 @@ enum BgEvent {
|
||||||
pub type SharedMindState = std::sync::Mutex<MindState>;
|
pub type SharedMindState = std::sync::Mutex<MindState>;
|
||||||
|
|
||||||
pub struct Mind {
|
pub struct Mind {
|
||||||
pub agent: Arc<Mutex<Agent>>,
|
pub agent: Arc<tokio::sync::Mutex<Agent>>,
|
||||||
pub shared: SharedMindState,
|
pub shared: Arc<SharedMindState>,
|
||||||
pub config: SessionConfig,
|
pub config: SessionConfig,
|
||||||
ui_tx: ui_channel::UiSender,
|
ui_tx: ui_channel::UiSender,
|
||||||
turn_tx: mpsc::Sender<(Result<TurnResult>, StreamTarget)>,
|
turn_tx: mpsc::Sender<(Result<TurnResult>, StreamTarget)>,
|
||||||
|
|
@ -216,7 +214,7 @@ impl Mind {
|
||||||
config.session_dir.join("conversation.jsonl"),
|
config.session_dir.join("conversation.jsonl"),
|
||||||
).ok();
|
).ok();
|
||||||
|
|
||||||
let agent = Arc::new(Mutex::new(Agent::new(
|
let agent = Arc::new(tokio::sync::Mutex::new(Agent::new(
|
||||||
client,
|
client,
|
||||||
config.system_prompt.clone(),
|
config.system_prompt.clone(),
|
||||||
config.context_parts.clone(),
|
config.context_parts.clone(),
|
||||||
|
|
@ -227,7 +225,7 @@ impl Mind {
|
||||||
shared_active_tools,
|
shared_active_tools,
|
||||||
)));
|
)));
|
||||||
|
|
||||||
let shared = std::sync::Mutex::new(MindState::new(config.app.dmn.max_turns));
|
let shared = Arc::new(std::sync::Mutex::new(MindState::new(config.app.dmn.max_turns)));
|
||||||
let (turn_watch, _) = tokio::sync::watch::channel(false);
|
let (turn_watch, _) = tokio::sync::watch::channel(false);
|
||||||
let (bg_tx, bg_rx) = mpsc::unbounded_channel();
|
let (bg_tx, bg_rx) = mpsc::unbounded_channel();
|
||||||
|
|
||||||
|
|
@ -242,7 +240,7 @@ impl Mind {
|
||||||
/// Initialize — restore log, start daemons and background agents.
|
/// Initialize — restore log, start daemons and background agents.
|
||||||
pub async fn init(&self) {
|
pub async fn init(&self) {
|
||||||
// Restore conversation
|
// Restore conversation
|
||||||
let mut ag = self.agent.lock().unwrap();
|
let mut ag = self.agent.lock().await;
|
||||||
ag.restore_from_log();
|
ag.restore_from_log();
|
||||||
drop(ag);
|
drop(ag);
|
||||||
}
|
}
|
||||||
|
|
@ -258,7 +256,7 @@ impl Mind {
|
||||||
MindCommand::None => {}
|
MindCommand::None => {}
|
||||||
MindCommand::Compact => {
|
MindCommand::Compact => {
|
||||||
let threshold = compaction_threshold(&self.config.app);
|
let threshold = compaction_threshold(&self.config.app);
|
||||||
let mut ag = self.agent.lock().unwrap();
|
let mut ag = self.agent.lock().await;
|
||||||
if ag.last_prompt_tokens() > threshold {
|
if ag.last_prompt_tokens() > threshold {
|
||||||
ag.compact();
|
ag.compact();
|
||||||
}
|
}
|
||||||
|
|
@ -273,7 +271,7 @@ impl Mind {
|
||||||
}
|
}
|
||||||
MindCommand::Interrupt => {
|
MindCommand::Interrupt => {
|
||||||
self.shared.lock().unwrap().interrupt();
|
self.shared.lock().unwrap().interrupt();
|
||||||
let ag = self.agent.lock().unwrap();
|
let ag = self.agent.lock().await;
|
||||||
let mut tools = ag.active_tools.lock().unwrap();
|
let mut tools = ag.active_tools.lock().unwrap();
|
||||||
for entry in tools.drain(..) { entry.handle.abort(); }
|
for entry in tools.drain(..) { entry.handle.abort(); }
|
||||||
drop(tools); drop(ag);
|
drop(tools); drop(ag);
|
||||||
|
|
@ -290,7 +288,7 @@ impl Mind {
|
||||||
let new_log = log::ConversationLog::new(
|
let new_log = log::ConversationLog::new(
|
||||||
self.config.session_dir.join("conversation.jsonl"),
|
self.config.session_dir.join("conversation.jsonl"),
|
||||||
).ok();
|
).ok();
|
||||||
let mut ag = self.agent.lock().unwrap();
|
let mut ag = self.agent.lock().await;
|
||||||
let shared_ctx = ag.shared_context.clone();
|
let shared_ctx = ag.shared_context.clone();
|
||||||
let shared_tools = ag.active_tools.clone();
|
let shared_tools = ag.active_tools.clone();
|
||||||
*ag = Agent::new(
|
*ag = Agent::new(
|
||||||
|
|
@ -324,7 +322,7 @@ impl Mind {
|
||||||
let response_window = cfg.scoring_response_window;
|
let response_window = cfg.scoring_response_window;
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let (context, client) = {
|
let (context, client) = {
|
||||||
let mut ag = agent.lock().unwrap();
|
let mut ag = agent.lock().await;
|
||||||
if ag.agent_cycles.memory_scoring_in_flight { return; }
|
if ag.agent_cycles.memory_scoring_in_flight { return; }
|
||||||
ag.agent_cycles.memory_scoring_in_flight = true;
|
ag.agent_cycles.memory_scoring_in_flight = true;
|
||||||
(ag.context.clone(), ag.client_clone())
|
(ag.context.clone(), ag.client_clone())
|
||||||
|
|
@ -333,7 +331,7 @@ impl Mind {
|
||||||
&context, max_age as i64, response_window, &client, &ui_tx,
|
&context, max_age as i64, response_window, &client, &ui_tx,
|
||||||
).await;
|
).await;
|
||||||
{
|
{
|
||||||
let mut ag = agent.lock().unwrap();
|
let mut ag = agent.lock().await;
|
||||||
ag.agent_cycles.memory_scoring_in_flight = false;
|
ag.agent_cycles.memory_scoring_in_flight = false;
|
||||||
if let Ok(ref scores) = result { ag.agent_cycles.memory_scores = scores.clone(); }
|
if let Ok(ref scores) = result { ag.agent_cycles.memory_scores = scores.clone(); }
|
||||||
}
|
}
|
||||||
|
|
@ -383,12 +381,12 @@ impl Mind {
|
||||||
let _ = self.turn_watch.send(false);
|
let _ = self.turn_watch.send(false);
|
||||||
|
|
||||||
if let Some(name) = model_switch {
|
if let Some(name) = model_switch {
|
||||||
crate::user::event_loop::cmd_switch_model(&self.agent, &name, &self.ui_tx).await;
|
crate::user::chat::cmd_switch_model(&self.agent, &name, &self.ui_tx).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post-turn maintenance
|
// Post-turn maintenance
|
||||||
{
|
{
|
||||||
let mut ag = self.agent.lock().unwrap();
|
let mut ag = self.agent.lock().await;
|
||||||
ag.age_out_images();
|
ag.age_out_images();
|
||||||
ag.publish_context_state();
|
ag.publish_context_state();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -602,7 +602,7 @@ fn str_err<T>(r: Result<T, String>) -> anyhow::Result<T> {
|
||||||
|
|
||||||
/// digest_daily tool handler: generate a daily digest
|
/// digest_daily tool handler: generate a daily digest
|
||||||
async fn handle_digest_daily(
|
async fn handle_digest_daily(
|
||||||
_agent: Option<std::sync::Arc<std::sync::Mutex<super::super::agent::Agent>>>,
|
_agent: Option<std::sync::Arc<tokio::sync::Mutex<super::super::agent::Agent>>>,
|
||||||
args: serde_json::Value,
|
args: serde_json::Value,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let date = str_err(get_str_required(&args, "date"))?;
|
let date = str_err(get_str_required(&args, "date"))?;
|
||||||
|
|
@ -613,7 +613,7 @@ async fn handle_digest_daily(
|
||||||
|
|
||||||
/// digest_weekly tool handler: generate a weekly digest
|
/// digest_weekly tool handler: generate a weekly digest
|
||||||
async fn handle_digest_weekly(
|
async fn handle_digest_weekly(
|
||||||
_agent: Option<std::sync::Arc<std::sync::Mutex<super::super::agent::Agent>>>,
|
_agent: Option<std::sync::Arc<tokio::sync::Mutex<super::super::agent::Agent>>>,
|
||||||
args: serde_json::Value,
|
args: serde_json::Value,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let week_label = str_err(get_str_required(&args, "week"))?;
|
let week_label = str_err(get_str_required(&args, "week"))?;
|
||||||
|
|
@ -624,7 +624,7 @@ async fn handle_digest_weekly(
|
||||||
|
|
||||||
/// digest_monthly tool handler: generate a monthly digest
|
/// digest_monthly tool handler: generate a monthly digest
|
||||||
async fn handle_digest_monthly(
|
async fn handle_digest_monthly(
|
||||||
_agent: Option<std::sync::Arc<std::sync::Mutex<super::super::agent::Agent>>>,
|
_agent: Option<std::sync::Arc<tokio::sync::Mutex<super::super::agent::Agent>>>,
|
||||||
args: serde_json::Value,
|
args: serde_json::Value,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let month = str_err(get_str_required(&args, "month"))?;
|
let month = str_err(get_str_required(&args, "month"))?;
|
||||||
|
|
@ -635,7 +635,7 @@ async fn handle_digest_monthly(
|
||||||
|
|
||||||
/// digest_auto tool handler: auto-generate all missing digests
|
/// digest_auto tool handler: auto-generate all missing digests
|
||||||
async fn handle_digest_auto(
|
async fn handle_digest_auto(
|
||||||
_agent: Option<std::sync::Arc<std::sync::Mutex<super::super::agent::Agent>>>,
|
_agent: Option<std::sync::Arc<tokio::sync::Mutex<super::super::agent::Agent>>>,
|
||||||
_args: serde_json::Value,
|
_args: serde_json::Value,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let mut store = str_err(Store::load())?;
|
let mut store = str_err(Store::load())?;
|
||||||
|
|
@ -645,7 +645,7 @@ async fn handle_digest_auto(
|
||||||
|
|
||||||
/// digest_links tool handler: parse and apply digest links
|
/// digest_links tool handler: parse and apply digest links
|
||||||
async fn handle_digest_links(
|
async fn handle_digest_links(
|
||||||
_agent: Option<std::sync::Arc<std::sync::Mutex<super::super::agent::Agent>>>,
|
_agent: Option<std::sync::Arc<tokio::sync::Mutex<super::super::agent::Agent>>>,
|
||||||
_args: serde_json::Value,
|
_args: serde_json::Value,
|
||||||
) -> anyhow::Result<String> {
|
) -> anyhow::Result<String> {
|
||||||
let mut store = str_err(Store::load())?;
|
let mut store = str_err(Store::load())?;
|
||||||
|
|
|
||||||
225
src/user/chat.rs
225
src/user/chat.rs
|
|
@ -17,6 +17,166 @@ use super::{
|
||||||
screen_legend,
|
screen_legend,
|
||||||
};
|
};
|
||||||
use crate::user::ui_channel::{UiMessage, StreamTarget};
|
use crate::user::ui_channel::{UiMessage, StreamTarget};
|
||||||
|
use crate::mind::MindCommand;
|
||||||
|
|
||||||
|
// --- Slash command table ---
|
||||||
|
|
||||||
|
type CmdHandler = fn(&InteractScreen, &str);
|
||||||
|
|
||||||
|
struct SlashCommand {
|
||||||
|
name: &'static str,
|
||||||
|
help: &'static str,
|
||||||
|
handler: CmdHandler,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commands() -> Vec<SlashCommand> { vec![
|
||||||
|
SlashCommand { name: "/quit", help: "Exit consciousness",
|
||||||
|
handler: |_, _| {} },
|
||||||
|
SlashCommand { name: "/new", help: "Start fresh session (saves current)",
|
||||||
|
handler: |s, _| { let _ = s.mind_tx.send(MindCommand::NewSession); } },
|
||||||
|
SlashCommand { name: "/save", help: "Save session to disk",
|
||||||
|
handler: |s, _| { let _ = s.ui_tx.send(UiMessage::Info("Conversation is saved automatically.".into())); } },
|
||||||
|
SlashCommand { name: "/retry", help: "Re-run last turn",
|
||||||
|
handler: |s, _| {
|
||||||
|
let agent = s.agent.clone();
|
||||||
|
let mind_tx = s.mind_tx.clone();
|
||||||
|
let ui_tx = s.ui_tx.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut ag = agent.lock().await;
|
||||||
|
let entries = ag.entries_mut();
|
||||||
|
let mut last_user_text = None;
|
||||||
|
while let Some(entry) = entries.last() {
|
||||||
|
if entry.message().role == crate::agent::api::types::Role::User {
|
||||||
|
last_user_text = Some(entries.pop().unwrap().message().content_text().to_string());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
entries.pop();
|
||||||
|
}
|
||||||
|
drop(ag);
|
||||||
|
match last_user_text {
|
||||||
|
Some(text) => {
|
||||||
|
let preview = &text[..text.len().min(60)];
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(format!("(retrying: {}...)", preview)));
|
||||||
|
let _ = mind_tx.send(MindCommand::Turn(text, StreamTarget::Conversation));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let _ = ui_tx.send(UiMessage::Info("(nothing to retry)".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/model", help: "Show/switch model (/model <name>)",
|
||||||
|
handler: |s, arg| {
|
||||||
|
if arg.is_empty() {
|
||||||
|
if let Ok(ag) = s.agent.try_lock() {
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info(format!("Current model: {}", ag.model())));
|
||||||
|
let names = ag.app_config.model_names();
|
||||||
|
if !names.is_empty() {
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info(format!("Available: {}", names.join(", "))));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info("(busy)".into()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let agent = s.agent.clone();
|
||||||
|
let ui_tx = s.ui_tx.clone();
|
||||||
|
let name = arg.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
cmd_switch_model(&agent, &name, &ui_tx).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/score", help: "Score memory importance",
|
||||||
|
handler: |s, _| { let _ = s.mind_tx.send(MindCommand::Score); } },
|
||||||
|
SlashCommand { name: "/dmn", help: "Show DMN state",
|
||||||
|
handler: |s, _| {
|
||||||
|
let st = s.shared_mind.lock().unwrap();
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info(format!(
|
||||||
|
"DMN: {:?} ({}/{})", st.dmn, st.dmn_turns, st.max_dmn_turns,
|
||||||
|
)));
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/sleep", help: "Put DMN to sleep",
|
||||||
|
handler: |s, _| {
|
||||||
|
let mut st = s.shared_mind.lock().unwrap();
|
||||||
|
st.dmn = crate::mind::dmn::State::Resting { since: std::time::Instant::now() };
|
||||||
|
st.dmn_turns = 0;
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info("DMN sleeping.".into()));
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/wake", help: "Wake DMN to foraging",
|
||||||
|
handler: |s, _| {
|
||||||
|
let mut st = s.shared_mind.lock().unwrap();
|
||||||
|
if matches!(st.dmn, crate::mind::dmn::State::Off) { crate::mind::dmn::set_off(false); }
|
||||||
|
st.dmn = crate::mind::dmn::State::Foraging;
|
||||||
|
st.dmn_turns = 0;
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info("DMN foraging.".into()));
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/pause", help: "Full stop — no autonomous ticks (Ctrl+P)",
|
||||||
|
handler: |s, _| {
|
||||||
|
let mut st = s.shared_mind.lock().unwrap();
|
||||||
|
st.dmn = crate::mind::dmn::State::Paused;
|
||||||
|
st.dmn_turns = 0;
|
||||||
|
let _ = s.ui_tx.send(UiMessage::Info("DMN paused.".into()));
|
||||||
|
} },
|
||||||
|
SlashCommand { name: "/help", help: "Show this help",
|
||||||
|
handler: |s, _| { send_help(&s.ui_tx); } },
|
||||||
|
]}
|
||||||
|
|
||||||
|
fn dispatch_command(input: &str) -> Option<SlashCommand> {
|
||||||
|
let cmd_name = input.split_whitespace().next()?;
|
||||||
|
commands().into_iter().find(|c| c.name == cmd_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switch model — used by both /model command and tool-initiated switches.
|
||||||
|
pub async fn cmd_switch_model(
|
||||||
|
agent: &std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
|
||||||
|
name: &str,
|
||||||
|
ui_tx: &crate::user::ui_channel::UiSender,
|
||||||
|
) {
|
||||||
|
let resolved = {
|
||||||
|
let ag = agent.lock().await;
|
||||||
|
match ag.app_config.resolve_model(name) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(format!("{}", e)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let new_client = crate::agent::api::ApiClient::new(
|
||||||
|
&resolved.api_base, &resolved.api_key, &resolved.model_id,
|
||||||
|
);
|
||||||
|
let prompt_changed = {
|
||||||
|
let ag = agent.lock().await;
|
||||||
|
resolved.prompt_file != ag.prompt_file
|
||||||
|
};
|
||||||
|
let mut ag = agent.lock().await;
|
||||||
|
ag.swap_client(new_client);
|
||||||
|
if prompt_changed {
|
||||||
|
ag.prompt_file = resolved.prompt_file.clone();
|
||||||
|
ag.compact();
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(format!(
|
||||||
|
"Switched to {} ({}) — prompt: {}, recompacted",
|
||||||
|
name, resolved.model_id, resolved.prompt_file,
|
||||||
|
)));
|
||||||
|
} else {
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(format!(
|
||||||
|
"Switched to {} ({})", name, resolved.model_id,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn send_help(ui_tx: &crate::user::ui_channel::UiSender) {
|
||||||
|
for cmd in &commands() {
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(format!(" {:12} {}", cmd.name, cmd.help)));
|
||||||
|
}
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(String::new()));
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(
|
||||||
|
"Keys: Tab=pane ^Up/Down=scroll PgUp/PgDn=scroll Mouse=click/scroll".into(),
|
||||||
|
));
|
||||||
|
let _ = ui_tx.send(UiMessage::Info(
|
||||||
|
" Alt+Enter=newline Esc=interrupt ^P=pause ^R=reasoning ^K=kill".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
/// Turn marker for the conversation pane gutter.
|
/// Turn marker for the conversation pane gutter.
|
||||||
#[derive(Clone, Copy, PartialEq, Default)]
|
#[derive(Clone, Copy, PartialEq, Default)]
|
||||||
|
|
@ -245,12 +405,21 @@ pub(crate) struct InteractScreen {
|
||||||
// State sync with agent — double buffer
|
// State sync with agent — double buffer
|
||||||
last_generation: u64,
|
last_generation: u64,
|
||||||
last_entries: Vec<crate::agent::context::ConversationEntry>,
|
last_entries: Vec<crate::agent::context::ConversationEntry>,
|
||||||
|
pending_display_count: usize,
|
||||||
/// Reference to agent for state sync
|
/// Reference to agent for state sync
|
||||||
agent: std::sync::Arc<std::sync::Mutex<crate::agent::Agent>>,
|
agent: std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
|
||||||
|
shared_mind: std::sync::Arc<crate::mind::SharedMindState>,
|
||||||
|
mind_tx: tokio::sync::mpsc::UnboundedSender<crate::mind::MindCommand>,
|
||||||
|
ui_tx: crate::user::ui_channel::UiSender,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InteractScreen {
|
impl InteractScreen {
|
||||||
pub fn new(agent: std::sync::Arc<std::sync::Mutex<crate::agent::Agent>>) -> Self {
|
pub fn new(
|
||||||
|
agent: std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
|
||||||
|
shared_mind: std::sync::Arc<crate::mind::SharedMindState>,
|
||||||
|
mind_tx: tokio::sync::mpsc::UnboundedSender<crate::mind::MindCommand>,
|
||||||
|
ui_tx: crate::user::ui_channel::UiSender,
|
||||||
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
autonomous: PaneState::new(true),
|
autonomous: PaneState::new(true),
|
||||||
conversation: PaneState::new(true),
|
conversation: PaneState::new(true),
|
||||||
|
|
@ -266,7 +435,11 @@ impl InteractScreen {
|
||||||
call_timeout_secs: 60,
|
call_timeout_secs: 60,
|
||||||
last_generation: 0,
|
last_generation: 0,
|
||||||
last_entries: Vec::new(),
|
last_entries: Vec::new(),
|
||||||
|
pending_display_count: 0,
|
||||||
agent,
|
agent,
|
||||||
|
shared_mind,
|
||||||
|
mind_tx,
|
||||||
|
ui_tx,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -317,9 +490,16 @@ impl InteractScreen {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sync conversation display from agent entries.
|
/// Sync conversation display from agent entries + pending input.
|
||||||
fn sync_from_agent(&mut self) {
|
fn sync_from_agent(&mut self) {
|
||||||
let agent = self.agent.lock().unwrap();
|
// Pop previously-displayed pending input
|
||||||
|
for _ in 0..self.pending_display_count {
|
||||||
|
self.conversation.pop_line();
|
||||||
|
}
|
||||||
|
self.pending_display_count = 0;
|
||||||
|
|
||||||
|
// Sync agent entries
|
||||||
|
if let Ok(agent) = self.agent.try_lock() {
|
||||||
let generation = agent.generation;
|
let generation = agent.generation;
|
||||||
let entries = agent.entries();
|
let entries = agent.entries();
|
||||||
|
|
||||||
|
|
@ -372,6 +552,39 @@ impl InteractScreen {
|
||||||
self.last_generation = generation;
|
self.last_generation = generation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Display pending input (queued in Mind, not yet accepted)
|
||||||
|
let mind = self.shared_mind.lock().unwrap();
|
||||||
|
for input in &mind.input {
|
||||||
|
self.conversation.push_line_with_marker(
|
||||||
|
input.clone(), Color::DarkGray, Marker::User,
|
||||||
|
);
|
||||||
|
self.pending_display_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dispatch user input — slash commands or conversation.
|
||||||
|
fn dispatch_input(&self, input: &str, app: &mut App) {
|
||||||
|
let input = input.trim();
|
||||||
|
if input.is_empty() { return; }
|
||||||
|
|
||||||
|
if input == "/quit" || input == "/exit" {
|
||||||
|
app.should_quit = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.starts_with('/') {
|
||||||
|
if let Some(cmd) = dispatch_command(input) {
|
||||||
|
(cmd.handler)(self, &input[cmd.name.len()..].trim_start());
|
||||||
|
} else {
|
||||||
|
let _ = self.ui_tx.send(UiMessage::Info(format!("Unknown command: {}", input.split_whitespace().next().unwrap_or(input))));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regular input → queue to Mind
|
||||||
|
self.shared_mind.lock().unwrap().input.push(input.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
/// Process a UiMessage — update pane state.
|
/// Process a UiMessage — update pane state.
|
||||||
pub fn handle_ui_message(&mut self, msg: &UiMessage, app: &mut App) {
|
pub fn handle_ui_message(&mut self, msg: &UiMessage, app: &mut App) {
|
||||||
match msg {
|
match msg {
|
||||||
|
|
@ -680,7 +893,8 @@ impl ScreenView for InteractScreen {
|
||||||
self.input_history.push(input.clone());
|
self.input_history.push(input.clone());
|
||||||
}
|
}
|
||||||
self.history_index = None;
|
self.history_index = None;
|
||||||
// TODO: push to submitted via app or return action
|
self.dispatch_input(&input, app);
|
||||||
|
self.textarea = new_textarea(vec![String::new()]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => self.scroll_active_up(3),
|
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => self.scroll_active_up(3),
|
||||||
|
|
@ -727,6 +941,7 @@ impl ScreenView for InteractScreen {
|
||||||
self.draw_main(frame, area, app);
|
self.draw_main(frame, area, app);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Draw the conversation pane with a two-column layout: marker gutter + text.
|
/// Draw the conversation pane with a two-column layout: marker gutter + text.
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ use ratatui::crossterm::event::{Event, EventStream, KeyEventKind};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::agent::Agent;
|
use crate::agent::Agent;
|
||||||
use crate::agent::api::ApiClient;
|
use crate::agent::api::ApiClient;
|
||||||
|
|
@ -19,89 +19,6 @@ use crate::user::ui_channel::{self, UiMessage};
|
||||||
|
|
||||||
// ── Slash commands ─────────────────────────────────────────────
|
// ── Slash commands ─────────────────────────────────────────────
|
||||||
|
|
||||||
type CmdHandler = for<'a> fn(
|
|
||||||
&'a crate::mind::Mind,
|
|
||||||
&'a tokio::sync::mpsc::UnboundedSender<MindCommand>,
|
|
||||||
&'a ui_channel::UiSender,
|
|
||||||
&'a str,
|
|
||||||
);
|
|
||||||
|
|
||||||
struct SlashCommand {
|
|
||||||
name: &'static str,
|
|
||||||
help: &'static str,
|
|
||||||
handler: CmdHandler,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn commands() -> Vec<SlashCommand> { vec![
|
|
||||||
SlashCommand { name: "/quit", help: "Exit consciousness",
|
|
||||||
handler: |_, _, _, _| {} },
|
|
||||||
SlashCommand { name: "/new", help: "Start fresh session (saves current)",
|
|
||||||
handler: |_, tx, _, _| { let _ = tx.send(MindCommand::NewSession); } },
|
|
||||||
SlashCommand { name: "/save", help: "Save session to disk",
|
|
||||||
handler: |_, _, ui, _| { let _ = ui.send(UiMessage::Info("Conversation is saved automatically.".into())); } },
|
|
||||||
SlashCommand { name: "/retry", help: "Re-run last turn",
|
|
||||||
handler: |m, tx, ui, _| {
|
|
||||||
let agent = m.agent.clone();
|
|
||||||
let mind_tx = tx.clone();
|
|
||||||
let ui_tx = ui.clone();
|
|
||||||
let mut tw = m.turn_watch();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let _ = tw.wait_for(|&active| !active).await;
|
|
||||||
cmd_retry_inner(&agent, &mind_tx, &ui_tx).await;
|
|
||||||
});
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/model", help: "Show/switch model (/model <name>)",
|
|
||||||
handler: |m, _, ui, arg| {
|
|
||||||
if arg.is_empty() {
|
|
||||||
if let Ok(ag) = m.agent.try_lock() {
|
|
||||||
let _ = ui.send(UiMessage::Info(format!("Current model: {}", ag.model())));
|
|
||||||
let names = ag.app_config.model_names();
|
|
||||||
if !names.is_empty() {
|
|
||||||
let _ = ui.send(UiMessage::Info(format!("Available: {}", names.join(", "))));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let _ = ui.send(UiMessage::Info("(busy)".into()));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let agent = m.agent.clone();
|
|
||||||
let ui_tx = ui.clone();
|
|
||||||
let name = arg.to_string();
|
|
||||||
tokio::spawn(async move { cmd_switch_model(&agent, &name, &ui_tx).await; });
|
|
||||||
}
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/score", help: "Score memory importance",
|
|
||||||
handler: |_, tx, _, _| { let _ = tx.send(MindCommand::Score); } },
|
|
||||||
SlashCommand { name: "/dmn", help: "Show DMN state",
|
|
||||||
handler: |m, _, ui, _| {
|
|
||||||
let s = m.shared.lock().unwrap();
|
|
||||||
let _ = ui.send(UiMessage::Info(format!("DMN: {:?} ({}/{})", s.dmn, s.dmn_turns, s.max_dmn_turns)));
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/sleep", help: "Put DMN to sleep",
|
|
||||||
handler: |m, _, ui, _| {
|
|
||||||
let mut s = m.shared.lock().unwrap();
|
|
||||||
s.dmn = crate::mind::dmn::State::Resting { since: std::time::Instant::now() };
|
|
||||||
s.dmn_turns = 0;
|
|
||||||
let _ = ui.send(UiMessage::Info("DMN sleeping.".into()));
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/wake", help: "Wake DMN to foraging",
|
|
||||||
handler: |m, _, ui, _| {
|
|
||||||
let mut s = m.shared.lock().unwrap();
|
|
||||||
if matches!(s.dmn, crate::mind::dmn::State::Off) { crate::mind::dmn::set_off(false); }
|
|
||||||
s.dmn = crate::mind::dmn::State::Foraging;
|
|
||||||
s.dmn_turns = 0;
|
|
||||||
let _ = ui.send(UiMessage::Info("DMN foraging.".into()));
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/pause", help: "Full stop — no autonomous ticks (Ctrl+P)",
|
|
||||||
handler: |m, _, ui, _| {
|
|
||||||
let mut s = m.shared.lock().unwrap();
|
|
||||||
s.dmn = crate::mind::dmn::State::Paused;
|
|
||||||
s.dmn_turns = 0;
|
|
||||||
let _ = ui.send(UiMessage::Info("DMN paused.".into()));
|
|
||||||
} },
|
|
||||||
SlashCommand { name: "/help", help: "Show this help",
|
|
||||||
handler: |_, _, ui, _| { send_help(ui); } },
|
|
||||||
]}
|
|
||||||
|
|
||||||
/// Top-level entry point — creates Mind and UI, wires them together.
|
/// Top-level entry point — creates Mind and UI, wires them together.
|
||||||
pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
||||||
let (config, _figment) = crate::config::load_session(&cli)?;
|
let (config, _figment) = crate::config::load_session(&cli)?;
|
||||||
|
|
@ -116,8 +33,8 @@ pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
||||||
|
|
||||||
let mind = crate::mind::Mind::new(config, ui_tx.clone(), turn_tx);
|
let mind = crate::mind::Mind::new(config, ui_tx.clone(), turn_tx);
|
||||||
|
|
||||||
let shared_context = mind.agent.lock().unwrap().shared_context.clone();
|
let shared_context = mind.agent.lock().await.shared_context.clone();
|
||||||
let shared_active_tools = mind.agent.lock().unwrap().active_tools.clone();
|
let shared_active_tools = mind.agent.lock().await.active_tools.clone();
|
||||||
|
|
||||||
let mut result = Ok(());
|
let mut result = Ok(());
|
||||||
tokio_scoped::scope(|s| {
|
tokio_scoped::scope(|s| {
|
||||||
|
|
@ -138,55 +55,7 @@ pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch_command(input: &str) -> Option<SlashCommand> {
|
|
||||||
let cmd_name = input.split_whitespace().next()?;
|
|
||||||
commands().into_iter().find(|c| c.name == cmd_name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_help(ui_tx: &ui_channel::UiSender) {
|
|
||||||
for cmd in &commands() {
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(format!(" {:12} {}", cmd.name, cmd.help)));
|
|
||||||
}
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(String::new()));
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(
|
|
||||||
"Keys: Tab=pane ^Up/Down=scroll PgUp/PgDn=scroll Mouse=click/scroll".into(),
|
|
||||||
));
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(
|
|
||||||
" Alt+Enter=newline Esc=interrupt ^P=pause ^R=reasoning ^K=kill F10=context F2=agents".into(),
|
|
||||||
));
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(
|
|
||||||
" Shift+click for native text selection (copy/paste)".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn cmd_retry_inner(
|
|
||||||
agent: &Arc<Mutex<Agent>>,
|
|
||||||
mind_tx: &tokio::sync::mpsc::UnboundedSender<MindCommand>,
|
|
||||||
ui_tx: &ui_channel::UiSender,
|
|
||||||
) {
|
|
||||||
let mut agent_guard = agent.lock().unwrap();
|
|
||||||
let entries = agent_guard.entries_mut();
|
|
||||||
let mut last_user_text = None;
|
|
||||||
while let Some(entry) = entries.last() {
|
|
||||||
if entry.message().role == crate::agent::api::types::Role::User {
|
|
||||||
last_user_text = Some(entries.pop().unwrap().message().content_text().to_string());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
entries.pop();
|
|
||||||
}
|
|
||||||
drop(agent_guard);
|
|
||||||
match last_user_text {
|
|
||||||
Some(text) => {
|
|
||||||
let preview_len = text.len().min(60);
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(format!("(retrying: {}...)", &text[..preview_len])));
|
|
||||||
// Send as a Turn command — Mind will process it
|
|
||||||
let _ = mind_tx.send(MindCommand::Turn(text, crate::user::ui_channel::StreamTarget::Conversation));
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
let _ = ui_tx.send(UiMessage::Info("(nothing to retry)".into()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
||||||
if let Ok(mut ag) = mind.agent.try_lock() {
|
if let Ok(mut ag) = mind.agent.try_lock() {
|
||||||
|
|
@ -211,7 +80,7 @@ fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn hotkey_kill_processes(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
async fn hotkey_kill_processes(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
||||||
let active_tools = mind.agent.lock().unwrap().active_tools.clone();
|
let active_tools = mind.agent.lock().await.active_tools.clone();
|
||||||
let mut tools = active_tools.lock().unwrap();
|
let mut tools = active_tools.lock().unwrap();
|
||||||
if tools.is_empty() {
|
if tools.is_empty() {
|
||||||
let _ = ui_tx.send(UiMessage::Info("(no running tool calls)".into()));
|
let _ = ui_tx.send(UiMessage::Info("(no running tool calls)".into()));
|
||||||
|
|
@ -278,44 +147,6 @@ pub fn send_context_info(config: &crate::config::SessionConfig, ui_tx: &ui_chann
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn cmd_switch_model(
|
|
||||||
agent: &Arc<Mutex<Agent>>,
|
|
||||||
name: &str,
|
|
||||||
ui_tx: &ui_channel::UiSender,
|
|
||||||
) {
|
|
||||||
let resolved = {
|
|
||||||
let ag = agent.lock().unwrap();
|
|
||||||
match ag.app_config.resolve_model(name) {
|
|
||||||
Ok(r) => r,
|
|
||||||
Err(e) => {
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(format!("{}", e)));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let new_client = ApiClient::new(&resolved.api_base, &resolved.api_key, &resolved.model_id);
|
|
||||||
let prompt_changed = {
|
|
||||||
let ag = agent.lock().unwrap();
|
|
||||||
resolved.prompt_file != ag.prompt_file
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut ag = agent.lock().unwrap();
|
|
||||||
ag.swap_client(new_client);
|
|
||||||
|
|
||||||
if prompt_changed {
|
|
||||||
ag.prompt_file = resolved.prompt_file.clone();
|
|
||||||
ag.compact();
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(format!(
|
|
||||||
"Switched to {} ({}) — prompt: {}, recompacted",
|
|
||||||
name, resolved.model_id, resolved.prompt_file,
|
|
||||||
)));
|
|
||||||
} else {
|
|
||||||
let _ = ui_tx.send(UiMessage::Info(format!(
|
|
||||||
"Switched to {} ({})", name, resolved.model_id,
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn diff_mind_state(
|
fn diff_mind_state(
|
||||||
cur: &crate::mind::MindState,
|
cur: &crate::mind::MindState,
|
||||||
|
|
@ -336,8 +167,6 @@ fn diff_mind_state(
|
||||||
}
|
}
|
||||||
// Input consumed — Mind started a turn with it
|
// Input consumed — Mind started a turn with it
|
||||||
if !prev.input.is_empty() && cur.input.is_empty() {
|
if !prev.input.is_empty() && cur.input.is_empty() {
|
||||||
let text = prev.input.join("\n");
|
|
||||||
let _ = ui_tx.send(UiMessage::UserInput(text));
|
|
||||||
*dirty = true;
|
*dirty = true;
|
||||||
}
|
}
|
||||||
if cur.turn_active != prev.turn_active {
|
if cur.turn_active != prev.turn_active {
|
||||||
|
|
@ -382,7 +211,9 @@ pub async fn run(
|
||||||
let notify_rx = crate::thalamus::channels::subscribe_all();
|
let notify_rx = crate::thalamus::channels::subscribe_all();
|
||||||
|
|
||||||
// InteractScreen held separately for UiMessage routing
|
// InteractScreen held separately for UiMessage routing
|
||||||
let mut interact = crate::user::chat::InteractScreen::new(mind.agent.clone());
|
let mut interact = crate::user::chat::InteractScreen::new(
|
||||||
|
mind.agent.clone(), mind.shared.clone(), mind_tx.clone(), ui_tx.clone(),
|
||||||
|
);
|
||||||
// Overlay screens: F2=conscious, F3=subconscious, F4=unconscious, F5=thalamus
|
// Overlay screens: F2=conscious, F3=subconscious, F4=unconscious, F5=thalamus
|
||||||
let mut screens: Vec<Box<dyn tui::ScreenView>> = vec![
|
let mut screens: Vec<Box<dyn tui::ScreenView>> = vec![
|
||||||
Box::new(crate::user::context::ConsciousScreen::new()),
|
Box::new(crate::user::context::ConsciousScreen::new()),
|
||||||
|
|
@ -443,11 +274,10 @@ pub async fn run(
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Global keys (Ctrl combos)
|
// Global keys (Ctrl combos) — only pass to screen if not consumed
|
||||||
app.handle_global_key(key);
|
if !app.handle_global_key(key) {
|
||||||
|
|
||||||
// Store pending key for active overlay screen
|
|
||||||
pending_key = Some(key);
|
pending_key = Some(key);
|
||||||
|
}
|
||||||
dirty = true;
|
dirty = true;
|
||||||
}
|
}
|
||||||
Some(Ok(Event::Mouse(_mouse))) => {
|
Some(Ok(Event::Mouse(_mouse))) => {
|
||||||
|
|
@ -509,23 +339,6 @@ pub async fn run(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process submitted input
|
|
||||||
let submitted: Vec<String> = app.submitted.drain(..).collect();
|
|
||||||
for input in submitted {
|
|
||||||
let input = input.trim().to_string();
|
|
||||||
if input.is_empty() { continue; }
|
|
||||||
if input == "/quit" || input == "/exit" {
|
|
||||||
app.should_quit = true;
|
|
||||||
} else if let Some(cmd) = dispatch_command(&input) {
|
|
||||||
(cmd.handler)(mind, &mind_tx, &ui_tx, &input[cmd.name.len()..].trim_start());
|
|
||||||
} else {
|
|
||||||
let mut s = shared_mind.lock().unwrap();
|
|
||||||
diff_mind_state(&s, &prev_mind, &ui_tx, &mut dirty);
|
|
||||||
s.input.push(input);
|
|
||||||
prev_mind = s.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle hotkey actions
|
// Handle hotkey actions
|
||||||
let actions: Vec<HotkeyAction> = app.hotkey_actions.drain(..).collect();
|
let actions: Vec<HotkeyAction> = app.hotkey_actions.drain(..).collect();
|
||||||
for action in actions {
|
for action in actions {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue