consciousness/src/mind/unconscious.rs

236 lines
7.2 KiB
Rust
Raw Normal View History

// unconscious.rs — Graph maintenance agents
//
// Standalone agents that operate on the memory graph without needing
// conversation context. Each agent runs in a loop: finish one run,
// wait a cooldown, start the next. Agents can be toggled on/off,
// persisted to ~/.consciousness/agent-enabled.json.
use std::time::{Duration, Instant};
use std::collections::HashMap;
use crate::agent::oneshot::{AutoAgent, AutoStep};
use crate::agent::tools;
use crate::subconscious::defs;
/// Cooldown between consecutive runs of the same agent.
const COOLDOWN: Duration = Duration::from_secs(120);
fn config_path() -> std::path::PathBuf {
dirs::home_dir().unwrap_or_default()
.join(".consciousness/agent-enabled.json")
}
fn load_enabled_config() -> HashMap<String, bool> {
std::fs::read_to_string(config_path()).ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default()
}
fn save_enabled_config(map: &HashMap<String, bool>) {
if let Ok(json) = serde_json::to_string_pretty(map) {
let _ = std::fs::write(config_path(), json);
}
}
struct UnconsciousAgent {
name: String,
enabled: bool,
handle: Option<tokio::task::JoinHandle<(AutoAgent, Result<String, String>)>>,
last_run: Option<Instant>,
runs: usize,
}
impl UnconsciousAgent {
fn is_running(&self) -> bool {
self.handle.as_ref().is_some_and(|h| !h.is_finished())
}
fn should_run(&self) -> bool {
if !self.enabled || self.is_running() { return false; }
match self.last_run {
Some(t) => t.elapsed() >= COOLDOWN,
None => true,
}
}
}
/// Snapshot for the TUI.
#[derive(Clone)]
pub struct UnconsciousSnapshot {
pub name: String,
pub running: bool,
pub enabled: bool,
pub runs: usize,
pub last_run_secs_ago: Option<f64>,
}
pub struct Unconscious {
agents: Vec<UnconsciousAgent>,
max_concurrent: usize,
pub graph_health: Option<crate::subconscious::daemon::GraphHealth>,
last_health_check: Option<Instant>,
}
impl Unconscious {
pub fn new() -> Self {
let enabled_map = load_enabled_config();
// Scan all .agent files, exclude subconscious-* and surface-observe
let mut agents: Vec<UnconsciousAgent> = Vec::new();
for def in defs::load_defs() {
if def.agent.starts_with("subconscious-") { continue; }
if def.agent == "surface-observe" { continue; }
let enabled = enabled_map.get(&def.agent).copied()
.unwrap_or(false); // new agents default to off
agents.push(UnconsciousAgent {
name: def.agent.clone(),
enabled,
handle: None,
last_run: None,
runs: 0,
});
}
agents.sort_by(|a, b| a.name.cmp(&b.name));
let mut s = Self {
agents, max_concurrent: 2,
graph_health: None,
last_health_check: None,
};
s.refresh_health();
s
}
/// Toggle an agent on/off by name. Returns new enabled state.
/// If enabling, immediately spawns the agent if it's not running.
pub fn toggle(&mut self, name: &str) -> Option<bool> {
let idx = self.agents.iter().position(|a| a.name == name)?;
self.agents[idx].enabled = !self.agents[idx].enabled;
let new_state = self.agents[idx].enabled;
self.save_enabled();
if new_state && !self.agents[idx].is_running() {
self.spawn_agent(idx);
}
Some(new_state)
}
fn save_enabled(&self) {
let map: HashMap<String, bool> = self.agents.iter()
.map(|a| (a.name.clone(), a.enabled))
.collect();
save_enabled_config(&map);
}
pub fn snapshots(&self) -> Vec<UnconsciousSnapshot> {
self.agents.iter().map(|a| UnconsciousSnapshot {
name: a.name.clone(),
running: a.is_running(),
enabled: a.enabled,
runs: a.runs,
last_run_secs_ago: a.last_run.map(|t| t.elapsed().as_secs_f64()),
}).collect()
}
fn refresh_health(&mut self) {
let store = match crate::store::Store::load() {
Ok(s) => s,
Err(_) => return,
};
self.graph_health = Some(crate::subconscious::daemon::compute_graph_health(&store));
self.last_health_check = Some(Instant::now());
}
/// Reap finished agents and spawn new ones.
pub fn trigger(&mut self) {
// Periodic graph health refresh
if self.last_health_check
.map(|t| t.elapsed() > Duration::from_secs(600))
.unwrap_or(false)
{
self.refresh_health();
}
for agent in &mut self.agents {
if agent.handle.as_ref().is_some_and(|h| h.is_finished()) {
agent.last_run = Some(Instant::now());
agent.runs += 1;
dbglog!("[unconscious] {} completed (run {})",
agent.name, agent.runs);
agent.handle = None;
}
}
let running = self.agents.iter().filter(|a| a.is_running()).count();
if running >= self.max_concurrent { return; }
let slots = self.max_concurrent - running;
let ready: Vec<usize> = self.agents.iter().enumerate()
.filter(|(_, a)| a.should_run())
.map(|(i, _)| i)
.take(slots)
.collect();
for idx in ready {
self.spawn_agent(idx);
}
}
fn spawn_agent(&mut self, idx: usize) {
let name = self.agents[idx].name.clone();
dbglog!("[unconscious] spawning {}", name);
let def = match defs::get_def(&name) {
Some(d) => d,
None => return,
};
let all_tools = tools::memory_and_journal_tools();
let effective_tools: Vec<tools::Tool> = if def.tools.is_empty() {
all_tools
} else {
all_tools.into_iter()
.filter(|t| def.tools.iter().any(|w| w == t.name))
.collect()
};
let mut store = match crate::store::Store::load() {
Ok(s) => s,
Err(e) => {
dbglog!("[unconscious] store load failed: {}", e);
return;
}
};
let exclude: std::collections::HashSet<String> = std::collections::HashSet::new();
let batch = match defs::run_agent(
&store, &def, def.count.unwrap_or(5), &exclude,
) {
Ok(b) => b,
Err(e) => {
dbglog!("[unconscious] {} query failed: {}", name, e);
return;
}
};
if !batch.node_keys.is_empty() {
store.record_agent_visits(&batch.node_keys, &name).ok();
}
let steps: Vec<AutoStep> = batch.steps.iter().map(|s| AutoStep {
prompt: s.prompt.clone(),
phase: s.phase.clone(),
}).collect();
let mut auto = AutoAgent::new(
name, effective_tools, steps,
def.temperature.unwrap_or(0.6),
def.priority,
);
self.agents[idx].handle = Some(tokio::spawn(async move {
let result = auto.run(None).await;
(auto, result)
}));
}
}