2026-04-07 01:07:04 -04:00
|
|
|
// oneshot.rs — Autonomous agent execution
|
2026-03-05 15:30:57 -05:00
|
|
|
//
|
2026-04-07 01:07:04 -04:00
|
|
|
// AutoAgent: wraps an Agent with a multi-step prompt sequence and an
|
|
|
|
|
// async run() method. Used for both oneshot CLI agents (from .agent
|
|
|
|
|
// files) and subconscious agents forked from the conscious agent.
|
Remove dead action pipeline: parsing, depth tracking, knowledge loop, fact miner
Agents now apply changes via tool calls (poc-memory write/link-add/etc)
during the LLM call. The old pipeline — where agents output WRITE_NODE/
LINK/REFINE text, which was parsed and applied separately — is dead code.
Removed:
- Action/ActionKind/Confidence types and all parse_* functions
- DepthDb, depth tracking, confidence gating
- apply_action, stamp_content, has_edge
- NamingResolution, resolve_naming and related naming agent code
- KnowledgeLoopConfig, CycleResult, GraphMetrics, convergence checking
- run_knowledge_loop, run_cycle, check_convergence
- apply_consolidation (old report re-processing)
- fact_mine.rs (folded into observation agent)
- resolve_action_names
Simplified:
- AgentResult no longer carries actions/no_ops
- run_and_apply_with_log just runs the agent
- consolidate_full simplified action tracking
-1364 lines.
2026-03-17 00:37:12 -04:00
|
|
|
//
|
2026-04-07 01:07:04 -04:00
|
|
|
// Also contains the legacy run_one_agent() pipeline and process
|
|
|
|
|
// management for spawned agent subprocesses.
|
2026-03-05 15:30:57 -05:00
|
|
|
|
Remove dead action pipeline: parsing, depth tracking, knowledge loop, fact miner
Agents now apply changes via tool calls (poc-memory write/link-add/etc)
during the LLM call. The old pipeline — where agents output WRITE_NODE/
LINK/REFINE text, which was parsed and applied separately — is dead code.
Removed:
- Action/ActionKind/Confidence types and all parse_* functions
- DepthDb, depth tracking, confidence gating
- apply_action, stamp_content, has_edge
- NamingResolution, resolve_naming and related naming agent code
- KnowledgeLoopConfig, CycleResult, GraphMetrics, convergence checking
- run_knowledge_loop, run_cycle, check_convergence
- apply_consolidation (old report re-processing)
- fact_mine.rs (folded into observation agent)
- resolve_action_names
Simplified:
- AgentResult no longer carries actions/no_ops
- run_and_apply_with_log just runs the agent
- consolidate_full simplified action tracking
-1364 lines.
2026-03-17 00:37:12 -04:00
|
|
|
use crate::store::{self, Store};
|
2026-04-04 17:25:10 -04:00
|
|
|
use crate::subconscious::{defs, prompts};
|
2026-03-05 15:30:57 -05:00
|
|
|
|
|
|
|
|
use std::fs;
|
Remove dead action pipeline: parsing, depth tracking, knowledge loop, fact miner
Agents now apply changes via tool calls (poc-memory write/link-add/etc)
during the LLM call. The old pipeline — where agents output WRITE_NODE/
LINK/REFINE text, which was parsed and applied separately — is dead code.
Removed:
- Action/ActionKind/Confidence types and all parse_* functions
- DepthDb, depth tracking, confidence gating
- apply_action, stamp_content, has_edge
- NamingResolution, resolve_naming and related naming agent code
- KnowledgeLoopConfig, CycleResult, GraphMetrics, convergence checking
- run_knowledge_loop, run_cycle, check_convergence
- apply_consolidation (old report re-processing)
- fact_mine.rs (folded into observation agent)
- resolve_action_names
Simplified:
- AgentResult no longer carries actions/no_ops
- run_and_apply_with_log just runs the agent
- consolidate_full simplified action tracking
-1364 lines.
2026-03-17 00:37:12 -04:00
|
|
|
use std::path::PathBuf;
|
2026-04-07 00:57:35 -04:00
|
|
|
use std::sync::OnceLock;
|
|
|
|
|
|
|
|
|
|
use super::api::ApiClient;
|
|
|
|
|
use super::api::types::*;
|
|
|
|
|
use super::tools::{self as agent_tools};
|
2026-04-07 01:07:04 -04:00
|
|
|
use super::Agent;
|
2026-04-07 00:57:35 -04:00
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// API client — shared across oneshot agent runs
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
static API_CLIENT: OnceLock<ApiClient> = OnceLock::new();
|
|
|
|
|
|
|
|
|
|
fn get_client() -> Result<&'static ApiClient, String> {
|
|
|
|
|
Ok(API_CLIENT.get_or_init(|| {
|
|
|
|
|
let config = crate::config::get();
|
|
|
|
|
let base_url = config.api_base_url.as_deref().unwrap_or("");
|
|
|
|
|
let api_key = config.api_key.as_deref().unwrap_or("");
|
|
|
|
|
let model = config.api_model.as_deref().unwrap_or("qwen-2.5-27b");
|
|
|
|
|
ApiClient::new(base_url, api_key, model)
|
|
|
|
|
}))
|
|
|
|
|
}
|
2026-03-05 15:30:57 -05:00
|
|
|
|
2026-04-07 01:07:04 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// AutoAgent — multi-step autonomous agent
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
pub struct AutoStep {
|
|
|
|
|
pub prompt: String,
|
|
|
|
|
pub phase: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// An autonomous agent that runs a sequence of prompts with tool dispatch.
|
|
|
|
|
///
|
2026-04-07 01:57:01 -04:00
|
|
|
/// Persistent across runs — holds config, tools, steps, and inter-run
|
|
|
|
|
/// state (walked keys). The conversation backend is ephemeral per run.
|
2026-04-07 01:07:04 -04:00
|
|
|
pub struct AutoAgent {
|
|
|
|
|
pub name: String,
|
2026-04-07 01:57:01 -04:00
|
|
|
pub tools: Vec<agent_tools::Tool>,
|
|
|
|
|
pub steps: Vec<AutoStep>,
|
2026-04-07 01:07:04 -04:00
|
|
|
sampling: super::api::SamplingParams,
|
|
|
|
|
priority: i32,
|
2026-04-07 01:57:01 -04:00
|
|
|
/// Memory keys the surface agent was exploring — persists between runs.
|
|
|
|
|
pub walked: Vec<String>,
|
2026-04-07 02:04:29 -04:00
|
|
|
/// Named outputs from the agent's output() tool calls.
|
|
|
|
|
/// Collected per-run, read by Mind after completion.
|
|
|
|
|
pub outputs: std::collections::HashMap<String, String>,
|
2026-04-07 02:08:48 -04:00
|
|
|
/// Entries added during the last forked run (after the fork point).
|
|
|
|
|
/// The subconscious screen shows these.
|
|
|
|
|
pub last_run_entries: Vec<super::context::ConversationEntry>,
|
2026-04-07 01:07:04 -04:00
|
|
|
// Observable status
|
|
|
|
|
pub current_phase: String,
|
|
|
|
|
pub turn: usize,
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
/// Per-run conversation backend — created fresh by run() or run_forked().
|
2026-04-07 01:12:54 -04:00
|
|
|
enum Backend {
|
2026-04-07 01:57:01 -04:00
|
|
|
Standalone { client: ApiClient, messages: Vec<Message> },
|
2026-04-07 01:12:54 -04:00
|
|
|
Forked(Agent),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Backend {
|
|
|
|
|
fn client(&self) -> &ApiClient {
|
|
|
|
|
match self {
|
|
|
|
|
Backend::Standalone { client, .. } => client,
|
|
|
|
|
Backend::Forked(agent) => &agent.client,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn messages(&self) -> Vec<Message> {
|
|
|
|
|
match self {
|
|
|
|
|
Backend::Standalone { messages, .. } => messages.clone(),
|
|
|
|
|
Backend::Forked(agent) => agent.assemble_api_messages(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn push_message(&mut self, msg: Message) {
|
|
|
|
|
match self {
|
|
|
|
|
Backend::Standalone { messages, .. } => messages.push(msg),
|
|
|
|
|
Backend::Forked(agent) => agent.push_message(msg),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn push_raw(&mut self, msg: Message) {
|
|
|
|
|
match self {
|
|
|
|
|
Backend::Standalone { messages, .. } => messages.push(msg),
|
|
|
|
|
Backend::Forked(agent) => {
|
|
|
|
|
agent.context.entries.push(
|
|
|
|
|
super::context::ConversationEntry::Message(msg));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-07 01:23:22 -04:00
|
|
|
|
|
|
|
|
fn log(&self, text: String) {
|
2026-04-07 01:57:01 -04:00
|
|
|
if let Backend::Forked(agent) = self {
|
|
|
|
|
if let Some(ref log) = agent.conversation_log {
|
|
|
|
|
let entry = super::context::ConversationEntry::Log(text);
|
|
|
|
|
log.append(&entry).ok();
|
2026-04-07 01:23:22 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-07 01:12:54 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
/// Resolve {{placeholder}} templates in subconscious agent prompts.
|
|
|
|
|
fn resolve_prompt(template: &str, memory_keys: &[String], walked: &[String]) -> String {
|
|
|
|
|
let mut result = String::with_capacity(template.len());
|
|
|
|
|
let mut rest = template;
|
|
|
|
|
while let Some(start) = rest.find("{{") {
|
|
|
|
|
result.push_str(&rest[..start]);
|
|
|
|
|
let after = &rest[start + 2..];
|
|
|
|
|
if let Some(end) = after.find("}}") {
|
|
|
|
|
let name = after[..end].trim();
|
|
|
|
|
let replacement = match name {
|
|
|
|
|
"seen_current" => format_key_list(memory_keys),
|
|
|
|
|
"walked" => format_key_list(walked),
|
|
|
|
|
_ => {
|
|
|
|
|
result.push_str("{{");
|
|
|
|
|
result.push_str(&after[..end + 2]);
|
|
|
|
|
rest = &after[end + 2..];
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
result.push_str(&replacement);
|
|
|
|
|
rest = &after[end + 2..];
|
|
|
|
|
} else {
|
|
|
|
|
result.push_str("{{");
|
|
|
|
|
rest = after;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
result.push_str(rest);
|
|
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn format_key_list(keys: &[String]) -> String {
|
|
|
|
|
if keys.is_empty() { "(none)".to_string() }
|
|
|
|
|
else { keys.iter().map(|k| format!("- {}", k)).collect::<Vec<_>>().join("\n") }
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:07:04 -04:00
|
|
|
impl AutoAgent {
|
|
|
|
|
pub fn new(
|
|
|
|
|
name: String,
|
|
|
|
|
tools: Vec<agent_tools::Tool>,
|
|
|
|
|
steps: Vec<AutoStep>,
|
|
|
|
|
temperature: f32,
|
|
|
|
|
priority: i32,
|
|
|
|
|
) -> Self {
|
|
|
|
|
Self {
|
2026-04-07 01:57:01 -04:00
|
|
|
name, tools, steps,
|
2026-04-07 01:07:04 -04:00
|
|
|
sampling: super::api::SamplingParams {
|
2026-04-07 01:57:01 -04:00
|
|
|
temperature, top_p: 0.95, top_k: 20,
|
2026-04-07 01:07:04 -04:00
|
|
|
},
|
|
|
|
|
priority,
|
2026-04-07 01:57:01 -04:00
|
|
|
walked: Vec::new(),
|
2026-04-07 02:04:29 -04:00
|
|
|
outputs: std::collections::HashMap::new(),
|
2026-04-07 02:08:48 -04:00
|
|
|
last_run_entries: Vec::new(),
|
2026-04-07 01:57:01 -04:00
|
|
|
current_phase: String::new(),
|
2026-04-07 01:07:04 -04:00
|
|
|
turn: 0,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
/// Run standalone — creates a fresh message list from the global
|
|
|
|
|
/// API client. Used by oneshot CLI agents.
|
2026-04-07 01:07:04 -04:00
|
|
|
pub async fn run(
|
|
|
|
|
&mut self,
|
|
|
|
|
bail_fn: Option<&(dyn Fn(usize) -> Result<(), String> + Sync)>,
|
|
|
|
|
) -> Result<String, String> {
|
2026-04-07 01:57:01 -04:00
|
|
|
let client = get_client()?.clone();
|
|
|
|
|
let mut backend = Backend::Standalone {
|
|
|
|
|
client, messages: Vec::new(),
|
|
|
|
|
};
|
|
|
|
|
self.run_with_backend(&mut backend, bail_fn).await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Run forked from a conscious agent's context. Each call gets a
|
|
|
|
|
/// fresh fork for KV cache sharing. Walked state persists between runs.
|
|
|
|
|
///
|
|
|
|
|
/// `memory_keys`: keys of Memory entries in the conscious agent's
|
|
|
|
|
/// context, used to resolve {{seen_current}} in prompt templates.
|
|
|
|
|
pub async fn run_forked(
|
|
|
|
|
&mut self,
|
|
|
|
|
agent: &Agent,
|
|
|
|
|
memory_keys: &[String],
|
|
|
|
|
) -> Result<String, String> {
|
|
|
|
|
// Resolve prompt templates with current state
|
|
|
|
|
let resolved_steps: Vec<AutoStep> = self.steps.iter().map(|s| AutoStep {
|
|
|
|
|
prompt: resolve_prompt(&s.prompt, memory_keys, &self.walked),
|
|
|
|
|
phase: s.phase.clone(),
|
|
|
|
|
}).collect();
|
|
|
|
|
let orig_steps = std::mem::replace(&mut self.steps, resolved_steps);
|
|
|
|
|
let forked = agent.fork(self.tools.clone());
|
2026-04-07 02:08:48 -04:00
|
|
|
let fork_point = forked.context.entries.len();
|
2026-04-07 01:57:01 -04:00
|
|
|
let mut backend = Backend::Forked(forked);
|
|
|
|
|
let result = self.run_with_backend(&mut backend, None).await;
|
2026-04-07 02:08:48 -04:00
|
|
|
// Capture entries added during this run
|
|
|
|
|
if let Backend::Forked(ref agent) = backend {
|
|
|
|
|
self.last_run_entries = agent.context.entries[fork_point..].to_vec();
|
|
|
|
|
}
|
|
|
|
|
self.steps = orig_steps;
|
2026-04-07 01:57:01 -04:00
|
|
|
result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn run_with_backend(
|
|
|
|
|
&mut self,
|
|
|
|
|
backend: &mut Backend,
|
|
|
|
|
bail_fn: Option<&(dyn Fn(usize) -> Result<(), String> + Sync)>,
|
|
|
|
|
) -> Result<String, String> {
|
|
|
|
|
self.turn = 0;
|
2026-04-07 02:04:29 -04:00
|
|
|
self.outputs.clear();
|
2026-04-07 01:57:01 -04:00
|
|
|
self.current_phase = self.steps.first()
|
|
|
|
|
.map(|s| s.phase.clone()).unwrap_or_default();
|
|
|
|
|
let mut next_step = 0;
|
|
|
|
|
|
|
|
|
|
if next_step < self.steps.len() {
|
|
|
|
|
backend.push_message(
|
|
|
|
|
Message::user(&self.steps[next_step].prompt));
|
|
|
|
|
next_step += 1;
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let reasoning = crate::config::get().api_reasoning.clone();
|
|
|
|
|
let max_turns = 50 * self.steps.len().max(1);
|
|
|
|
|
|
|
|
|
|
for _ in 0..max_turns {
|
|
|
|
|
self.turn += 1;
|
2026-04-07 01:57:01 -04:00
|
|
|
let messages = backend.messages();
|
|
|
|
|
backend.log(format!("turn {} ({} messages)",
|
2026-04-07 01:12:54 -04:00
|
|
|
self.turn, messages.len()));
|
2026-04-07 01:07:04 -04:00
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
let (msg, usage_opt) = Self::api_call_with_retry(
|
|
|
|
|
&self.name, backend, &self.tools, &messages,
|
|
|
|
|
&reasoning, self.sampling, self.priority).await?;
|
2026-04-07 01:07:04 -04:00
|
|
|
|
|
|
|
|
if let Some(u) = &usage_opt {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!("tokens: {} prompt + {} completion",
|
2026-04-07 01:07:04 -04:00
|
|
|
u.prompt_tokens, u.completion_tokens));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let has_content = msg.content.is_some();
|
|
|
|
|
let has_tools = msg.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty());
|
|
|
|
|
|
|
|
|
|
if has_tools {
|
2026-04-07 02:04:29 -04:00
|
|
|
self.dispatch_tools(backend, &msg).await;
|
2026-04-07 01:07:04 -04:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let text = msg.content_text().to_string();
|
|
|
|
|
if text.is_empty() && !has_content {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log("empty response, retrying".into());
|
|
|
|
|
backend.push_message(Message::user(
|
2026-04-07 01:07:04 -04:00
|
|
|
"[system] Your previous response was empty. \
|
|
|
|
|
Please respond with text or use a tool."
|
|
|
|
|
));
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!("response: {}",
|
2026-04-07 01:23:22 -04:00
|
|
|
&text[..text.len().min(200)]));
|
2026-04-07 01:07:04 -04:00
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
if next_step < self.steps.len() {
|
2026-04-07 01:07:04 -04:00
|
|
|
if let Some(ref check) = bail_fn {
|
2026-04-07 01:57:01 -04:00
|
|
|
check(next_step)?;
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
2026-04-07 01:57:01 -04:00
|
|
|
self.current_phase = self.steps[next_step].phase.clone();
|
|
|
|
|
backend.push_message(Message::assistant(&text));
|
|
|
|
|
backend.push_message(
|
|
|
|
|
Message::user(&self.steps[next_step].prompt));
|
|
|
|
|
next_step += 1;
|
|
|
|
|
backend.log(format!("step {}/{}",
|
|
|
|
|
next_step, self.steps.len()));
|
2026-04-07 01:07:04 -04:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Ok(text);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Err(format!("{}: exceeded {} tool turns", self.name, max_turns))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn api_call_with_retry(
|
2026-04-07 01:57:01 -04:00
|
|
|
name: &str,
|
|
|
|
|
backend: &Backend,
|
|
|
|
|
tools: &[agent_tools::Tool],
|
2026-04-07 01:12:54 -04:00
|
|
|
messages: &[Message],
|
2026-04-07 01:07:04 -04:00
|
|
|
reasoning: &str,
|
2026-04-07 01:57:01 -04:00
|
|
|
sampling: super::api::SamplingParams,
|
|
|
|
|
priority: i32,
|
2026-04-07 01:07:04 -04:00
|
|
|
) -> Result<(Message, Option<Usage>), String> {
|
2026-04-07 01:57:01 -04:00
|
|
|
let client = backend.client();
|
2026-04-07 01:07:04 -04:00
|
|
|
let mut last_err = None;
|
|
|
|
|
for attempt in 0..5 {
|
2026-04-07 01:12:54 -04:00
|
|
|
match client.chat_completion_stream_temp(
|
2026-04-07 01:57:01 -04:00
|
|
|
messages, tools, reasoning, sampling, Some(priority),
|
2026-04-07 01:07:04 -04:00
|
|
|
).await {
|
|
|
|
|
Ok((msg, usage)) => {
|
|
|
|
|
if let Some(ref e) = last_err {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!(
|
2026-04-07 01:23:22 -04:00
|
|
|
"succeeded after retry (previous: {})", e));
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
|
|
|
|
return Ok((msg, usage));
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
let err_str = e.to_string();
|
|
|
|
|
let is_transient = err_str.contains("IncompleteMessage")
|
|
|
|
|
|| err_str.contains("connection closed")
|
|
|
|
|
|| err_str.contains("connection reset")
|
|
|
|
|
|| err_str.contains("timed out")
|
|
|
|
|
|| err_str.contains("Connection refused");
|
|
|
|
|
if is_transient && attempt < 4 {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!(
|
2026-04-07 01:23:22 -04:00
|
|
|
"transient error (attempt {}): {}, retrying",
|
2026-04-07 01:07:04 -04:00
|
|
|
attempt + 1, err_str));
|
|
|
|
|
tokio::time::sleep(std::time::Duration::from_secs(2 << attempt)).await;
|
|
|
|
|
last_err = Some(e);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-04-07 01:12:54 -04:00
|
|
|
let msg_bytes: usize = messages.iter()
|
2026-04-07 01:57:01 -04:00
|
|
|
.map(|m| m.content_text().len()).sum();
|
2026-04-07 01:07:04 -04:00
|
|
|
return Err(format!(
|
2026-04-07 01:57:01 -04:00
|
|
|
"{}: API error (~{}KB, {} messages, {} attempts): {}",
|
|
|
|
|
name, msg_bytes / 1024,
|
2026-04-07 01:12:54 -04:00
|
|
|
messages.len(), attempt + 1, e));
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
unreachable!()
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 02:04:29 -04:00
|
|
|
async fn dispatch_tools(&mut self, backend: &mut Backend, msg: &Message) {
|
2026-04-07 01:07:04 -04:00
|
|
|
let mut sanitized = msg.clone();
|
|
|
|
|
if let Some(ref mut calls) = sanitized.tool_calls {
|
|
|
|
|
for call in calls {
|
|
|
|
|
if serde_json::from_str::<serde_json::Value>(&call.function.arguments).is_err() {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!(
|
2026-04-07 01:23:22 -04:00
|
|
|
"sanitizing malformed args for {}: {}",
|
2026-04-07 01:07:04 -04:00
|
|
|
call.function.name, &call.function.arguments));
|
|
|
|
|
call.function.arguments = "{}".to_string();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.push_raw(sanitized);
|
2026-04-07 01:07:04 -04:00
|
|
|
|
|
|
|
|
for call in msg.tool_calls.as_ref().unwrap() {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!("tool: {}({})",
|
2026-04-07 01:07:04 -04:00
|
|
|
call.function.name, &call.function.arguments));
|
|
|
|
|
|
|
|
|
|
let args: serde_json::Value = match serde_json::from_str(&call.function.arguments) {
|
|
|
|
|
Ok(v) => v,
|
|
|
|
|
Err(_) => {
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.push_raw(Message::tool_result(
|
2026-04-07 01:07:04 -04:00
|
|
|
&call.id,
|
|
|
|
|
"Error: your tool call had malformed JSON arguments. \
|
|
|
|
|
Please retry with valid JSON.",
|
|
|
|
|
));
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-04-07 02:04:29 -04:00
|
|
|
// Intercept output() — store in-memory instead of filesystem
|
|
|
|
|
let output = if call.function.name == "output" {
|
|
|
|
|
let key = args["key"].as_str().unwrap_or("");
|
|
|
|
|
let value = args["value"].as_str().unwrap_or("");
|
|
|
|
|
if !key.is_empty() {
|
|
|
|
|
self.outputs.insert(key.to_string(), value.to_string());
|
|
|
|
|
}
|
|
|
|
|
format!("{}: {}", key, value)
|
|
|
|
|
} else {
|
|
|
|
|
agent_tools::dispatch(&call.function.name, &args).await
|
|
|
|
|
};
|
|
|
|
|
|
2026-04-07 01:57:01 -04:00
|
|
|
backend.log(format!("result: {} chars", output.len()));
|
|
|
|
|
backend.push_raw(Message::tool_result(&call.id, &output));
|
2026-04-07 01:07:04 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-05 15:30:57 -05:00
|
|
|
// ---------------------------------------------------------------------------
|
Remove dead action pipeline: parsing, depth tracking, knowledge loop, fact miner
Agents now apply changes via tool calls (poc-memory write/link-add/etc)
during the LLM call. The old pipeline — where agents output WRITE_NODE/
LINK/REFINE text, which was parsed and applied separately — is dead code.
Removed:
- Action/ActionKind/Confidence types and all parse_* functions
- DepthDb, depth tracking, confidence gating
- apply_action, stamp_content, has_edge
- NamingResolution, resolve_naming and related naming agent code
- KnowledgeLoopConfig, CycleResult, GraphMetrics, convergence checking
- run_knowledge_loop, run_cycle, check_convergence
- apply_consolidation (old report re-processing)
- fact_mine.rs (folded into observation agent)
- resolve_action_names
Simplified:
- AgentResult no longer carries actions/no_ops
- run_and_apply_with_log just runs the agent
- consolidate_full simplified action tracking
-1364 lines.
2026-03-17 00:37:12 -04:00
|
|
|
// Agent execution
|
2026-03-05 15:30:57 -05:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
Remove dead action pipeline: parsing, depth tracking, knowledge loop, fact miner
Agents now apply changes via tool calls (poc-memory write/link-add/etc)
during the LLM call. The old pipeline — where agents output WRITE_NODE/
LINK/REFINE text, which was parsed and applied separately — is dead code.
Removed:
- Action/ActionKind/Confidence types and all parse_* functions
- DepthDb, depth tracking, confidence gating
- apply_action, stamp_content, has_edge
- NamingResolution, resolve_naming and related naming agent code
- KnowledgeLoopConfig, CycleResult, GraphMetrics, convergence checking
- run_knowledge_loop, run_cycle, check_convergence
- apply_consolidation (old report re-processing)
- fact_mine.rs (folded into observation agent)
- resolve_action_names
Simplified:
- AgentResult no longer carries actions/no_ops
- run_and_apply_with_log just runs the agent
- consolidate_full simplified action tracking
-1364 lines.
2026-03-17 00:37:12 -04:00
|
|
|
/// Result of running a single agent.
|
2026-03-10 17:33:12 -04:00
|
|
|
pub struct AgentResult {
|
|
|
|
|
pub output: String,
|
|
|
|
|
pub node_keys: Vec<String>,
|
2026-03-26 14:21:43 -04:00
|
|
|
/// Directory containing output() files from the agent run.
|
2026-04-04 17:33:36 -04:00
|
|
|
pub state_dir: PathBuf,
|
2026-03-10 17:33:12 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
/// Run an agent. If keys are provided, use them directly (bypassing the
|
|
|
|
|
/// agent's query). Otherwise, run the query to select target nodes.
|
|
|
|
|
pub fn run_one_agent(
|
2026-03-17 00:24:24 -04:00
|
|
|
store: &mut Store,
|
|
|
|
|
agent_name: &str,
|
|
|
|
|
count: usize,
|
2026-04-04 17:33:36 -04:00
|
|
|
keys: Option<&[String]>,
|
2026-03-17 00:24:24 -04:00
|
|
|
) -> Result<AgentResult, String> {
|
2026-04-04 17:25:10 -04:00
|
|
|
let def = defs::get_def(agent_name)
|
2026-03-17 00:24:24 -04:00
|
|
|
.ok_or_else(|| format!("no .agent file for {}", agent_name))?;
|
|
|
|
|
|
2026-04-04 17:47:49 -04:00
|
|
|
// State dir for agent output files
|
|
|
|
|
let state_dir = std::env::var("POC_AGENT_OUTPUT_DIR")
|
|
|
|
|
.map(PathBuf::from)
|
|
|
|
|
.unwrap_or_else(|_| store::memory_dir().join("agent-output").join(agent_name));
|
|
|
|
|
fs::create_dir_all(&state_dir)
|
|
|
|
|
.map_err(|e| format!("create state dir: {}", e))?;
|
|
|
|
|
unsafe { std::env::set_var("POC_AGENT_OUTPUT_DIR", &state_dir); }
|
2026-03-26 15:58:59 -04:00
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
// Build prompt batch — either from explicit keys or the agent's query
|
|
|
|
|
let agent_batch = if let Some(keys) = keys {
|
2026-04-07 01:23:22 -04:00
|
|
|
dbglog!("[{}] targeting: {}", agent_name, keys.join(", "));
|
2026-04-04 17:33:36 -04:00
|
|
|
let graph = store.build_graph();
|
|
|
|
|
let mut resolved_steps = Vec::new();
|
|
|
|
|
let mut all_keys: Vec<String> = keys.to_vec();
|
|
|
|
|
for step in &def.steps {
|
|
|
|
|
let (prompt, extra_keys) = defs::resolve_placeholders(
|
|
|
|
|
&step.prompt, store, &graph, keys, count,
|
|
|
|
|
);
|
|
|
|
|
all_keys.extend(extra_keys);
|
|
|
|
|
resolved_steps.push(prompts::ResolvedStep {
|
|
|
|
|
prompt,
|
|
|
|
|
phase: step.phase.clone(),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
let batch = prompts::AgentBatch { steps: resolved_steps, node_keys: all_keys };
|
|
|
|
|
if !batch.node_keys.is_empty() {
|
|
|
|
|
store.record_agent_visits(&batch.node_keys, agent_name).ok();
|
|
|
|
|
}
|
|
|
|
|
batch
|
|
|
|
|
} else {
|
|
|
|
|
let effective_count = def.count.unwrap_or(count);
|
|
|
|
|
defs::run_agent(store, &def, effective_count, &Default::default())?
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Filter tools based on agent def
|
|
|
|
|
let all_tools = super::tools::memory_and_journal_tools();
|
|
|
|
|
let effective_tools: Vec<super::tools::Tool> = if def.tools.is_empty() {
|
|
|
|
|
all_tools.to_vec()
|
|
|
|
|
} else {
|
|
|
|
|
all_tools.into_iter()
|
|
|
|
|
.filter(|t| def.tools.iter().any(|w| w == &t.name))
|
|
|
|
|
.collect()
|
|
|
|
|
};
|
|
|
|
|
let n_steps = agent_batch.steps.len();
|
|
|
|
|
|
|
|
|
|
// Guard: reject oversized first prompt
|
|
|
|
|
let max_prompt_bytes = 800_000;
|
|
|
|
|
let first_len = agent_batch.steps[0].prompt.len();
|
|
|
|
|
if first_len > max_prompt_bytes {
|
|
|
|
|
let prompt_kb = first_len / 1024;
|
|
|
|
|
let oversize_dir = store::memory_dir().join("llm-logs").join("oversized");
|
|
|
|
|
fs::create_dir_all(&oversize_dir).ok();
|
|
|
|
|
let oversize_path = oversize_dir.join(format!("{}-{}.txt",
|
|
|
|
|
agent_name, store::compact_timestamp()));
|
|
|
|
|
let header = format!("=== OVERSIZED PROMPT ===\nagent: {}\nsize: {}KB (max {}KB)\nnodes: {:?}\n\n",
|
|
|
|
|
agent_name, prompt_kb, max_prompt_bytes / 1024, agent_batch.node_keys);
|
|
|
|
|
fs::write(&oversize_path, format!("{}{}", header, &agent_batch.steps[0].prompt)).ok();
|
|
|
|
|
return Err(format!(
|
|
|
|
|
"prompt too large: {}KB (max {}KB) — seed nodes may be oversized",
|
|
|
|
|
prompt_kb, max_prompt_bytes / 1024,
|
|
|
|
|
));
|
2026-03-20 12:29:32 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
let phases: Vec<&str> = agent_batch.steps.iter().map(|s| s.phase.as_str()).collect();
|
2026-04-07 01:23:22 -04:00
|
|
|
dbglog!("[{}] {} step(s) {:?}, {}KB initial, {} nodes",
|
|
|
|
|
agent_name, n_steps, phases, first_len / 1024, agent_batch.node_keys.len());
|
2026-03-17 00:24:24 -04:00
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
let prompts: Vec<String> = agent_batch.steps.iter()
|
|
|
|
|
.map(|s| s.prompt.clone()).collect();
|
|
|
|
|
let step_phases: Vec<String> = agent_batch.steps.iter()
|
|
|
|
|
.map(|s| s.phase.clone()).collect();
|
2026-03-20 12:45:24 -04:00
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
// Bail check: if the agent defines a bail script, run it between steps.
|
|
|
|
|
let bail_script = def.bail.as_ref().map(|name| defs::agents_dir().join(name));
|
|
|
|
|
let state_dir_for_bail = state_dir.clone();
|
|
|
|
|
let bail_fn = move |step_idx: usize| -> Result<(), String> {
|
|
|
|
|
if let Some(ref script) = bail_script {
|
|
|
|
|
let status = std::process::Command::new(script)
|
|
|
|
|
.current_dir(&state_dir_for_bail)
|
|
|
|
|
.status()
|
|
|
|
|
.map_err(|e| format!("bail script {:?} failed: {}", script, e))?;
|
|
|
|
|
if !status.success() {
|
|
|
|
|
return Err(format!("bailed at step {}: {:?} exited {}",
|
|
|
|
|
step_idx + 1, script.file_name().unwrap_or_default(),
|
|
|
|
|
status.code().unwrap_or(-1)));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
};
|
2026-03-26 15:58:59 -04:00
|
|
|
|
2026-04-07 00:57:35 -04:00
|
|
|
let output = call_api_with_tools_sync(
|
2026-04-04 17:33:36 -04:00
|
|
|
agent_name, &prompts, &step_phases, def.temperature, def.priority,
|
2026-04-07 01:23:22 -04:00
|
|
|
&effective_tools, Some(&bail_fn))?;
|
2026-03-20 12:29:32 -04:00
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
Ok(AgentResult {
|
|
|
|
|
output,
|
|
|
|
|
node_keys: agent_batch.node_keys,
|
|
|
|
|
state_dir,
|
|
|
|
|
})
|
2026-03-26 15:58:59 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-07 00:57:35 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
2026-04-07 01:07:04 -04:00
|
|
|
// Compatibility wrappers — delegate to AutoAgent
|
2026-04-07 00:57:35 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
/// Run agent prompts through the API with tool support.
|
2026-04-07 01:07:04 -04:00
|
|
|
/// Convenience wrapper around AutoAgent for existing callers.
|
2026-04-07 00:57:35 -04:00
|
|
|
pub async fn call_api_with_tools(
|
|
|
|
|
agent: &str,
|
|
|
|
|
prompts: &[String],
|
|
|
|
|
phases: &[String],
|
|
|
|
|
temperature: Option<f32>,
|
|
|
|
|
priority: i32,
|
|
|
|
|
tools: &[agent_tools::Tool],
|
|
|
|
|
bail_fn: Option<&(dyn Fn(usize) -> Result<(), String> + Sync)>,
|
|
|
|
|
) -> Result<String, String> {
|
2026-04-07 01:07:04 -04:00
|
|
|
let steps: Vec<AutoStep> = prompts.iter().zip(
|
|
|
|
|
phases.iter().map(String::as_str)
|
|
|
|
|
.chain(std::iter::repeat(""))
|
|
|
|
|
).map(|(prompt, phase)| AutoStep {
|
|
|
|
|
prompt: prompt.clone(),
|
|
|
|
|
phase: phase.to_string(),
|
|
|
|
|
}).collect();
|
|
|
|
|
|
|
|
|
|
let mut auto = AutoAgent::new(
|
|
|
|
|
agent.to_string(),
|
|
|
|
|
tools.to_vec(),
|
|
|
|
|
steps,
|
|
|
|
|
temperature.unwrap_or(0.6),
|
|
|
|
|
priority,
|
2026-04-07 01:57:01 -04:00
|
|
|
);
|
2026-04-07 01:23:22 -04:00
|
|
|
auto.run(bail_fn).await
|
2026-04-07 00:57:35 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-07 01:07:04 -04:00
|
|
|
/// Synchronous wrapper — runs on a dedicated thread with its own
|
|
|
|
|
/// tokio runtime. Safe to call from any context.
|
2026-04-07 00:57:35 -04:00
|
|
|
pub fn call_api_with_tools_sync(
|
|
|
|
|
agent: &str,
|
|
|
|
|
prompts: &[String],
|
|
|
|
|
phases: &[String],
|
|
|
|
|
temperature: Option<f32>,
|
|
|
|
|
priority: i32,
|
|
|
|
|
tools: &[agent_tools::Tool],
|
|
|
|
|
bail_fn: Option<&(dyn Fn(usize) -> Result<(), String> + Sync)>,
|
|
|
|
|
) -> Result<String, String> {
|
|
|
|
|
std::thread::scope(|s| {
|
|
|
|
|
s.spawn(|| {
|
|
|
|
|
let rt = tokio::runtime::Builder::new_current_thread()
|
|
|
|
|
.enable_all()
|
|
|
|
|
.build()
|
|
|
|
|
.map_err(|e| format!("tokio runtime: {}", e))?;
|
|
|
|
|
rt.block_on(
|
2026-04-07 01:23:22 -04:00
|
|
|
call_api_with_tools(agent, prompts, phases, temperature, priority, tools, bail_fn)
|
2026-04-07 00:57:35 -04:00
|
|
|
)
|
|
|
|
|
}).join().unwrap()
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-04 17:33:36 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
2026-04-04 17:47:49 -04:00
|
|
|
// Process management — PID tracking and subprocess spawning
|
2026-04-04 17:33:36 -04:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
2026-03-26 15:58:59 -04:00
|
|
|
/// Check for live agent processes in a state dir. Returns (phase, pid) pairs.
|
|
|
|
|
/// Cleans up stale pid files and kills timed-out processes.
|
|
|
|
|
pub fn scan_pid_files(state_dir: &std::path::Path, timeout_secs: u64) -> Vec<(String, u32)> {
|
|
|
|
|
let mut live = Vec::new();
|
|
|
|
|
let Ok(entries) = fs::read_dir(state_dir) else { return live };
|
|
|
|
|
for entry in entries.flatten() {
|
|
|
|
|
let name = entry.file_name();
|
|
|
|
|
let name_str = name.to_string_lossy();
|
2026-04-04 17:33:36 -04:00
|
|
|
let Some(pid_str) = name_str.strip_prefix("pid-") else { continue };
|
|
|
|
|
let Ok(pid) = pid_str.parse::<u32>() else { continue };
|
2026-03-26 15:58:59 -04:00
|
|
|
|
|
|
|
|
if unsafe { libc::kill(pid as i32, 0) } != 0 {
|
|
|
|
|
fs::remove_file(entry.path()).ok();
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if timeout_secs > 0 {
|
|
|
|
|
if let Ok(meta) = entry.metadata() {
|
|
|
|
|
if let Ok(modified) = meta.modified() {
|
|
|
|
|
if modified.elapsed().unwrap_or_default().as_secs() > timeout_secs {
|
|
|
|
|
unsafe { libc::kill(pid as i32, libc::SIGTERM); }
|
|
|
|
|
fs::remove_file(entry.path()).ok();
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let phase = fs::read_to_string(entry.path())
|
|
|
|
|
.unwrap_or_default()
|
|
|
|
|
.trim().to_string();
|
|
|
|
|
live.push((phase, pid));
|
|
|
|
|
}
|
|
|
|
|
live
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-02 01:04:54 -04:00
|
|
|
pub struct SpawnResult {
|
2026-04-02 01:20:03 -04:00
|
|
|
pub child: std::process::Child,
|
2026-04-02 01:04:54 -04:00
|
|
|
pub log_path: PathBuf,
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-26 15:58:59 -04:00
|
|
|
pub fn spawn_agent(
|
|
|
|
|
agent_name: &str,
|
|
|
|
|
state_dir: &std::path::Path,
|
|
|
|
|
session_id: &str,
|
2026-04-02 01:04:54 -04:00
|
|
|
) -> Option<SpawnResult> {
|
2026-04-04 17:25:10 -04:00
|
|
|
let def = defs::get_def(agent_name)?;
|
2026-03-26 15:58:59 -04:00
|
|
|
let first_phase = def.steps.first()
|
|
|
|
|
.map(|s| s.phase.as_str())
|
|
|
|
|
.unwrap_or("step-0");
|
|
|
|
|
|
2026-03-28 20:39:20 -04:00
|
|
|
let log_dir = dirs::home_dir().unwrap_or_default()
|
|
|
|
|
.join(format!(".consciousness/logs/{}", agent_name));
|
2026-03-26 15:58:59 -04:00
|
|
|
fs::create_dir_all(&log_dir).ok();
|
2026-04-02 01:04:54 -04:00
|
|
|
let log_path = log_dir.join(format!("{}.log", store::compact_timestamp()));
|
|
|
|
|
let agent_log = fs::File::create(&log_path)
|
2026-03-26 15:58:59 -04:00
|
|
|
.unwrap_or_else(|_| fs::File::create("/dev/null").unwrap());
|
|
|
|
|
|
|
|
|
|
let child = std::process::Command::new("poc-memory")
|
|
|
|
|
.args(["agent", "run", agent_name, "--count", "1", "--local",
|
|
|
|
|
"--state-dir", &state_dir.to_string_lossy()])
|
|
|
|
|
.env("POC_SESSION_ID", session_id)
|
|
|
|
|
.stdout(agent_log.try_clone().unwrap_or_else(|_| fs::File::create("/dev/null").unwrap()))
|
|
|
|
|
.stderr(agent_log)
|
|
|
|
|
.spawn()
|
|
|
|
|
.ok()?;
|
|
|
|
|
|
|
|
|
|
let pid = child.id();
|
|
|
|
|
let pid_path = state_dir.join(format!("pid-{}", pid));
|
|
|
|
|
fs::write(&pid_path, first_phase).ok();
|
2026-04-02 01:20:03 -04:00
|
|
|
Some(SpawnResult { child, log_path })
|
2026-03-17 00:24:24 -04:00
|
|
|
}
|