2026-04-03 23:21:16 -04:00
|
|
|
// agent.rs — Core agent loop
|
2026-03-27 15:22:48 -04:00
|
|
|
//
|
2026-04-03 23:21:16 -04:00
|
|
|
// The simplest possible implementation of the agent pattern:
|
|
|
|
|
// send messages + tool definitions to the model, if it responds
|
|
|
|
|
// with tool calls then dispatch them and loop, if it responds
|
|
|
|
|
// with text then display it and wait for the next prompt.
|
|
|
|
|
//
|
|
|
|
|
// Uses streaming by default so text tokens appear as they're
|
|
|
|
|
// generated. Tool calls are accumulated from stream deltas and
|
|
|
|
|
// dispatched after the stream completes.
|
|
|
|
|
//
|
|
|
|
|
// The DMN (dmn.rs) is the outer loop that decides what prompts
|
|
|
|
|
// to send here. This module just handles single turns: prompt
|
|
|
|
|
// in, response out, tool calls dispatched.
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-04 00:29:11 -04:00
|
|
|
pub mod api;
|
2026-03-27 15:22:48 -04:00
|
|
|
pub mod context;
|
2026-04-04 17:25:10 -04:00
|
|
|
pub mod oneshot;
|
2026-04-08 11:20:03 -04:00
|
|
|
pub mod tokenizer;
|
2026-04-03 21:59:14 -04:00
|
|
|
pub mod tools;
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-04 04:23:29 -04:00
|
|
|
use std::sync::Arc;
|
2026-04-03 23:21:16 -04:00
|
|
|
use anyhow::Result;
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
use api::ApiClient;
|
WIP: Rename context_new → context, delete old files, fix UI layer
Renamed context_new.rs to context.rs, deleted context_old.rs,
types.rs, openai.rs, parsing.rs. Updated all imports. Rewrote
user/context.rs and user/widgets.rs for new types. Stubbed
working_stack tool. Killed tokenize_conv_entry.
Remaining: mind/mod.rs, mind/dmn.rs, learn.rs, chat.rs,
subconscious.rs, oneshot.rs.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:20:26 -04:00
|
|
|
use context::{AstNode, NodeBody, ContextState, Section, Ast, PendingToolCall, ResponseParser, Role};
|
2026-04-04 00:29:11 -04:00
|
|
|
|
2026-04-05 01:48:11 -04:00
|
|
|
use crate::mind::log::ConversationLog;
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-05 22:18:07 -04:00
|
|
|
// --- Activity tracking (RAII guards) ---
|
|
|
|
|
|
|
|
|
|
pub struct ActivityEntry {
|
|
|
|
|
pub id: u64,
|
|
|
|
|
pub label: String,
|
|
|
|
|
pub started: std::time::Instant,
|
|
|
|
|
/// Auto-expires this long after creation (or completion).
|
|
|
|
|
pub expires_at: std::time::Instant,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub struct ActivityGuard {
|
2026-04-08 15:36:08 -04:00
|
|
|
agent: Arc<Agent>,
|
2026-04-05 22:18:07 -04:00
|
|
|
id: u64,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const ACTIVITY_LINGER: std::time::Duration = std::time::Duration::from_secs(5);
|
|
|
|
|
|
|
|
|
|
impl Drop for ActivityGuard {
|
|
|
|
|
fn drop(&mut self) {
|
2026-04-08 15:36:08 -04:00
|
|
|
if let Ok(mut st) = self.agent.state.try_lock() {
|
|
|
|
|
if let Some(entry) = st.activities.iter_mut().find(|a| a.id == self.id) {
|
2026-04-05 22:18:07 -04:00
|
|
|
entry.label.push_str(" (complete)");
|
|
|
|
|
entry.expires_at = std::time::Instant::now() + ACTIVITY_LINGER;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
impl AgentState {
|
2026-04-05 22:18:07 -04:00
|
|
|
pub fn push_activity(&mut self, label: impl Into<String>) -> u64 {
|
|
|
|
|
self.expire_activities();
|
|
|
|
|
let id = self.next_activity_id;
|
|
|
|
|
self.next_activity_id += 1;
|
|
|
|
|
self.activities.push(ActivityEntry {
|
|
|
|
|
id, label: label.into(),
|
|
|
|
|
started: std::time::Instant::now(),
|
|
|
|
|
expires_at: std::time::Instant::now() + std::time::Duration::from_secs(3600),
|
|
|
|
|
});
|
2026-04-05 23:04:10 -04:00
|
|
|
self.changed.notify_one();
|
2026-04-05 22:18:07 -04:00
|
|
|
id
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn notify(&mut self, label: impl Into<String>) {
|
|
|
|
|
self.expire_activities();
|
|
|
|
|
let id = self.next_activity_id;
|
|
|
|
|
self.next_activity_id += 1;
|
|
|
|
|
self.activities.push(ActivityEntry {
|
|
|
|
|
id, label: label.into(),
|
|
|
|
|
started: std::time::Instant::now(),
|
|
|
|
|
expires_at: std::time::Instant::now() + ACTIVITY_LINGER,
|
|
|
|
|
});
|
2026-04-05 23:04:10 -04:00
|
|
|
self.changed.notify_one();
|
2026-04-05 22:18:07 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn expire_activities(&mut self) {
|
|
|
|
|
let now = std::time::Instant::now();
|
|
|
|
|
self.activities.retain(|a| a.expires_at > now);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
pub async fn start_activity(agent: &Arc<Agent>, label: impl Into<String>) -> ActivityGuard {
|
|
|
|
|
let id = agent.state.lock().await.push_activity(label);
|
2026-04-05 22:18:07 -04:00
|
|
|
ActivityGuard { agent: agent.clone(), id }
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-03 23:21:16 -04:00
|
|
|
/// Result of a single agent turn.
|
|
|
|
|
pub struct TurnResult {
|
|
|
|
|
/// The text response (already sent through UI channel).
|
|
|
|
|
#[allow(dead_code)]
|
2026-03-27 15:22:48 -04:00
|
|
|
pub text: String,
|
2026-04-03 23:21:16 -04:00
|
|
|
/// Whether the model called yield_to_user during this turn.
|
|
|
|
|
pub yield_requested: bool,
|
|
|
|
|
/// Whether any tools (other than yield_to_user) were called.
|
|
|
|
|
pub had_tool_calls: bool,
|
|
|
|
|
/// Number of tool calls that returned errors this turn.
|
|
|
|
|
pub tool_errors: u32,
|
|
|
|
|
/// Model name to switch to after this turn completes.
|
2026-03-27 15:22:48 -04:00
|
|
|
pub model_switch: Option<String>,
|
2026-04-03 23:21:16 -04:00
|
|
|
/// Agent requested DMN pause (full stop on autonomous behavior).
|
2026-03-27 15:22:48 -04:00
|
|
|
pub dmn_pause: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-03 23:21:16 -04:00
|
|
|
/// Accumulated state across tool dispatches within a single turn.
|
|
|
|
|
struct DispatchState {
|
|
|
|
|
yield_requested: bool,
|
|
|
|
|
had_tool_calls: bool,
|
|
|
|
|
tool_errors: u32,
|
|
|
|
|
model_switch: Option<String>,
|
|
|
|
|
dmn_pause: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-04 04:23:29 -04:00
|
|
|
impl DispatchState {
|
|
|
|
|
fn new() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
yield_requested: false, had_tool_calls: false,
|
|
|
|
|
tool_errors: 0, model_switch: None, dmn_pause: false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
/// Immutable agent config — shared via Arc, no mutex needed.
|
2026-04-03 23:21:16 -04:00
|
|
|
pub struct Agent {
|
2026-04-08 15:36:08 -04:00
|
|
|
pub client: ApiClient,
|
|
|
|
|
pub app_config: crate::config::AppConfig,
|
|
|
|
|
pub prompt_file: String,
|
|
|
|
|
pub session_id: String,
|
|
|
|
|
pub context: tokio::sync::Mutex<ContextState>,
|
|
|
|
|
pub state: tokio::sync::Mutex<AgentState>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Mutable agent state — behind its own mutex.
|
2026-04-09 11:45:39 -04:00
|
|
|
/// Which external MCP tools an agent can access.
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
pub enum McpToolAccess {
|
|
|
|
|
None,
|
|
|
|
|
All,
|
|
|
|
|
Some(Vec<String>),
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
pub struct AgentState {
|
|
|
|
|
pub tools: Vec<tools::Tool>,
|
2026-04-09 11:45:39 -04:00
|
|
|
pub mcp_tools: McpToolAccess,
|
2026-04-08 15:36:08 -04:00
|
|
|
pub last_prompt_tokens: u32,
|
2026-04-03 23:21:16 -04:00
|
|
|
pub reasoning_effort: String,
|
2026-04-04 13:48:24 -04:00
|
|
|
pub temperature: f32,
|
|
|
|
|
pub top_p: f32,
|
|
|
|
|
pub top_k: u32,
|
2026-04-05 22:18:07 -04:00
|
|
|
pub activities: Vec<ActivityEntry>,
|
|
|
|
|
next_activity_id: u64,
|
2026-04-04 16:05:33 -04:00
|
|
|
pub pending_yield: bool,
|
|
|
|
|
pub pending_model_switch: Option<String>,
|
|
|
|
|
pub pending_dmn_pause: bool,
|
2026-04-07 17:46:40 -04:00
|
|
|
pub provenance: String,
|
2026-04-05 19:17:13 -04:00
|
|
|
pub generation: u64,
|
2026-04-06 21:48:12 -04:00
|
|
|
pub memory_scoring_in_flight: bool,
|
2026-04-08 16:41:14 -04:00
|
|
|
pub active_tools: tools::ActiveTools,
|
2026-04-08 23:00:12 -04:00
|
|
|
/// Forked agents should not compact on overflow — it blows the
|
|
|
|
|
/// KV cache prefix and evicts the step prompts.
|
|
|
|
|
pub no_compact: bool,
|
2026-04-05 23:04:10 -04:00
|
|
|
pub changed: Arc<tokio::sync::Notify>,
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Agent {
|
2026-04-08 15:36:08 -04:00
|
|
|
pub async fn new(
|
2026-04-03 23:21:16 -04:00
|
|
|
client: ApiClient,
|
|
|
|
|
system_prompt: String,
|
|
|
|
|
personality: Vec<(String, String)>,
|
|
|
|
|
app_config: crate::config::AppConfig,
|
|
|
|
|
prompt_file: String,
|
|
|
|
|
conversation_log: Option<ConversationLog>,
|
2026-04-08 16:41:14 -04:00
|
|
|
active_tools: tools::ActiveTools,
|
2026-04-08 15:36:08 -04:00
|
|
|
) -> Arc<Self> {
|
2026-04-08 14:55:10 -04:00
|
|
|
let mut context = ContextState::new();
|
2026-04-09 00:32:32 -04:00
|
|
|
context.conversation_log = conversation_log;
|
2026-04-09 01:10:40 -04:00
|
|
|
context.push_no_log(Section::System, AstNode::system_msg(&system_prompt));
|
2026-04-08 11:36:33 -04:00
|
|
|
|
2026-04-09 11:45:39 -04:00
|
|
|
let tool_defs = tools::all_tool_definitions().await;
|
2026-04-08 11:36:33 -04:00
|
|
|
if !tool_defs.is_empty() {
|
|
|
|
|
let tools_text = format!(
|
|
|
|
|
"# Tools\n\nYou have access to the following functions:\n\n<tools>\n{}\n</tools>\n\n\
|
|
|
|
|
If you choose to call a function ONLY reply in the following format with NO suffix:\n\n\
|
|
|
|
|
<tool_call>\n<function=example_function_name>\n\
|
|
|
|
|
<parameter=example_parameter_1>\nvalue_1\n</parameter>\n\
|
|
|
|
|
</function>\n</tool_call>\n\n\
|
|
|
|
|
IMPORTANT: Function calls MUST follow the specified format.",
|
|
|
|
|
tool_defs.join("\n"),
|
|
|
|
|
);
|
2026-04-09 01:10:40 -04:00
|
|
|
context.push_no_log(Section::System, AstNode::system_msg(&tools_text));
|
2026-04-08 11:36:33 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
for (name, content) in &personality {
|
2026-04-09 01:10:40 -04:00
|
|
|
context.push_no_log(Section::Identity, AstNode::memory(name, content));
|
2026-04-07 20:15:31 -04:00
|
|
|
}
|
2026-04-08 15:36:08 -04:00
|
|
|
|
2026-04-03 23:21:16 -04:00
|
|
|
let session_id = format!("consciousness-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S"));
|
2026-04-08 15:36:08 -04:00
|
|
|
let agent = Arc::new(Self {
|
2026-04-03 23:21:16 -04:00
|
|
|
client,
|
|
|
|
|
app_config,
|
|
|
|
|
prompt_file,
|
|
|
|
|
session_id,
|
2026-04-08 15:36:08 -04:00
|
|
|
context: tokio::sync::Mutex::new(context),
|
|
|
|
|
state: tokio::sync::Mutex::new(AgentState {
|
|
|
|
|
tools: tools::tools(),
|
2026-04-09 11:45:39 -04:00
|
|
|
mcp_tools: McpToolAccess::All,
|
2026-04-08 15:36:08 -04:00
|
|
|
last_prompt_tokens: 0,
|
|
|
|
|
reasoning_effort: "none".to_string(),
|
|
|
|
|
temperature: 0.6,
|
|
|
|
|
top_p: 0.95,
|
|
|
|
|
top_k: 20,
|
|
|
|
|
activities: Vec::new(),
|
|
|
|
|
next_activity_id: 0,
|
|
|
|
|
pending_yield: false,
|
|
|
|
|
pending_model_switch: None,
|
|
|
|
|
pending_dmn_pause: false,
|
|
|
|
|
provenance: "manual".to_string(),
|
|
|
|
|
generation: 0,
|
|
|
|
|
memory_scoring_in_flight: false,
|
|
|
|
|
active_tools,
|
2026-04-08 23:00:12 -04:00
|
|
|
no_compact: false,
|
2026-04-08 15:36:08 -04:00
|
|
|
changed: Arc::new(tokio::sync::Notify::new()),
|
|
|
|
|
}),
|
|
|
|
|
});
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
agent.load_startup_journal().await;
|
2026-04-03 23:21:16 -04:00
|
|
|
agent
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
/// Fork: clones context for KV cache prefix sharing.
|
|
|
|
|
pub async fn fork(self: &Arc<Self>, tools: Vec<tools::Tool>) -> Arc<Self> {
|
|
|
|
|
let ctx = self.context.lock().await.clone();
|
|
|
|
|
let st = self.state.lock().await;
|
|
|
|
|
Arc::new(Self {
|
2026-04-07 01:07:04 -04:00
|
|
|
client: self.client.clone(),
|
|
|
|
|
app_config: self.app_config.clone(),
|
|
|
|
|
prompt_file: self.prompt_file.clone(),
|
|
|
|
|
session_id: self.session_id.clone(),
|
2026-04-08 15:36:08 -04:00
|
|
|
context: tokio::sync::Mutex::new(ctx),
|
|
|
|
|
state: tokio::sync::Mutex::new(AgentState {
|
|
|
|
|
tools,
|
2026-04-09 11:45:39 -04:00
|
|
|
mcp_tools: McpToolAccess::None,
|
2026-04-08 15:36:08 -04:00
|
|
|
last_prompt_tokens: 0,
|
|
|
|
|
reasoning_effort: "none".to_string(),
|
|
|
|
|
temperature: st.temperature,
|
|
|
|
|
top_p: st.top_p,
|
|
|
|
|
top_k: st.top_k,
|
|
|
|
|
activities: Vec::new(),
|
|
|
|
|
next_activity_id: 0,
|
|
|
|
|
pending_yield: false,
|
|
|
|
|
pending_model_switch: None,
|
|
|
|
|
pending_dmn_pause: false,
|
|
|
|
|
provenance: st.provenance.clone(),
|
|
|
|
|
generation: 0,
|
|
|
|
|
memory_scoring_in_flight: false,
|
2026-04-08 16:41:14 -04:00
|
|
|
active_tools: tools::ActiveTools::new(),
|
2026-04-08 23:00:12 -04:00
|
|
|
no_compact: true,
|
2026-04-08 15:36:08 -04:00
|
|
|
changed: Arc::new(tokio::sync::Notify::new()),
|
|
|
|
|
}),
|
|
|
|
|
})
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
pub async fn assemble_prompt_tokens(&self) -> Vec<u32> {
|
|
|
|
|
let ctx = self.context.lock().await;
|
|
|
|
|
let mut tokens = ctx.token_ids();
|
2026-04-08 11:36:33 -04:00
|
|
|
tokens.push(tokenizer::IM_START);
|
|
|
|
|
tokens.extend(tokenizer::encode("assistant\n"));
|
|
|
|
|
tokens
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 15:36:08 -04:00
|
|
|
pub async fn push_node(&self, node: AstNode) {
|
2026-04-08 17:18:48 -04:00
|
|
|
let node = node.with_timestamp(chrono::Utc::now());
|
2026-04-09 01:10:40 -04:00
|
|
|
self.context.lock().await.push_log(Section::Conversation, node);
|
2026-04-09 00:32:32 -04:00
|
|
|
self.state.lock().await.changed.notify_one();
|
2026-04-06 22:20:22 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
/// Run the agent turn loop: assemble prompt, stream response,
|
|
|
|
|
/// parse into AST, dispatch tool calls, repeat until text response.
|
2026-04-03 23:21:16 -04:00
|
|
|
pub async fn turn(
|
2026-04-08 15:36:08 -04:00
|
|
|
agent: Arc<Agent>,
|
2026-04-03 23:21:16 -04:00
|
|
|
) -> Result<TurnResult> {
|
2026-04-08 14:55:10 -04:00
|
|
|
// Collect finished background tools
|
|
|
|
|
{
|
2026-04-08 16:41:14 -04:00
|
|
|
let finished = agent.state.lock().await.active_tools.take_finished();
|
2026-04-08 14:55:10 -04:00
|
|
|
if !finished.is_empty() {
|
2026-04-08 16:41:14 -04:00
|
|
|
let mut bg_ds = DispatchState::new();
|
2026-04-08 16:48:05 -04:00
|
|
|
let mut results = Vec::new();
|
2026-04-08 14:55:10 -04:00
|
|
|
for entry in finished {
|
|
|
|
|
if let Ok((call, output)) = entry.handle.await {
|
2026-04-08 16:48:05 -04:00
|
|
|
results.push((call, output));
|
2026-04-08 14:55:10 -04:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-08 16:48:05 -04:00
|
|
|
Agent::apply_tool_results(&agent, results, &mut bg_ds).await;
|
2026-04-05 21:13:48 -04:00
|
|
|
}
|
2026-04-08 14:55:10 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
|
|
|
|
let mut overflow_retries: u32 = 0;
|
|
|
|
|
let mut empty_retries: u32 = 0;
|
2026-04-04 04:23:29 -04:00
|
|
|
let mut ds = DispatchState::new();
|
2026-04-03 23:21:16 -04:00
|
|
|
|
|
|
|
|
loop {
|
2026-04-05 22:18:07 -04:00
|
|
|
let _thinking = start_activity(&agent, "thinking...").await;
|
2026-04-08 14:55:10 -04:00
|
|
|
|
2026-04-08 16:35:57 -04:00
|
|
|
let (rx, _stream_guard) = {
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let prompt_tokens = agent.assemble_prompt_tokens().await;
|
|
|
|
|
let st = agent.state.lock().await;
|
|
|
|
|
agent.client.stream_completion(
|
2026-04-08 14:55:10 -04:00
|
|
|
&prompt_tokens,
|
|
|
|
|
api::SamplingParams {
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
temperature: st.temperature,
|
|
|
|
|
top_p: st.top_p,
|
|
|
|
|
top_k: st.top_k,
|
2026-04-08 14:55:10 -04:00
|
|
|
},
|
|
|
|
|
None,
|
|
|
|
|
)
|
2026-04-04 04:23:29 -04:00
|
|
|
};
|
2026-04-07 22:49:35 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
let branch_idx = {
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let mut ctx = agent.context.lock().await;
|
|
|
|
|
let idx = ctx.len(Section::Conversation);
|
2026-04-09 01:10:40 -04:00
|
|
|
ctx.push_log(Section::Conversation,
|
2026-04-08 17:18:48 -04:00
|
|
|
AstNode::branch(Role::Assistant, vec![])
|
|
|
|
|
.with_timestamp(chrono::Utc::now()));
|
2026-04-08 14:55:10 -04:00
|
|
|
idx
|
|
|
|
|
};
|
2026-04-08 16:32:00 -04:00
|
|
|
|
|
|
|
|
let parser = ResponseParser::new(branch_idx);
|
|
|
|
|
let (mut tool_rx, parser_handle) = parser.run(rx, agent.clone());
|
|
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
let mut pending_calls: Vec<PendingToolCall> = Vec::new();
|
2026-04-08 16:32:00 -04:00
|
|
|
while let Some(call) = tool_rx.recv().await {
|
|
|
|
|
let call_clone = call.clone();
|
|
|
|
|
let agent_handle = agent.clone();
|
|
|
|
|
let handle = tokio::spawn(async move {
|
|
|
|
|
let args: serde_json::Value =
|
|
|
|
|
serde_json::from_str(&call_clone.arguments).unwrap_or_default();
|
|
|
|
|
let output = tools::dispatch_with_agent(
|
|
|
|
|
&call_clone.name, &args, Some(agent_handle),
|
|
|
|
|
).await;
|
|
|
|
|
(call_clone, output)
|
|
|
|
|
});
|
2026-04-08 16:41:14 -04:00
|
|
|
agent.state.lock().await.active_tools.push(tools::ActiveToolCall {
|
2026-04-08 16:32:00 -04:00
|
|
|
id: call.id.clone(),
|
|
|
|
|
name: call.name.clone(),
|
|
|
|
|
detail: call.arguments.clone(),
|
|
|
|
|
started: std::time::Instant::now(),
|
|
|
|
|
background: false,
|
|
|
|
|
handle,
|
|
|
|
|
});
|
|
|
|
|
pending_calls.push(call);
|
2026-04-08 14:55:10 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 16:32:00 -04:00
|
|
|
// Check for stream/parse errors
|
|
|
|
|
match parser_handle.await {
|
|
|
|
|
Ok(Err(e)) => {
|
2026-04-08 23:00:12 -04:00
|
|
|
if context::is_context_overflow(&e) {
|
|
|
|
|
if agent.state.lock().await.no_compact {
|
|
|
|
|
return Err(e);
|
|
|
|
|
}
|
|
|
|
|
if overflow_retries < 2 {
|
|
|
|
|
overflow_retries += 1;
|
|
|
|
|
agent.state.lock().await.notify(
|
|
|
|
|
format!("context overflow — retrying ({}/2)", overflow_retries));
|
|
|
|
|
agent.compact().await;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-04-08 16:32:00 -04:00
|
|
|
}
|
|
|
|
|
return Err(e);
|
2026-04-04 04:23:29 -04:00
|
|
|
}
|
2026-04-08 16:32:00 -04:00
|
|
|
Err(e) => return Err(anyhow::anyhow!("parser task panicked: {}", e)),
|
2026-04-08 16:58:05 -04:00
|
|
|
Ok(Ok(())) => {
|
2026-04-09 00:32:32 -04:00
|
|
|
// Assistant response was pushed to context by the parser;
|
|
|
|
|
// log it now that parsing is complete.
|
|
|
|
|
let ctx = agent.context.lock().await;
|
|
|
|
|
if let Some(ref log) = ctx.conversation_log {
|
|
|
|
|
let node = &ctx.conversation()[branch_idx];
|
|
|
|
|
if let Err(e) = log.append_node(node) {
|
|
|
|
|
eprintln!("warning: log: {:#}", e);
|
2026-04-08 16:58:05 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-08 14:55:10 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
// Empty response — nudge and retry
|
2026-04-08 16:32:00 -04:00
|
|
|
let has_content = {
|
|
|
|
|
let ctx = agent.context.lock().await;
|
|
|
|
|
!ctx.conversation()[branch_idx].children().is_empty()
|
|
|
|
|
};
|
|
|
|
|
if !has_content && pending_calls.is_empty() {
|
2026-04-08 14:55:10 -04:00
|
|
|
if empty_retries < 2 {
|
|
|
|
|
empty_retries += 1;
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
agent.push_node(AstNode::user_msg(
|
2026-04-08 14:55:10 -04:00
|
|
|
"[system] Your previous response was empty. \
|
|
|
|
|
Please respond with text or use a tool."
|
2026-04-08 15:47:21 -04:00
|
|
|
)).await;
|
2026-04-08 14:55:10 -04:00
|
|
|
continue;
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
2026-04-08 14:55:10 -04:00
|
|
|
} else {
|
|
|
|
|
empty_retries = 0;
|
|
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
// Wait for tool calls to complete
|
|
|
|
|
if !pending_calls.is_empty() {
|
|
|
|
|
ds.had_tool_calls = true;
|
|
|
|
|
|
2026-04-08 16:41:14 -04:00
|
|
|
let handles = agent.state.lock().await.active_tools.take_foreground();
|
2026-04-08 16:48:05 -04:00
|
|
|
let mut results = Vec::new();
|
2026-04-08 14:55:10 -04:00
|
|
|
for entry in handles {
|
|
|
|
|
if let Ok((call, output)) = entry.handle.await {
|
2026-04-08 16:48:05 -04:00
|
|
|
results.push((call, output));
|
2026-04-04 04:23:29 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
2026-04-08 16:48:05 -04:00
|
|
|
Agent::apply_tool_results(&agent, results, &mut ds).await;
|
2026-04-09 16:47:49 -04:00
|
|
|
if !agent.state.lock().await.pending_yield {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-04-05 21:13:48 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 14:55:10 -04:00
|
|
|
// Text-only response — extract text and return
|
|
|
|
|
let text = {
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let ctx = agent.context.lock().await;
|
|
|
|
|
let children = ctx.conversation()[branch_idx].children();
|
2026-04-08 14:55:10 -04:00
|
|
|
children.iter()
|
|
|
|
|
.filter_map(|c| c.leaf())
|
|
|
|
|
.filter(|l| matches!(l.body(), NodeBody::Content(_)))
|
|
|
|
|
.map(|l| l.body().text())
|
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
|
.join("")
|
|
|
|
|
};
|
2026-04-05 21:13:48 -04:00
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let mut st = agent.state.lock().await;
|
|
|
|
|
if st.pending_yield { ds.yield_requested = true; st.pending_yield = false; }
|
|
|
|
|
if st.pending_model_switch.is_some() { ds.model_switch = st.pending_model_switch.take(); }
|
|
|
|
|
if st.pending_dmn_pause { ds.dmn_pause = true; st.pending_dmn_pause = false; }
|
2026-04-05 21:13:48 -04:00
|
|
|
|
|
|
|
|
return Ok(TurnResult {
|
|
|
|
|
text,
|
|
|
|
|
yield_requested: ds.yield_requested,
|
|
|
|
|
had_tool_calls: ds.had_tool_calls,
|
|
|
|
|
tool_errors: ds.tool_errors,
|
|
|
|
|
model_switch: ds.model_switch,
|
|
|
|
|
dmn_pause: ds.dmn_pause,
|
|
|
|
|
});
|
2026-03-27 15:22:48 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-08 16:48:05 -04:00
|
|
|
fn make_tool_result_node(call: &PendingToolCall, output: &str) -> AstNode {
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
if call.name == "memory_render" && !output.starts_with("Error:") {
|
|
|
|
|
let args: serde_json::Value =
|
|
|
|
|
serde_json::from_str(&call.arguments).unwrap_or_default();
|
2026-04-03 23:21:16 -04:00
|
|
|
if let Some(key) = args.get("key").and_then(|v| v.as_str()) {
|
2026-04-08 16:48:05 -04:00
|
|
|
return AstNode::memory(key, output);
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
}
|
2026-04-08 16:48:05 -04:00
|
|
|
AstNode::tool_result(output)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn apply_tool_results(
|
|
|
|
|
agent: &Arc<Agent>,
|
|
|
|
|
results: Vec<(PendingToolCall, String)>,
|
|
|
|
|
ds: &mut DispatchState,
|
|
|
|
|
) {
|
|
|
|
|
let mut nodes = Vec::new();
|
|
|
|
|
for (call, output) in &results {
|
2026-04-09 18:08:07 -04:00
|
|
|
if call.name == "yield_to_user" { continue; }
|
2026-04-08 16:48:05 -04:00
|
|
|
ds.had_tool_calls = true;
|
|
|
|
|
if output.starts_with("Error:") { ds.tool_errors += 1; }
|
|
|
|
|
nodes.push(Self::make_tool_result_node(call, output));
|
|
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
|
2026-04-08 16:48:05 -04:00
|
|
|
{
|
|
|
|
|
let mut st = agent.state.lock().await;
|
|
|
|
|
for (call, _) in &results {
|
|
|
|
|
st.active_tools.remove(&call.id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
{
|
|
|
|
|
let mut ctx = agent.context.lock().await;
|
|
|
|
|
for node in nodes {
|
2026-04-09 01:10:40 -04:00
|
|
|
ctx.push_log(Section::Conversation, node);
|
2026-04-08 16:48:05 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
agent.state.lock().await.changed.notify_one();
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
async fn load_startup_journal(&self) {
|
|
|
|
|
let oldest_msg_ts = {
|
2026-04-09 00:32:32 -04:00
|
|
|
let ctx = self.context.lock().await;
|
|
|
|
|
ctx.conversation_log.as_ref().and_then(|log| log.oldest_timestamp())
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
};
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-03 23:21:16 -04:00
|
|
|
let store = match crate::store::Store::load() {
|
|
|
|
|
Ok(s) => s,
|
|
|
|
|
Err(_) => return,
|
|
|
|
|
};
|
2026-03-27 15:22:48 -04:00
|
|
|
|
2026-04-03 23:21:16 -04:00
|
|
|
let mut journal_nodes: Vec<_> = store.nodes.values()
|
|
|
|
|
.filter(|n| n.node_type == crate::store::NodeType::EpisodicSession)
|
|
|
|
|
.collect();
|
|
|
|
|
journal_nodes.sort_by_key(|n| n.created_at);
|
|
|
|
|
|
|
|
|
|
let cutoff_idx = if let Some(cutoff) = oldest_msg_ts {
|
|
|
|
|
let cutoff_ts = cutoff.timestamp();
|
|
|
|
|
let mut idx = journal_nodes.len();
|
|
|
|
|
for (i, node) in journal_nodes.iter().enumerate() {
|
|
|
|
|
if node.created_at >= cutoff_ts {
|
|
|
|
|
idx = i + 1;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
idx
|
|
|
|
|
} else {
|
|
|
|
|
journal_nodes.len()
|
|
|
|
|
};
|
|
|
|
|
|
WIP: Rename context_new → context, delete old files, fix UI layer
Renamed context_new.rs to context.rs, deleted context_old.rs,
types.rs, openai.rs, parsing.rs. Updated all imports. Rewrote
user/context.rs and user/widgets.rs for new types. Stubbed
working_stack tool. Killed tokenize_conv_entry.
Remaining: mind/mod.rs, mind/dmn.rs, learn.rs, chat.rs,
subconscious.rs, oneshot.rs.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:20:26 -04:00
|
|
|
let journal_budget = context::context_window() * 15 / 100;
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
let mut entries = Vec::new();
|
2026-04-03 23:21:16 -04:00
|
|
|
let mut total_tokens = 0;
|
|
|
|
|
|
|
|
|
|
for node in journal_nodes[..cutoff_idx].iter().rev() {
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
let ts = chrono::DateTime::from_timestamp(node.created_at, 0);
|
|
|
|
|
let ast = AstNode::memory(&node.key, &node.content)
|
|
|
|
|
.with_timestamp(ts.unwrap_or_else(chrono::Utc::now));
|
|
|
|
|
let tok = ast.tokens();
|
|
|
|
|
if total_tokens + tok > journal_budget && !entries.is_empty() {
|
2026-04-03 23:21:16 -04:00
|
|
|
break;
|
|
|
|
|
}
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
total_tokens += tok;
|
|
|
|
|
entries.push(ast);
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
entries.reverse();
|
2026-04-03 23:21:16 -04:00
|
|
|
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
if entries.is_empty() { return; }
|
2026-04-03 23:21:16 -04:00
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let mut ctx = self.context.lock().await;
|
|
|
|
|
ctx.clear(Section::Journal);
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
for entry in entries {
|
2026-04-09 01:10:40 -04:00
|
|
|
ctx.push_no_log(Section::Journal, entry);
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
pub async fn compact(&self) {
|
2026-04-03 23:21:16 -04:00
|
|
|
match crate::config::reload_for_model(&self.app_config, &self.prompt_file) {
|
2026-04-08 17:48:10 -04:00
|
|
|
Ok((_system_prompt, personality)) => {
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let mut ctx = self.context.lock().await;
|
2026-04-08 17:48:10 -04:00
|
|
|
// System section (prompt + tools) set by new(), don't touch it
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
ctx.clear(Section::Identity);
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
for (name, content) in &personality {
|
2026-04-09 01:10:40 -04:00
|
|
|
ctx.push_no_log(Section::Identity, AstNode::memory(name, content));
|
2026-04-07 20:15:31 -04:00
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
eprintln!("warning: failed to reload identity: {:#}", e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
self.load_startup_journal().await;
|
2026-04-06 21:48:12 -04:00
|
|
|
|
2026-04-08 21:20:50 -04:00
|
|
|
self.context.lock().await.trim_conversation();
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
let mut st = self.state.lock().await;
|
|
|
|
|
st.generation += 1;
|
|
|
|
|
st.last_prompt_tokens = 0;
|
2026-04-03 23:21:16 -04:00
|
|
|
}
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
pub async fn restore_from_log(&self) -> bool {
|
2026-04-09 13:09:26 -04:00
|
|
|
let tail = {
|
2026-04-09 00:32:32 -04:00
|
|
|
let ctx = self.context.lock().await;
|
|
|
|
|
match &ctx.conversation_log {
|
2026-04-09 13:09:26 -04:00
|
|
|
Some(log) => match log.read_tail() {
|
|
|
|
|
Ok(t) => t,
|
|
|
|
|
Err(_) => return false,
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
},
|
|
|
|
|
None => return false,
|
|
|
|
|
}
|
2026-04-03 23:21:16 -04:00
|
|
|
};
|
|
|
|
|
|
2026-04-09 13:06:19 -04:00
|
|
|
let budget = context::context_budget_tokens();
|
|
|
|
|
let fixed = {
|
|
|
|
|
let ctx = self.context.lock().await;
|
|
|
|
|
ctx.system().iter().chain(ctx.identity().iter())
|
|
|
|
|
.map(|n| n.tokens()).sum::<usize>()
|
|
|
|
|
};
|
|
|
|
|
let conv_budget = budget.saturating_sub(fixed);
|
|
|
|
|
|
2026-04-09 13:09:26 -04:00
|
|
|
// Walk backwards (newest first), retokenize, stop at budget
|
2026-04-09 13:06:19 -04:00
|
|
|
let mut kept = Vec::new();
|
|
|
|
|
let mut total = 0;
|
2026-04-09 13:09:26 -04:00
|
|
|
for node in tail.iter() {
|
2026-04-09 13:06:19 -04:00
|
|
|
let node = node.retokenize();
|
|
|
|
|
let tok = node.tokens();
|
|
|
|
|
if total + tok > conv_budget && !kept.is_empty() { break; }
|
|
|
|
|
total += tok;
|
|
|
|
|
kept.push(node);
|
|
|
|
|
}
|
|
|
|
|
kept.reverse();
|
|
|
|
|
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
{
|
|
|
|
|
let mut ctx = self.context.lock().await;
|
|
|
|
|
ctx.clear(Section::Conversation);
|
2026-04-09 13:06:19 -04:00
|
|
|
for node in kept {
|
2026-04-09 01:07:55 -04:00
|
|
|
ctx.push_no_log(Section::Conversation, node);
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
}
|
WIP: Agent core migrated to AST types
agent/mod.rs fully uses AstNode/ContextState/PendingToolCall.
Killed: push_message, push_entry, append_streaming, finalize_streaming,
streaming_index, assemble_api_messages, age_out_images, working_stack,
context_sections, entries. ConversationLog rewritten for AstNode.
Remaining: api dead code (chat path), mind/, user/, oneshot, learn.
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 14:59:38 -04:00
|
|
|
}
|
WIP: Agent/AgentState split — core methods migrated
turn(), push_node(), assemble_prompt_tokens(), compact(),
restore_from_log(), load_startup_journal(), apply_tool_result()
all use separate context/state locks. ToolHandler signature
updated to Arc<Agent>.
Remaining: tool handlers, control.rs, memory.rs, digest.rs,
and all outer callers (mind, user, learn, oneshot, dmn).
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-08 15:39:03 -04:00
|
|
|
self.compact().await;
|
2026-04-09 13:06:19 -04:00
|
|
|
self.state.lock().await.last_prompt_tokens = self.context.lock().await.tokens() as u32;
|
2026-04-03 23:21:16 -04:00
|
|
|
true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn model(&self) -> &str {
|
|
|
|
|
&self.client.model
|
|
|
|
|
}
|
2026-04-01 15:12:14 -04:00
|
|
|
}
|