use crate::app::{AppState, Shared};
use eclipse_core::approvals::Decision;
use eclipse_core::loops::{self, Owner, State, Status};
use eclipse_core::runtime::{AgentEvent, RunOptions};
use eclipse_core::tools::Approver;
use eclipse_core::{approvals::Pending, cancel::Cancel, Agent};
use std::path::PathBuf;
use std::sync::Arc;
const POLL: std::time::Duration = std::time::Duration::from_secs(5);
pub fn spawn(st: Shared) {
tokio::spawn(async move {
loop {
sweep(&st).await;
tokio::time::sleep(POLL).await;
}
});
}
async fn sweep(st: &Shared) {
sweep_goals(st).await;
sweep_loops(st).await;
}
async fn sweep_goals(st: &Shared) {
let live = match st.store.live_goals() {
Ok(live) => live,
Err(_) => return,
};
for goal in live {
if !goal.wants_turn() {
continue;
}
let session = goal.session.clone();
if !st.claim_tick(&session) {
continue;
}
let st = st.clone();
let prompt = goal.continuation_prompt();
tokio::spawn(async move {
goal_turn(st.clone(), &session, &prompt).await;
st.release_tick(&session);
});
}
}
async fn goal_turn(st: Shared, session: &str, prompt: &str) {
let Some(agent) = st.agent.clone() else {
return;
};
let _ = run_turn(&st, &agent, session, prompt).await;
}
async fn sweep_loops(st: &Shared) {
let Some(root) = st.cron_root.clone() else {
return;
};
let now = eclipse_core::session::now_ms() as i64;
let found = match loops::all(&root) {
Ok(found) => found,
Err(_) => return,
};
for state in found {
if state.owner != Owner::Gateway || state.status != Status::Running || !state.due(now) {
continue;
}
let session = state.session.clone();
if !st.claim_tick(&session) {
continue;
}
let st = st.clone();
let root = root.clone();
tokio::spawn(async move {
tick(st.clone(), root, state, now).await;
st.release_tick(&session);
});
}
}
async fn tick(st: Shared, root: PathBuf, mut state: State, now: i64) {
let Some(agent) = st.agent.clone() else {
return;
};
let session = state.session.clone();
match agent.loop_tick_begin(&root, &mut state, now) {
Ok(true) => {}
Ok(false) => {
return;
}
Err(_) => return,
}
let prompt = state.prompt.clone();
let result = run_turn(&st, &agent, &session, &prompt).await;
let _ = agent.loop_tick_end(&root, &mut state, now, result).await;
}
async fn run_turn(
st: &Shared,
agent: &Arc<Agent>,
session: &str,
prompt: &str,
) -> Result<Option<String>, String> {
let Some(_permit) = st.try_chat_slot() else {
return Err("every chat slot was busy".to_string());
};
let cancel = Cancel::new();
let sink = |_: AgentEvent| {};
let opts = RunOptions {
resume: false,
title: false,
..RunOptions::default()
};
match agent
.run_cancellable_with(Some(session), prompt, &Unattended, &sink, &cancel, &opts)
.await
{
Ok(_) => Ok(last_reply(agent, session)),
Err(eclipse_core::Error::Cancelled) => Err("the tick was cancelled".to_string()),
Err(e) => Err(format!("{e:#}")),
}
}
fn last_reply(agent: &Agent, session: &str) -> Option<String> {
let records = agent.store().load_records(session).ok()?;
records.iter().rev().find_map(|record| {
let text = record.message.content.clone().unwrap_or_default();
(record.message.role == eclipse_core::message::Role::Assistant && !text.trim().is_empty())
.then_some(text)
})
}
struct Unattended;
#[async_trait::async_trait]
impl Approver for Unattended {
async fn decide(&self, _call: &Pending) -> Decision {
Decision::Deny(
"a `/loop` tick in the gateway runs with nobody watching, so this call is refused: \
approvals need a person, and a person is at the terminal, not on a timer"
.to_string(),
)
}
}
pub fn manage(st: &AppState, session: Option<&str>, arg: &str) -> Result<String, String> {
let root = st
.cron_root
.clone()
.ok_or_else(|| "this dashboard was started without an install root".to_string())?;
let Some(id) = session.filter(|s| !s.is_empty()) else {
return Ok(
"no session yet — send a message first, then `/loop 2m <prompt>` starts a loop in it"
.to_string(),
);
};
let now = eclipse_core::session::now_ms() as i64;
loops::manage(&root, id, arg, Owner::Gateway, now).map_err(|e| format!("{e:#}"))
}