system agents: generalise the scheduler and add the two memory lints
Nightly Build / build (push) Successful in 7m14s
Nightly Build / build (push) Successful in 7m14s
Memory is kept as a maintained wiki, and a wiki nobody prunes rots. This adds
the scheduled maintenance pass, and generalises the machinery TIC had grown so
that a background agent is a trait impl rather than a loop of its own.
Two lint agents, not one. The private pass runs per user over `user-memory/`
and reports to them; the shared pass runs once over `shared-memory/`, where the
interesting defect is different — a note failing the table rule, i.e. private
business written where every member can read it. It names the note and the
category without repeating the content, since restating it spreads the very
thing being flagged. Both share `agents/common/memory-lint.md`.
Both are read-only, and that is enforced twice: the prompt says report-never-
repair, and `shared-memory/*` writes are already `@fs_write require`, so an
agent that tried to fix something would raise an approval card from an
unattended pass, which is auto-denied. Read-only is the only design that works
here, not merely the safe one.
One scheduler for cadences three orders of magnitude apart. TIC runs every few
minutes, a lint weekly — the case that tempts a second loop. It stays one
because the wake-up decides nothing: `base_tick` picks only how often to look,
and whether an agent runs for a user is `is_due` against persisted state.
Due-ness moves out of the run log into a new owner table, `system_agent_state`.
The two answer different questions: the run log skips idle ticks so it stays a
history rather than a heartbeat, while scheduling needs every attempt. Reading
due-ness off the log would re-run an idle agent on every tick and never bring a
weekly one due once its last productive run aged out. Persisting it is also
what makes a long interval survive a restart — an in-memory deadline is fine at
TIC's scale, but a weekly agent on a box rebooted every few days would have it
re-armed before it ever fired.
The shared store belongs to nobody, so `AgentScope::Instance` runs that pass as
the first unlocked admin. An ownerless run would write its trace into system.db,
which the runs endpoint shows to nobody by design, and its notify() would have
no recipient; attributing it to a user keeps the whole per-user surface working
unchanged.
Settings move to where the run log is. `ConfigSet` gains `owner`, so placement
is data on the set rather than a page that knows set names; the System agents
page grows one tab per agent holding its description, its settings (admin only)
and its runs — "why did this do nothing last night?" is half a schedule
question and half a log question. The form is shared with the Config page, and
writes still go through PUT /api/config/{key}.
Fixes an authorization gap found on the way: neither /api/config handler took
the caller into account, so any authenticated session could read and write
instance-wide config. The sidebar hiding the page is presentation, not access
control. Both are now admin-gated.
This commit is contained in:
@@ -43,10 +43,30 @@ pub struct ConfigProperty {
|
||||
}
|
||||
|
||||
/// A named group of related [`ConfigProperty`] items, shown as a distinct
|
||||
/// section in the Config UI.
|
||||
/// section of whichever page owns it.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ConfigSet {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub properties: Vec<ConfigProperty>,
|
||||
/// Who this set belongs to, and therefore **where it is edited**.
|
||||
///
|
||||
/// `None` is the general Config page. `Some(id)` hands the set to the
|
||||
/// surface that owns `id` — today the System agents page, which shows an
|
||||
/// agent's settings next to that same agent's run history, because "why did
|
||||
/// it not run" is half a config question and half a log question.
|
||||
///
|
||||
/// Placement is deliberately **data on the set** rather than a filter that
|
||||
/// knows set names: a page selects by owner, so a new owned set lands in the
|
||||
/// right place without touching either page.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub owner: Option<String>,
|
||||
}
|
||||
|
||||
impl ConfigSet {
|
||||
/// Hand this set to the surface that owns `owner` (see [`ConfigSet::owner`]).
|
||||
pub fn owned_by(mut self, owner: impl Into<String>) -> Self {
|
||||
self.owner = Some(owner.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ pub fn config_set() -> ConfigSet {
|
||||
default_value: None,
|
||||
},
|
||||
],
|
||||
owner: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ pub mod scratchpad;
|
||||
pub mod shared_folders;
|
||||
pub mod sources;
|
||||
pub mod system_agent_runs;
|
||||
pub mod system_agent_state;
|
||||
pub mod tool_permission_groups;
|
||||
pub mod users;
|
||||
|
||||
@@ -935,6 +936,33 @@ pub async fn create_owner_tables(pool: &SqlitePool) -> Result<()> {
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
// When each system agent last *attempted* a pass for this user — the
|
||||
// scheduler's state, deliberately kept apart from `system_agent_runs`.
|
||||
//
|
||||
// The two answer different questions and conflating them breaks both. The run
|
||||
// log is a history for the human: an idle tick writes nothing there, or it
|
||||
// degenerates into a heartbeat. Scheduling needs the opposite — every attempt,
|
||||
// productive or not — because "is this agent due?" is `now - last_attempt >=
|
||||
// interval`. Reading due-ness off the run log would re-run an idle agent on
|
||||
// every pass, and a weekly agent would never come due at all once its last
|
||||
// productive run aged out.
|
||||
//
|
||||
// Persisting it is what makes a long interval survive a restart. An in-memory
|
||||
// deadline is fine at TIC's scale — a few minutes, re-armed on boot — but a
|
||||
// weekly agent on a machine rebooted every few days would have its deadline
|
||||
// reset before it ever fired, and would simply never run.
|
||||
//
|
||||
// Owner table for the same reason as the run log: when an agent last ran for
|
||||
// someone is that person's activity, not the registry's.
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS system_agent_state (
|
||||
agent_id TEXT PRIMARY KEY,
|
||||
last_attempt_at TEXT NOT NULL
|
||||
)",
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS mcp_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! Scheduler state for the system agents: when each one last *attempted* a pass
|
||||
//! for this user.
|
||||
//!
|
||||
//! Deliberately separate from [`super::system_agent_runs`], which is a history
|
||||
//! written for the human and skips idle ticks. Due-ness needs every attempt, so
|
||||
//! it needs its own row — see the table comment in [`super::create_owner_tables`]
|
||||
//! for why conflating the two breaks both.
|
||||
//!
|
||||
//! Owner table, no `user_id` column: the file is the owner (§5.1).
|
||||
|
||||
use anyhow::Result;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
/// When `agent_id` last attempted a pass here, as a SQLite `datetime('now')`
|
||||
/// string, or `None` if it never has.
|
||||
pub async fn last_attempt_at(pool: &SqlitePool, agent_id: &str) -> Result<Option<String>> {
|
||||
let at = sqlx::query_scalar::<_, String>(
|
||||
"SELECT last_attempt_at FROM system_agent_state WHERE agent_id = ?",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// Record an attempt as of now. Called whether or not the pass had anything to
|
||||
/// do — that is the whole point of this table.
|
||||
pub async fn mark_attempt(pool: &SqlitePool, agent_id: &str) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO system_agent_state (agent_id, last_attempt_at)
|
||||
VALUES (?, datetime('now'))
|
||||
ON CONFLICT(agent_id) DO UPDATE SET last_attempt_at = datetime('now')",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seconds since the last attempt, or `None` when there has never been one
|
||||
/// (which every caller must read as "due now").
|
||||
pub async fn seconds_since_attempt(pool: &SqlitePool, agent_id: &str) -> Result<Option<i64>> {
|
||||
let secs = sqlx::query_scalar::<_, Option<i64>>(
|
||||
"SELECT CAST(strftime('%s', 'now') AS INTEGER)
|
||||
- CAST(strftime('%s', last_attempt_at) AS INTEGER)
|
||||
FROM system_agent_state WHERE agent_id = ?",
|
||||
)
|
||||
.bind(agent_id)
|
||||
.fetch_optional(pool)
|
||||
.await?
|
||||
.flatten();
|
||||
Ok(secs)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
async fn pool() -> SqlitePool {
|
||||
let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
|
||||
crate::db::create_owner_tables(&pool).await.unwrap();
|
||||
pool
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn never_attempted_reads_as_due() {
|
||||
let pool = pool().await;
|
||||
assert!(last_attempt_at(&pool, "tic").await.unwrap().is_none());
|
||||
assert!(seconds_since_attempt(&pool, "tic").await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_attempt_is_recorded_and_then_overwritten() {
|
||||
let pool = pool().await;
|
||||
mark_attempt(&pool, "tic").await.unwrap();
|
||||
let first = last_attempt_at(&pool, "tic").await.unwrap().unwrap();
|
||||
|
||||
// Fresh attempt: still one row for this agent, and the age is small.
|
||||
mark_attempt(&pool, "tic").await.unwrap();
|
||||
assert!(seconds_since_attempt(&pool, "tic").await.unwrap().unwrap() < 5);
|
||||
assert!(!first.is_empty());
|
||||
|
||||
let rows = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM system_agent_state")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1, "mark_attempt must upsert, not accumulate");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agents_do_not_share_a_row() {
|
||||
let pool = pool().await;
|
||||
mark_attempt(&pool, "tic").await.unwrap();
|
||||
assert!(seconds_since_attempt(&pool, "tic").await.unwrap().is_some());
|
||||
assert!(seconds_since_attempt(&pool, "memory-lint").await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -172,6 +172,7 @@ pub fn config_set() -> ConfigSet {
|
||||
default_value: Some("en".into()),
|
||||
},
|
||||
],
|
||||
owner: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ pub mod secrets;
|
||||
pub mod service_manager;
|
||||
pub mod session;
|
||||
pub mod setup;
|
||||
pub mod system_agents;
|
||||
pub mod tic;
|
||||
pub mod tool_catalog;
|
||||
pub mod tool_discovery;
|
||||
|
||||
@@ -63,11 +63,16 @@ impl Runtime {
|
||||
users,
|
||||
sessions,
|
||||
config,
|
||||
config_properties: vec![
|
||||
// Sets with no `owner` render on the general Config page; the owned
|
||||
// ones are claimed by the surface that owns them — today the System
|
||||
// agents page, one tab per agent.
|
||||
config_properties: [
|
||||
crate::i18n::config_set(),
|
||||
crate::tic::config_set(),
|
||||
crate::compactor::config_set(),
|
||||
],
|
||||
]
|
||||
.into_iter()
|
||||
.chain(crate::system_agents::config_sets())
|
||||
.collect(),
|
||||
system_bus,
|
||||
event_bus,
|
||||
global_tx,
|
||||
|
||||
@@ -17,7 +17,7 @@ use tracing::{info, warn};
|
||||
|
||||
use crate::config::{CoreConfig, TicConfig};
|
||||
use crate::elicitation::ElicitationBridge;
|
||||
use crate::tic::{TicManager, TIC_INTERVAL_MINUTES_KEY};
|
||||
use crate::system_agents::{self, AgentRunCtx, AgentScope, SystemAgent};
|
||||
|
||||
use super::bundles::{Conversation, Integrations, Interaction, Tasks};
|
||||
use super::runtime::Runtime;
|
||||
@@ -174,13 +174,23 @@ pub(super) fn spawn_user_lifecycle(skald: &Arc<super::Skald>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Spawns the **system-agent scheduler** — the instance-wide timer that runs the
|
||||
/// background agents nobody asked for (today: TIC).
|
||||
/// Spawns the **system-agent scheduler** — the one instance-wide timer behind
|
||||
/// every background agent nobody asked for (TIC, the two memory lints).
|
||||
///
|
||||
/// One loop, not one per user. Every pass walks the user directory and runs the
|
||||
/// agent for each user **sequentially**: a pass means N container round-trips and
|
||||
/// N LLM calls, and doing them concurrently would spike the box every interval
|
||||
/// for no gain — nobody is waiting on a background tick.
|
||||
/// **One loop for all of them.** The agents differ by three orders of magnitude
|
||||
/// in cadence — TIC every few minutes, a lint every week — which is exactly the
|
||||
/// case that tempts a second loop. It stays one because the wake-up decides
|
||||
/// nothing: [`base_tick`] only picks how often to *look*, and whether an agent
|
||||
/// actually runs for a given user is [`system_agents::is_due`] against state in
|
||||
/// that user's own database. Adding an agent therefore adds a registry entry,
|
||||
/// never a task.
|
||||
///
|
||||
/// **Due-ness is persisted, not counted from boot.** An in-memory deadline is
|
||||
/// fine at TIC's scale but silently breaks a weekly agent: every restart re-arms
|
||||
/// it, so on a machine rebooted every few days it would never fire once. Reading
|
||||
/// the last attempt from `system_agent_state` makes a long interval survive
|
||||
/// restarts, and has the pleasant side effect that a user who logs in after a
|
||||
/// long absence is picked up on the next pass rather than a week later.
|
||||
///
|
||||
/// A user whose database is still locked is **skipped**, and that is the normal
|
||||
/// case rather than an error: the pool is the unlock token (§9), so a user who
|
||||
@@ -197,19 +207,24 @@ pub(super) fn spawn_system_agents(skald: &Arc<super::Skald>, tic_config: TicConf
|
||||
let shutdown = skald.rt.shutdown_token.clone();
|
||||
let mut sys_rx = skald.rt.system_bus.subscribe();
|
||||
|
||||
let tic = TicManager::new(
|
||||
// Adding an agent is one line in `system_agents::registry` plus a
|
||||
// `SystemAgent` impl — no loop of its own, which is the whole point: a second
|
||||
// scheduler would be a fourth global bus in disguise.
|
||||
let agents = system_agents::registry(
|
||||
tic_config,
|
||||
Arc::clone(&skald.rt.config),
|
||||
Arc::clone(&skald.rt.db),
|
||||
);
|
||||
|
||||
// Interval keys, so a change in the UI cuts the current wait short for
|
||||
// whichever agent it belongs to.
|
||||
let interval_keys: Vec<&'static str> = agents.iter().map(|a| a.interval_key()).collect();
|
||||
|
||||
skald.rt.supervisor.spawn("system-agents", async move {
|
||||
info!("system-agents: scheduler started");
|
||||
info!(agents = agents.len(), "system-agents: scheduler started");
|
||||
|
||||
'outer: loop {
|
||||
// Re-read the interval each pass so a Settings change lands without a
|
||||
// restart; a live change also cuts the current wait short.
|
||||
let wait = Duration::from_secs(tic.interval_secs().await);
|
||||
let wait = base_tick(&agents).await;
|
||||
let deadline = tokio::time::sleep(wait);
|
||||
tokio::pin!(deadline);
|
||||
|
||||
@@ -219,9 +234,9 @@ pub(super) fn spawn_system_agents(skald: &Arc<super::Skald>, tic_config: TicConf
|
||||
_ = &mut deadline => break,
|
||||
ev = sys_rx.recv() => match ev {
|
||||
Ok(SystemEvent::ConfigKeyUpdated { key, .. })
|
||||
if key == TIC_INTERVAL_MINUTES_KEY =>
|
||||
if interval_keys.contains(&key.as_str()) =>
|
||||
{
|
||||
info!("system-agents: interval changed, rescheduling");
|
||||
info!(%key, "system-agents: interval changed, rescheduling");
|
||||
continue 'outer;
|
||||
}
|
||||
Err(RecvError::Closed) => break 'outer,
|
||||
@@ -231,49 +246,154 @@ pub(super) fn spawn_system_agents(skald: &Arc<super::Skald>, tic_config: TicConf
|
||||
}
|
||||
|
||||
let Some(skald) = weak.upgrade() else { break };
|
||||
tic_pass(&skald, &tic).await;
|
||||
agents_pass(&skald, &agents).await;
|
||||
}
|
||||
|
||||
info!("system-agents: scheduler stopped");
|
||||
});
|
||||
}
|
||||
|
||||
/// One TIC pass over the whole directory, one user at a time.
|
||||
async fn tic_pass(skald: &Arc<super::Skald>, tic: &Arc<TicManager>) {
|
||||
if !tic.is_enabled().await {
|
||||
return;
|
||||
}
|
||||
/// How long to sleep between passes: the shortest interval any enabled agent
|
||||
/// asks for, clamped.
|
||||
///
|
||||
/// The wake-up itself decides nothing — every agent is gated per user by
|
||||
/// [`system_agents::is_due`] against persisted state — so this only has to be
|
||||
/// fine-grained enough not to delay the most impatient agent, and coarse enough
|
||||
/// not to spin. The floor keeps a misconfigured one-minute interval from turning
|
||||
/// into a busy loop; the ceiling keeps a box that runs only weekly agents from
|
||||
/// sleeping so long that a freshly changed setting takes hours to be noticed.
|
||||
async fn base_tick(agents: &[Arc<dyn SystemAgent>]) -> Duration {
|
||||
const FLOOR_SECS: u64 = 60;
|
||||
const CEIL_SECS: u64 = 15 * 60;
|
||||
|
||||
let mut shortest = CEIL_SECS;
|
||||
for agent in agents {
|
||||
if agent.is_enabled().await {
|
||||
shortest = shortest.min(agent.interval_secs().await);
|
||||
}
|
||||
}
|
||||
Duration::from_secs(shortest.clamp(FLOOR_SECS, CEIL_SECS))
|
||||
}
|
||||
|
||||
/// One pass over every agent, sequentially.
|
||||
///
|
||||
/// Sequential on purpose, and at two levels: agents one after another, and
|
||||
/// within a per-user agent, users one after another. A pass is N container
|
||||
/// round-trips and N LLM calls, nobody is waiting on it, and running them
|
||||
/// concurrently would only spike the box every interval. It is also what makes
|
||||
/// the `running` row of a crashed pass safe to sweep — no other run of the same
|
||||
/// agent can be live.
|
||||
async fn agents_pass(skald: &Arc<super::Skald>, agents: &[Arc<dyn SystemAgent>]) {
|
||||
for agent in agents {
|
||||
if skald.rt.shutdown_token.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
// Re-read per pass, so disabling an agent takes effect without a restart.
|
||||
if !agent.is_enabled().await {
|
||||
continue;
|
||||
}
|
||||
match agent.scope() {
|
||||
AgentScope::PerUser => per_user_pass(skald, agent.as_ref()).await,
|
||||
AgentScope::Instance => instance_pass(skald, agent.as_ref()).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `agent` for each active user whose database is unlocked and who is due.
|
||||
async fn per_user_pass(skald: &Arc<super::Skald>, agent: &dyn SystemAgent) {
|
||||
let users = match skald.users().list().await {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
warn!(error = %e, "system-agents: cannot list users, skipping this pass");
|
||||
warn!(agent = agent.id(), error = %e,
|
||||
"system-agents: cannot list users, skipping this pass");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for user in users.into_iter().filter(|u| u.active) {
|
||||
if skald.rt.shutdown_token.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
|
||||
if !skald.users().is_unlocked(&user.id) {
|
||||
info!(
|
||||
user = %user.id, username = %user.username,
|
||||
"TIC: skipped — the user's database is still encrypted (not logged in since the last restart)",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Unlocked, so this resolves (and is normally already live from their login).
|
||||
let Some(ctx) = skald.user_context(&user.id).await else {
|
||||
warn!(user = %user.id, "TIC: skipped — could not resolve the user's runtime");
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Err(e) = tic.run_for(&user.id, &ctx.pool, &ctx.sessions, &ctx.chat_hub).await {
|
||||
// One user's failure must not end the pass for everyone after them.
|
||||
warn!(user = %user.id, error = %e, "TIC: tick failed");
|
||||
return;
|
||||
}
|
||||
run_one(skald, agent, &user.id, &user.username).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an instance-scoped `agent` once, as the admin.
|
||||
///
|
||||
/// The first active admin who is unlocked wins; ordering is `users::list`'s, so
|
||||
/// the choice is stable across passes rather than racing between two admins. If
|
||||
/// none has logged in since the last restart the pass is skipped exactly like a
|
||||
/// locked user's — it settles at the next login.
|
||||
async fn instance_pass(skald: &Arc<super::Skald>, agent: &dyn SystemAgent) {
|
||||
let users = match skald.users().list().await {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
warn!(agent = agent.id(), error = %e,
|
||||
"system-agents: cannot list users, skipping this pass");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let admins = users
|
||||
.into_iter()
|
||||
.filter(|u| u.active && u.role_id == crate::db::roles::ADMIN_ROLE_ID);
|
||||
|
||||
for admin in admins {
|
||||
if skald.users().is_unlocked(&admin.id) {
|
||||
run_one(skald, agent, &admin.id, &admin.username).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
agent = agent.id(),
|
||||
"system-agents: skipped — no admin has logged in since the last restart, \
|
||||
so the instance-wide pass has no runtime to run in",
|
||||
);
|
||||
}
|
||||
|
||||
/// The common tail: skip a locked user, resolve their runtime, check due-ness,
|
||||
/// run and record.
|
||||
async fn run_one(
|
||||
skald: &Arc<super::Skald>,
|
||||
agent: &dyn SystemAgent,
|
||||
user_id: &str,
|
||||
username: &str,
|
||||
) {
|
||||
// A locked user is the normal case, not an error: the pool is the unlock
|
||||
// token (§9), so someone who has not logged in since the last restart has
|
||||
// nothing readable — and no place to record the skip, since the only file
|
||||
// that could hold it is the one we cannot open. Hence a log line and nothing
|
||||
// else; their next login picks it up.
|
||||
if !skald.users().is_unlocked(user_id) {
|
||||
info!(
|
||||
agent = agent.id(), user = %user_id, %username,
|
||||
"system-agents: skipped — the user's database is still encrypted \
|
||||
(not logged in since the last restart)",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Unlocked, so this resolves (and is normally already live from their login).
|
||||
let Some(ctx) = skald.user_context(user_id).await else {
|
||||
warn!(agent = agent.id(), user = %user_id,
|
||||
"system-agents: skipped — could not resolve the user's runtime");
|
||||
return;
|
||||
};
|
||||
|
||||
if !system_agents::is_due(agent, &ctx.pool).await {
|
||||
return;
|
||||
}
|
||||
|
||||
let run_ctx = AgentRunCtx {
|
||||
user_id,
|
||||
pool: &ctx.pool,
|
||||
sessions: &ctx.sessions,
|
||||
hub: &ctx.chat_hub,
|
||||
};
|
||||
|
||||
// One user's failure must not end the pass for everyone after them.
|
||||
if let Err(e) = system_agents::run_and_record(agent, &run_ctx).await {
|
||||
warn!(agent = agent.id(), user = %user_id, error = %e, "system-agents: pass failed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The memory-lint agents — the weekly health pass over the two memory stores.
|
||||
//!
|
||||
//! Memory is a wiki, not a scrapbook (`agents/common/memory-wiki.md`), and a wiki
|
||||
//! that nobody maintains rots: contradictions stay pending, dates go by, notes
|
||||
//! lose their last inbound link, the same fact ends up written twice. The Lint
|
||||
//! habit in the Schema covers "when you notice drift"; these agents are what
|
||||
//! makes it happen when nobody notices.
|
||||
//!
|
||||
//! **There are two of them, and they are not the same job.** The private lint
|
||||
//! runs for each user over their own store — their data, their notify, their run
|
||||
//! log. The shared lint runs once over the group store, where the interesting
|
||||
//! defect is different: a note that fails the table rule, i.e. one person's
|
||||
//! private business sitting somewhere every member can read. They share the
|
||||
//! wiki Schema through `agents/common/`, and diverge in their `AGENT.md`.
|
||||
//!
|
||||
//! **Both are read-only, and that is enforced twice.** The prompt says report,
|
||||
//! never repair; and the approval rules already gate `shared-memory/*` writes as
|
||||
//! `require` — so an agent that tried to fix something would raise an approval
|
||||
//! card from an unattended pass, which [`super::run_ephemeral_turn`] auto-denies.
|
||||
//! Read-only is therefore not a convention here, it is the only thing that works.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use core_api::{ConfigProperty, ConfigSet, PropertyType};
|
||||
|
||||
use crate::config_store::GlobalConfigManager;
|
||||
use crate::db::memory_docs;
|
||||
use crate::tools::fs::{SHARED_MEMORY_ROOT, USER_MEMORY_ROOT};
|
||||
|
||||
use super::{
|
||||
AgentOutcome, AgentRunCtx, AgentScope, SystemAgent, configured_run_context,
|
||||
enabled_from_config, enabled_property, interval_from_config, run_ephemeral_turn,
|
||||
security_group_property,
|
||||
};
|
||||
|
||||
/// The chat `source` a lint pass runs under. Distinct from the user-facing
|
||||
/// sources so a pass never lands in a conversation somebody is reading.
|
||||
const LINT_SOURCE: &str = "memory-lint";
|
||||
|
||||
const DAY_SECS: u64 = 24 * 60 * 60;
|
||||
/// A week, the default for both passes: long enough that a report is worth
|
||||
/// reading, short enough that a contradiction does not sit for a month.
|
||||
const DEFAULT_INTERVAL_SECS: u64 = 7 * DAY_SECS;
|
||||
|
||||
pub const PRIVATE_AGENT: &str = "memory-lint-private";
|
||||
pub const SHARED_AGENT: &str = "memory-lint-shared";
|
||||
|
||||
pub const PRIVATE_ENABLED_KEY: &str = "memory_lint_private.enabled";
|
||||
pub const PRIVATE_SECURITY_GROUP_KEY: &str = "memory_lint_private.security_group";
|
||||
pub const PRIVATE_INTERVAL_DAYS_KEY: &str = "memory_lint_private.interval_days";
|
||||
|
||||
pub const SHARED_ENABLED_KEY: &str = "memory_lint_shared.enabled";
|
||||
pub const SHARED_SECURITY_GROUP_KEY: &str = "memory_lint_shared.security_group";
|
||||
pub const SHARED_INTERVAL_DAYS_KEY: &str = "memory_lint_shared.interval_days";
|
||||
|
||||
/// The interval property, in **days**.
|
||||
///
|
||||
/// The unit is per-agent on purpose. TIC is configured in minutes because it
|
||||
/// runs in minutes; asking an admin to type `10080` for "weekly" would be a
|
||||
/// worse form of the same field.
|
||||
fn interval_days_property(key: &str, description: &str) -> ConfigProperty {
|
||||
ConfigProperty {
|
||||
key: key.into(),
|
||||
name: "Interval (days)".into(),
|
||||
description: description.into(),
|
||||
property_type: PropertyType::Int,
|
||||
default_value: Some("7".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn private_config_set() -> ConfigSet {
|
||||
ConfigSet {
|
||||
name: "Private memory lint".into(),
|
||||
description: "A periodic health pass over each person's own memory store. For one user at \
|
||||
a time it re-reads their notes and looks for drift: contradictions still \
|
||||
pending, facts whose date has gone by, notes nothing links to, index lines \
|
||||
pointing at nothing, and duplicates worth merging. It reports what it found \
|
||||
as a notification and never edits anything itself. It reads only that \
|
||||
user's private store, and the run is recorded on their own System agents \
|
||||
page; a user who has not logged in since the last restart is skipped, \
|
||||
because their database is still encrypted."
|
||||
.into(),
|
||||
properties: vec![
|
||||
enabled_property(
|
||||
PRIVATE_ENABLED_KEY,
|
||||
"Enable the private memory lint for the whole instance. When disabled, nobody's \
|
||||
private store is checked.",
|
||||
),
|
||||
security_group_property(PRIVATE_SECURITY_GROUP_KEY),
|
||||
interval_days_property(
|
||||
PRIVATE_INTERVAL_DAYS_KEY,
|
||||
"How long between passes for each user. Counted per person from their own last \
|
||||
pass, and it survives a restart, so a long interval is not reset by rebooting \
|
||||
the machine.",
|
||||
),
|
||||
],
|
||||
owner: Some(PRIVATE_AGENT.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shared_config_set() -> ConfigSet {
|
||||
ConfigSet {
|
||||
name: "Shared memory lint".into(),
|
||||
description: "A periodic health pass over the group's shared memory. It looks for the \
|
||||
same drift as the private pass, plus the defect that only exists here: a \
|
||||
note that fails the table rule — one person's private business sitting \
|
||||
where every member can read it. It reports and never edits. The shared \
|
||||
store belongs to nobody, so the pass runs as the admin and its report goes \
|
||||
to them; it needs an admin who has logged in since the last restart."
|
||||
.into(),
|
||||
properties: vec![
|
||||
enabled_property(
|
||||
SHARED_ENABLED_KEY,
|
||||
"Enable the shared memory lint for the whole instance.",
|
||||
),
|
||||
security_group_property(SHARED_SECURITY_GROUP_KEY),
|
||||
interval_days_property(
|
||||
SHARED_INTERVAL_DAYS_KEY,
|
||||
"How long between passes over the shared store. It survives a restart, so a long \
|
||||
interval is not reset by rebooting the machine.",
|
||||
),
|
||||
],
|
||||
owner: Some(SHARED_AGENT.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared by both agents: everything that differs is a field.
|
||||
pub struct MemoryLintAgent {
|
||||
id: &'static str,
|
||||
scope: AgentScope,
|
||||
/// The store this pass reads: `user-memory` or `shared-memory`.
|
||||
root: &'static str,
|
||||
enabled_key: &'static str,
|
||||
group_key: &'static str,
|
||||
interval_key: &'static str,
|
||||
config_set: fn() -> ConfigSet,
|
||||
config_store: Arc<GlobalConfigManager>,
|
||||
/// `system.db` — the registry, read to reconcile the security group against
|
||||
/// the user's role, and (for the shared pass) the store itself.
|
||||
registry_pool: Arc<SqlitePool>,
|
||||
}
|
||||
|
||||
impl MemoryLintAgent {
|
||||
/// The per-user pass over `user-memory/`.
|
||||
pub fn private(
|
||||
config_store: Arc<GlobalConfigManager>,
|
||||
registry_pool: Arc<SqlitePool>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
id: PRIVATE_AGENT,
|
||||
scope: AgentScope::PerUser,
|
||||
root: USER_MEMORY_ROOT,
|
||||
enabled_key: PRIVATE_ENABLED_KEY,
|
||||
group_key: PRIVATE_SECURITY_GROUP_KEY,
|
||||
interval_key: PRIVATE_INTERVAL_DAYS_KEY,
|
||||
config_set: private_config_set,
|
||||
config_store,
|
||||
registry_pool,
|
||||
})
|
||||
}
|
||||
|
||||
/// The instance pass over `shared-memory/`, run as the admin.
|
||||
pub fn shared(
|
||||
config_store: Arc<GlobalConfigManager>,
|
||||
registry_pool: Arc<SqlitePool>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
id: SHARED_AGENT,
|
||||
scope: AgentScope::Instance,
|
||||
root: SHARED_MEMORY_ROOT,
|
||||
enabled_key: SHARED_ENABLED_KEY,
|
||||
group_key: SHARED_SECURITY_GROUP_KEY,
|
||||
interval_key: SHARED_INTERVAL_DAYS_KEY,
|
||||
config_set: shared_config_set,
|
||||
config_store,
|
||||
registry_pool,
|
||||
})
|
||||
}
|
||||
|
||||
/// Which pool holds the store this agent lints: the caller's own for the
|
||||
/// private pass, `system.db` for the shared one (the same routing
|
||||
/// `classify_memory` gives the fs-tools).
|
||||
fn store_pool<'a>(&'a self, ctx: &'a AgentRunCtx<'_>) -> &'a SqlitePool {
|
||||
match self.scope {
|
||||
AgentScope::PerUser => ctx.pool,
|
||||
AgentScope::Instance => &self.registry_pool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SystemAgent for MemoryLintAgent {
|
||||
fn id(&self) -> &'static str { self.id }
|
||||
|
||||
fn scope(&self) -> AgentScope { self.scope }
|
||||
|
||||
fn config_set(&self) -> ConfigSet { (self.config_set)() }
|
||||
|
||||
fn interval_key(&self) -> &'static str { self.interval_key }
|
||||
|
||||
async fn is_enabled(&self) -> bool {
|
||||
enabled_from_config(&self.config_store, self.enabled_key).await
|
||||
}
|
||||
|
||||
async fn interval_secs(&self) -> u64 {
|
||||
interval_from_config(
|
||||
&self.config_store,
|
||||
self.interval_key,
|
||||
DAY_SECS,
|
||||
DEFAULT_INTERVAL_SECS,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Nothing to lint in an empty store. Worth checking: without it, a member
|
||||
/// who never uses memory would collect a weekly run row and a weekly
|
||||
/// notification saying there was nothing to report.
|
||||
async fn has_work(&self, ctx: &AgentRunCtx<'_>) -> Result<bool> {
|
||||
let notes = memory_docs::list(self.store_pool(ctx), "").await?;
|
||||
Ok(!notes.is_empty())
|
||||
}
|
||||
|
||||
async fn run(&self, ctx: &AgentRunCtx<'_>) -> Result<AgentOutcome> {
|
||||
let notes = memory_docs::list(self.store_pool(ctx), "").await?;
|
||||
let rc = configured_run_context(
|
||||
&self.config_store,
|
||||
&self.registry_pool,
|
||||
self.group_key,
|
||||
ctx.user_id,
|
||||
)
|
||||
.await;
|
||||
|
||||
let (session_id, notified) = run_ephemeral_turn(
|
||||
self.id,
|
||||
LINT_SOURCE,
|
||||
&build_prompt(self.root, notes.len()),
|
||||
rc.as_ref(),
|
||||
"Memory lint",
|
||||
ctx,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(AgentOutcome {
|
||||
session_id: Some(session_id),
|
||||
stats: serde_json::json!({
|
||||
"notes_examined": notes.len(),
|
||||
"notifications_emitted": notified,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The trigger message. Deliberately thin: *how* to lint is the agent's
|
||||
/// `AGENT.md` plus the wiki Schema it includes from `agents/common/`, and
|
||||
/// duplicating any of it here would give us two copies to keep in step.
|
||||
fn build_prompt(root: &str, note_count: usize) -> String {
|
||||
let today = chrono::Utc::now().format("%Y-%m-%d");
|
||||
format!(
|
||||
"[LINT] Scheduled health pass over `{root}/` — {today}\n\
|
||||
The store currently holds {note_count} note(s).\n\n\
|
||||
Read the store, find what has drifted, and report it. Change nothing."
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_prompt_names_the_store_and_forbids_editing() {
|
||||
let p = build_prompt(SHARED_MEMORY_ROOT, 12);
|
||||
assert!(p.contains("shared-memory/"));
|
||||
assert!(p.contains("12 note(s)"));
|
||||
assert!(p.contains("Change nothing."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_agents_do_not_share_config_keys() {
|
||||
let private: Vec<String> = private_config_set()
|
||||
.properties.into_iter().map(|p| p.key).collect();
|
||||
let shared: Vec<String> = shared_config_set()
|
||||
.properties.into_iter().map(|p| p.key).collect();
|
||||
|
||||
// A shared key would make one agent's switch silently move the other's.
|
||||
for key in &private {
|
||||
assert!(!shared.contains(key), "`{key}` is claimed by both lint agents");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
//! System agents — the background agents the instance runs on a user's behalf.
|
||||
//!
|
||||
//! A system agent runs without being asked. TIC was the first, and everything it
|
||||
//! needed turned out to be general: an on/off switch, an interval, a security
|
||||
//! group reconciled against the user's own role, an ephemeral session, and a run
|
||||
//! recorded in the user's own database. This module is that shape, extracted, so
|
||||
//! a second agent is a [`SystemAgent`] impl and nothing else — no timer of its
|
||||
//! own, no bookkeeping of its own, no scheduler of its own.
|
||||
//!
|
||||
//! **The unit of work is one agent for one user.** The instance-wide scheduler
|
||||
//! (`skald::wiring::spawn_system_agents`) decides who and when; an agent decides
|
||||
//! only what. That split is what made TIC per-user correct, and it is why an
|
||||
//! agent never sees the user list.
|
||||
//!
|
||||
//! ## Why the work is split in three
|
||||
//!
|
||||
//! [`run_and_record`] wraps every pass, and the order of its steps is
|
||||
//! load-bearing:
|
||||
//!
|
||||
//! 1. **Mark the attempt** ([`db::system_agent_state`]) — always, before
|
||||
//! anything else, so due-ness advances even for a pass that turns out to have
|
||||
//! nothing to do. An agent that only recorded productive runs would be asked
|
||||
//! again on every tick.
|
||||
//! 2. **Ask [`SystemAgent::has_work`]** — a cheap look before any row is opened.
|
||||
//! `false` writes nothing at all: an idle tick must not leave a trace, or the
|
||||
//! run log stops being a history and becomes a heartbeat.
|
||||
//! 3. **Open the run row, then work.** The `start`/`finish` split means a crash
|
||||
//! mid-pass leaves a visible `running` row, swept to `failed` by the next
|
||||
//! `start` for that agent — safe only because the scheduler is sequential and
|
||||
//! single-instance.
|
||||
|
||||
pub mod memory_lint;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use sqlx::SqlitePool;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use core_api::interface_tool::{InterfaceTool, ToolFuture};
|
||||
use core_api::{ConfigProperty, ConfigSet, PropertyType};
|
||||
|
||||
use crate::chat_hub::ChatHub;
|
||||
use crate::config_store::GlobalConfigManager;
|
||||
use crate::db::{system_agent_runs, system_agent_state};
|
||||
use crate::run_context::{self, RunContext};
|
||||
use crate::session::manager::ChatSessionManager;
|
||||
|
||||
/// Who a pass runs for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AgentScope {
|
||||
/// One pass per user, over that user's own runtime. The default shape: the
|
||||
/// data is theirs, the notification is theirs, the trace is theirs.
|
||||
PerUser,
|
||||
/// One pass for the whole instance, run inside the admin's runtime.
|
||||
///
|
||||
/// For work over something that has **no owner** — the shared memory store
|
||||
/// being the case that forced this variant. Such a pass still has to run
|
||||
/// *somewhere*: an ownerless run would write its trace into `system.db`,
|
||||
/// which `GET /api/system-agents/runs` shows to nobody (scoped on the
|
||||
/// caller's own pool, by design), and its `notify()` would have no
|
||||
/// recipient. Attributing it to the admin keeps the whole per-user surface
|
||||
/// working unchanged, at the price of needing an admin who has logged in
|
||||
/// since the last restart.
|
||||
Instance,
|
||||
}
|
||||
|
||||
/// What one pass did, for the run log.
|
||||
pub struct AgentOutcome {
|
||||
/// The ephemeral session the pass ran in, so the UI can link to it.
|
||||
pub session_id: Option<i64>,
|
||||
/// The agent's own counters. Never the contents of what it read.
|
||||
pub stats: serde_json::Value,
|
||||
}
|
||||
|
||||
/// One user's runtime, unpacked from their `UserContext` by the scheduler.
|
||||
pub struct AgentRunCtx<'a> {
|
||||
pub user_id: &'a str,
|
||||
/// The user's own (unlocked) database.
|
||||
pub pool: &'a SqlitePool,
|
||||
pub sessions: &'a Arc<ChatSessionManager>,
|
||||
pub hub: &'a Arc<ChatHub>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait SystemAgent: Send + Sync {
|
||||
/// Directory name under `agents/`, and the `agent_id` of its rows.
|
||||
fn id(&self) -> &'static str;
|
||||
|
||||
fn scope(&self) -> AgentScope;
|
||||
|
||||
/// The settings shown on this agent's tab of the System agents page. Must be
|
||||
/// `owned_by(self.id())`, or it lands on the general Config page instead.
|
||||
fn config_set(&self) -> ConfigSet;
|
||||
|
||||
/// The config key holding the interval. The scheduler watches it so a change
|
||||
/// in the UI reschedules without a restart.
|
||||
fn interval_key(&self) -> &'static str;
|
||||
|
||||
/// Instance-wide on/off switch, re-read every pass.
|
||||
async fn is_enabled(&self) -> bool;
|
||||
|
||||
/// How long between passes **for one user**, in seconds.
|
||||
async fn interval_secs(&self) -> u64;
|
||||
|
||||
/// Cheap look at whether this pass would do anything, before a run row is
|
||||
/// opened. `false` means "nothing to do" and leaves no trace behind.
|
||||
async fn has_work(&self, ctx: &AgentRunCtx<'_>) -> Result<bool>;
|
||||
|
||||
/// The pass itself. The run row is already open; returning `Err` closes it
|
||||
/// as `failed` with the message.
|
||||
async fn run(&self, ctx: &AgentRunCtx<'_>) -> Result<AgentOutcome>;
|
||||
}
|
||||
|
||||
/// Every system agent the instance runs, in pass order.
|
||||
///
|
||||
/// The **one** place the set is enumerated. The scheduler takes this list, and
|
||||
/// [`config_sets`] derives the settings surface from it, so an agent cannot exist
|
||||
/// in one and be missing from the other — the failure that would otherwise look
|
||||
/// like "the agent runs but has no settings" or "the settings page edits keys
|
||||
/// nothing reads".
|
||||
pub fn registry(
|
||||
tic_config: crate::config::TicConfig,
|
||||
config_store: Arc<GlobalConfigManager>,
|
||||
registry_pool: Arc<SqlitePool>,
|
||||
) -> Vec<Arc<dyn SystemAgent>> {
|
||||
vec![
|
||||
crate::tic::TicManager::new(
|
||||
tic_config,
|
||||
Arc::clone(&config_store),
|
||||
Arc::clone(®istry_pool),
|
||||
),
|
||||
memory_lint::MemoryLintAgent::private(
|
||||
Arc::clone(&config_store),
|
||||
Arc::clone(®istry_pool),
|
||||
),
|
||||
memory_lint::MemoryLintAgent::shared(config_store, registry_pool),
|
||||
]
|
||||
}
|
||||
|
||||
/// The config sets of every system agent, in the same order as [`registry`].
|
||||
///
|
||||
/// A free function rather than `registry(..).map(|a| a.config_set())` because
|
||||
/// `Runtime::bootstrap` needs the settings surface before it has the runtime
|
||||
/// dependencies an agent is built from. `registry_and_config_sets_agree` is what
|
||||
/// keeps the two honest.
|
||||
pub fn config_sets() -> Vec<ConfigSet> {
|
||||
vec![
|
||||
crate::tic::config_set(),
|
||||
memory_lint::private_config_set(),
|
||||
memory_lint::shared_config_set(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Is `agent` due for this user? `true` when it has never run here, or when the
|
||||
/// last attempt is older than the configured interval.
|
||||
///
|
||||
/// Read from the database rather than an in-memory deadline, which is what makes
|
||||
/// a weekly agent survive a restart — see the `system_agent_state` table comment.
|
||||
pub async fn is_due(agent: &dyn SystemAgent, pool: &SqlitePool) -> bool {
|
||||
let interval = agent.interval_secs().await as i64;
|
||||
match system_agent_state::seconds_since_attempt(pool, agent.id()).await {
|
||||
Ok(Some(elapsed)) => elapsed >= interval,
|
||||
// Never attempted here — due now.
|
||||
Ok(None) => true,
|
||||
// Unreadable state: run it. A spurious pass is recoverable; an agent that
|
||||
// silently stops running is not.
|
||||
Err(e) => {
|
||||
warn!(agent = agent.id(), error = %e, "system-agents: cannot read schedule state, running anyway");
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one pass and record it. See the module docs for why the steps are ordered
|
||||
/// the way they are.
|
||||
///
|
||||
/// `Ok(None)` means the pass had nothing to do and wrote no run row.
|
||||
pub async fn run_and_record(
|
||||
agent: &dyn SystemAgent,
|
||||
ctx: &AgentRunCtx<'_>,
|
||||
) -> Result<Option<AgentOutcome>> {
|
||||
// Step 1 — the attempt counts even if there is nothing to do, or an idle
|
||||
// agent is asked again on every single tick.
|
||||
if let Err(e) = system_agent_state::mark_attempt(ctx.pool, agent.id()).await {
|
||||
warn!(agent = agent.id(), user = %ctx.user_id, error = %e,
|
||||
"system-agents: could not record the attempt");
|
||||
}
|
||||
|
||||
// Step 2 — nothing to do leaves no trace.
|
||||
if !agent.has_work(ctx).await? {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Step 3 — open the row, then work.
|
||||
let run_id = system_agent_runs::start(ctx.pool, agent.id()).await?;
|
||||
let started = Instant::now();
|
||||
|
||||
match agent.run(ctx).await {
|
||||
Ok(outcome) => {
|
||||
system_agent_runs::finish(
|
||||
ctx.pool,
|
||||
run_id,
|
||||
system_agent_runs::STATUS_COMPLETED,
|
||||
outcome.session_id,
|
||||
started.elapsed().as_millis() as i64,
|
||||
Some(&outcome.stats.to_string()),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
info!(agent = agent.id(), user = %ctx.user_id, stats = %outcome.stats,
|
||||
"system-agents: pass complete");
|
||||
Ok(Some(outcome))
|
||||
}
|
||||
Err(e) => {
|
||||
// Best-effort: the pass already failed, and a failing log write must
|
||||
// not mask the original error.
|
||||
if let Err(log_err) = system_agent_runs::finish(
|
||||
ctx.pool,
|
||||
run_id,
|
||||
system_agent_runs::STATUS_FAILED,
|
||||
None,
|
||||
started.elapsed().as_millis() as i64,
|
||||
None,
|
||||
Some(&e.to_string()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(agent = agent.id(), user = %ctx.user_id, error = %log_err,
|
||||
"system-agents: failed to record the failed pass");
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared machinery ───────────────────────────────────────────────────────────
|
||||
|
||||
/// Run one ephemeral turn of `agent_id` and return `(session_id, notifications
|
||||
/// emitted)`.
|
||||
///
|
||||
/// Every system agent talks to its user the same way: a throwaway session that
|
||||
/// `ChatHub` never sees, approvals auto-denied because nobody is watching, and
|
||||
/// `notify()` as the only way out. Sharing it is what keeps a new agent from
|
||||
/// re-deriving the two subtleties below.
|
||||
pub async fn run_ephemeral_turn(
|
||||
agent_id: &str,
|
||||
source: &str,
|
||||
prompt: &str,
|
||||
run_context: Option<&RunContext>,
|
||||
notify_label: &str,
|
||||
ctx: &AgentRunCtx<'_>,
|
||||
) -> Result<(i64, usize)> {
|
||||
// A fresh ephemeral session per pass. ChatHub is bypassed on purpose: a
|
||||
// system agent is not a user-facing source and must not take over the
|
||||
// `sources` row of a conversation the user is having.
|
||||
let (session_id, _) = ctx
|
||||
.sessions
|
||||
.create_session(agent_id, source, false, true, run_context)
|
||||
.await?;
|
||||
let handler = ctx.sessions.get_or_create_handler(session_id).await?;
|
||||
|
||||
// Nobody is at the keyboard to answer an approval card, so anything the
|
||||
// rules gate is denied rather than left hanging forever.
|
||||
handler.set_auto_deny_approvals();
|
||||
|
||||
// The session's event stream has no subscriber, but the translator awaits its
|
||||
// sends — a receiver merely dropped, or kept and never polled, wedges the
|
||||
// turn at the channel's capacity. Drain it explicitly.
|
||||
let (tx, mut rx) = mpsc::channel(32);
|
||||
tokio::spawn(async move { while rx.recv().await.is_some() {} });
|
||||
|
||||
let (notify, emitted) = counting_notify(Arc::clone(ctx.hub), notify_label);
|
||||
|
||||
handler
|
||||
.handle_message(
|
||||
prompt,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
vec![notify],
|
||||
HashMap::new(),
|
||||
tx,
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok((session_id, emitted.load(Ordering::Relaxed)))
|
||||
}
|
||||
|
||||
/// The security group for one user's pass.
|
||||
///
|
||||
/// The configured group is an instance-wide admin setting, so it cannot be
|
||||
/// applied verbatim to somebody else's session: that would hand a restricted
|
||||
/// member's background agent a tool set their role never granted. It goes
|
||||
/// through the same seam a persisted group does —
|
||||
/// [`run_context::reconcile_group_for_user`] — which degrades it to the user's
|
||||
/// role default when their role does not allow it. With nothing configured we
|
||||
/// still start from the role default rather than `None`, because `None` means
|
||||
/// the catch-all group, which is *wider*.
|
||||
pub async fn configured_run_context(
|
||||
config_store: &GlobalConfigManager,
|
||||
registry_pool: &SqlitePool,
|
||||
key: &str,
|
||||
user_id: &str,
|
||||
) -> Option<RunContext> {
|
||||
let configured = config_store
|
||||
.get(key)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|g| !g.is_empty());
|
||||
|
||||
match configured {
|
||||
Some(group) => {
|
||||
let wanted = RunContext::with_security_group(Some(group));
|
||||
run_context::reconcile_group_for_user(registry_pool, user_id, Some(wanted)).await
|
||||
}
|
||||
None => run_context::role_default_run_context(registry_pool, user_id).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an instance-wide boolean switch, defaulting to on.
|
||||
pub async fn enabled_from_config(config_store: &GlobalConfigManager, key: &str) -> bool {
|
||||
match config_store.get(key).await {
|
||||
Ok(Some(v)) => v != "false",
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an interval expressed in `unit_secs`-sized units, falling back to
|
||||
/// `default_secs` when unset, unparseable or zero.
|
||||
pub async fn interval_from_config(
|
||||
config_store: &GlobalConfigManager,
|
||||
key: &str,
|
||||
unit_secs: u64,
|
||||
default_secs: u64,
|
||||
) -> u64 {
|
||||
if let Ok(Some(val)) = config_store.get(key).await {
|
||||
if let Ok(n) = val.trim().parse::<u64>() {
|
||||
if n > 0 {
|
||||
return n.saturating_mul(unit_secs);
|
||||
}
|
||||
}
|
||||
}
|
||||
default_secs
|
||||
}
|
||||
|
||||
/// The on/off switch every system agent has.
|
||||
pub fn enabled_property(key: &str, description: &str) -> ConfigProperty {
|
||||
ConfigProperty {
|
||||
key: key.into(),
|
||||
name: "Enabled".into(),
|
||||
description: description.into(),
|
||||
property_type: PropertyType::Bool,
|
||||
default_value: Some("true".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The security-group picker every system agent has. The wording spells out the
|
||||
/// per-user reconciliation, because an admin choosing a wide group here would
|
||||
/// otherwise expect it to apply verbatim.
|
||||
pub fn security_group_property(key: &str) -> ConfigProperty {
|
||||
ConfigProperty {
|
||||
key: key.into(),
|
||||
name: "Security group".into(),
|
||||
description: "Tool permission group applied to each run. It is re-checked against each \
|
||||
user's own role: a user whose role does not allow this group runs under \
|
||||
their role's default group instead. Leave empty to always use the role \
|
||||
default."
|
||||
.into(),
|
||||
property_type: PropertyType::SecurityGroup,
|
||||
default_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the `notify` tool so the run log can report how many notifications a
|
||||
/// pass actually produced, without the tool itself knowing it is being counted.
|
||||
fn counting_notify(hub: Arc<ChatHub>, label: &str) -> (InterfaceTool, Arc<AtomicUsize>) {
|
||||
let inner = crate::tools::notify::make_tool(hub, label);
|
||||
let counter = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let handler = {
|
||||
let counter = Arc::clone(&counter);
|
||||
let call = Arc::clone(&inner.handler);
|
||||
Arc::new(move |args: serde_json::Value| {
|
||||
let counter = Arc::clone(&counter);
|
||||
let fut = call(args);
|
||||
Box::pin(async move {
|
||||
let out = fut.await;
|
||||
if out.is_ok() {
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
out
|
||||
}) as ToolFuture
|
||||
})
|
||||
};
|
||||
|
||||
(InterfaceTool { definition: inner.definition, handler }, counter)
|
||||
}
|
||||
|
||||
/// Every system agent's config set must be owned by the agent, or its settings
|
||||
/// silently land on the general Config page instead of its own tab.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tic_config_set_is_owned_by_tic() {
|
||||
let set = crate::tic::config_set();
|
||||
assert_eq!(set.owner.as_deref(), Some(crate::tic::TIC_AGENT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lint_config_sets_are_owned_by_their_agents() {
|
||||
assert_eq!(
|
||||
memory_lint::private_config_set().owner.as_deref(),
|
||||
Some(memory_lint::PRIVATE_AGENT),
|
||||
);
|
||||
assert_eq!(
|
||||
memory_lint::shared_config_set().owner.as_deref(),
|
||||
Some(memory_lint::SHARED_AGENT),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn registry_and_config_sets_agree() {
|
||||
// Constructing the agents touches no table — the pool is only a handle
|
||||
// they hold on to — so an empty database is enough here.
|
||||
let pool = Arc::new(SqlitePool::connect("sqlite::memory:").await.unwrap());
|
||||
let config = Arc::new(GlobalConfigManager::new(
|
||||
Arc::clone(&pool),
|
||||
Arc::new(core_api::system_bus::SystemEventBus::new()),
|
||||
));
|
||||
|
||||
let scheduled: Vec<&str> =
|
||||
registry(Default::default(), config, pool).iter().map(|a| a.id()).collect();
|
||||
let configured: Vec<String> = config_sets()
|
||||
.into_iter()
|
||||
.map(|s| s.owner.expect("a system agent's config set must be owned by it"))
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
scheduled, configured,
|
||||
"the scheduler's agents and the settings surface have drifted apart",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_agent_declares_its_interval_key_among_its_properties() {
|
||||
// The scheduler watches `interval_key()` for live changes; a key that is
|
||||
// not in the set is one nothing can ever edit.
|
||||
for (set, key) in [
|
||||
(crate::tic::config_set(), crate::tic::TIC_INTERVAL_MINUTES_KEY),
|
||||
(memory_lint::private_config_set(), memory_lint::PRIVATE_INTERVAL_DAYS_KEY),
|
||||
(memory_lint::shared_config_set(), memory_lint::SHARED_INTERVAL_DAYS_KEY),
|
||||
] {
|
||||
assert!(
|
||||
set.properties.iter().any(|p| p.key == key),
|
||||
"`{key}` is watched by the scheduler but is not an editable property",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,31 +9,35 @@
|
||||
//! reads live in `mcp_events` inside the caller's own encrypted database, the
|
||||
//! connectors that produced them run inside the caller's container, and the
|
||||
//! notification it emits goes to the caller's own hub. This manager therefore
|
||||
//! owns no timer and no user list: it exposes [`TicManager::run_for`], one tick
|
||||
//! for one user, and the instance-wide scheduler
|
||||
//! (`skald::wiring::spawn_system_agents`) decides who to run it for and when —
|
||||
//! sequentially, skipping anyone whose database is still locked.
|
||||
//! owns no timer and no user list: it implements
|
||||
//! [`SystemAgent`](crate::system_agents::SystemAgent), one pass for one user,
|
||||
//! and the instance-wide scheduler (`skald::wiring::spawn_system_agents`)
|
||||
//! decides who to run it for and when — sequentially, skipping anyone whose
|
||||
//! database is still locked.
|
||||
//!
|
||||
//! The run is recorded in `system_agent_runs` in that same user's database, so
|
||||
//! the trace of what TIC did for someone is readable by them and by nobody else.
|
||||
//! Opening and closing that row is [`crate::system_agents::run_and_record`]'s
|
||||
//! job, not TIC's: every agent needs it identically, and the ordering rules
|
||||
//! around it are subtle enough that one copy is the only safe number.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use sqlx::SqlitePool;
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{info, warn};
|
||||
use tracing::info;
|
||||
|
||||
use core_api::interface_tool::{InterfaceTool, ToolFuture};
|
||||
use core_api::{ConfigProperty, ConfigSet, PropertyType};
|
||||
|
||||
use crate::chat_hub::ChatHub;
|
||||
use crate::config::TicConfig;
|
||||
use crate::config_store::GlobalConfigManager;
|
||||
use crate::db::{mcp_events, system_agent_runs};
|
||||
use crate::run_context::{self, RunContext};
|
||||
use crate::session::manager::ChatSessionManager;
|
||||
use crate::db::mcp_events;
|
||||
use crate::system_agents::{
|
||||
AgentOutcome, AgentRunCtx, AgentScope, SystemAgent, configured_run_context,
|
||||
enabled_from_config, enabled_property, interval_from_config, run_ephemeral_turn,
|
||||
security_group_property,
|
||||
};
|
||||
|
||||
/// The chat `source` TIC's ephemeral sessions carry. Kept distinct from the
|
||||
/// user-facing sources (`web`, `talk`, `telegram`) so a tick never lands in a
|
||||
@@ -58,28 +62,24 @@ pub fn config_set() -> ConfigSet {
|
||||
because their database is still encrypted. Each run is recorded on the System \
|
||||
agents page, visible to the user it ran for.".into(),
|
||||
properties: vec![
|
||||
ConfigProperty {
|
||||
key: TIC_ENABLED_KEY.into(),
|
||||
name: "Enabled".into(),
|
||||
description: "Enable or disable the TIC agent for the whole instance. When disabled, no events are processed for anyone.".into(),
|
||||
property_type: PropertyType::Bool,
|
||||
default_value: Some("true".into()),
|
||||
},
|
||||
ConfigProperty {
|
||||
key: TIC_SECURITY_GROUP_KEY.into(),
|
||||
name: "Security Group".into(),
|
||||
description: "Tool permission group applied to each TIC run. It is re-checked against each user's own role: a user whose role does not allow this group runs under their role's default group instead. Leave empty to always use the role default.".into(),
|
||||
property_type: PropertyType::SecurityGroup,
|
||||
default_value: None,
|
||||
},
|
||||
enabled_property(
|
||||
TIC_ENABLED_KEY,
|
||||
"Enable or disable the TIC agent for the whole instance. When disabled, no events \
|
||||
are processed for anyone.",
|
||||
),
|
||||
security_group_property(TIC_SECURITY_GROUP_KEY),
|
||||
ConfigProperty {
|
||||
key: TIC_INTERVAL_MINUTES_KEY.into(),
|
||||
name: "Check Interval (minutes)".into(),
|
||||
description: "How often TIC starts a pass over all users, in minutes. Leave empty to use the value from config.yml (tic.interval_secs).".into(),
|
||||
name: "Check interval (minutes)".into(),
|
||||
description: "How long between passes for each user, in minutes. Counted per \
|
||||
person from their own last pass. Leave empty to use the value from \
|
||||
config.yml (tic.interval_secs)."
|
||||
.into(),
|
||||
property_type: PropertyType::Int,
|
||||
default_value: Some("15".into()),
|
||||
},
|
||||
],
|
||||
owner: Some(TIC_AGENT.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,16 +90,6 @@ pub struct TicRun {
|
||||
pub notifications_emitted: usize,
|
||||
}
|
||||
|
||||
impl TicRun {
|
||||
fn stats_json(&self) -> String {
|
||||
serde_json::json!({
|
||||
"events_processed": self.events_processed,
|
||||
"notifications_emitted": self.notifications_emitted,
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TicManager {
|
||||
config: TicConfig,
|
||||
config_store: Arc<GlobalConfigManager>,
|
||||
@@ -117,199 +107,86 @@ impl TicManager {
|
||||
Arc::new(Self { config, config_store, registry_pool })
|
||||
}
|
||||
|
||||
/// Instance-wide on/off switch. Read fresh each pass, so toggling it in
|
||||
/// Settings takes effect at the next pass with no restart.
|
||||
pub async fn is_enabled(&self) -> bool {
|
||||
match self.config_store.get(TIC_ENABLED_KEY).await {
|
||||
Ok(Some(v)) => v != "false",
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds between passes: the Settings value wins, else `config.yml`.
|
||||
pub async fn interval_secs(&self) -> u64 {
|
||||
if let Ok(Some(val)) = self.config_store.get(TIC_INTERVAL_MINUTES_KEY).await {
|
||||
if let Ok(mins) = val.parse::<u64>() {
|
||||
if mins > 0 {
|
||||
return mins * 60;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.config.interval_secs
|
||||
}
|
||||
|
||||
/// One tick for one user, over that user's own runtime.
|
||||
///
|
||||
/// `Ok(None)` means there was nothing to do — no pending events — and
|
||||
/// **nothing is written**: an idle tick must not leave a row behind, or the
|
||||
/// run log becomes a heartbeat instead of a history. Any other outcome opens
|
||||
/// a `system_agent_runs` row and closes it, failure included.
|
||||
pub async fn run_for(
|
||||
&self,
|
||||
user_id: &str,
|
||||
pool: &SqlitePool,
|
||||
sessions: &Arc<ChatSessionManager>,
|
||||
hub: &Arc<ChatHub>,
|
||||
) -> anyhow::Result<Option<TicRun>> {
|
||||
let events = mcp_events::pending_limited(pool, self.config.batch_size).await?;
|
||||
if events.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let run_id = system_agent_runs::start(pool, TIC_AGENT).await?;
|
||||
let started = Instant::now();
|
||||
|
||||
match self.tick(user_id, pool, sessions, hub, events).await {
|
||||
Ok(run) => {
|
||||
system_agent_runs::finish(
|
||||
pool,
|
||||
run_id,
|
||||
system_agent_runs::STATUS_COMPLETED,
|
||||
Some(run.session_id),
|
||||
started.elapsed().as_millis() as i64,
|
||||
Some(&run.stats_json()),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
info!(
|
||||
user = %user_id,
|
||||
events = run.events_processed,
|
||||
notifications = run.notifications_emitted,
|
||||
"TIC: tick complete",
|
||||
);
|
||||
Ok(Some(run))
|
||||
}
|
||||
Err(e) => {
|
||||
// Best-effort: the tick already failed, a failing log write must not
|
||||
// mask the original error.
|
||||
if let Err(log_err) = system_agent_runs::finish(
|
||||
pool,
|
||||
run_id,
|
||||
system_agent_runs::STATUS_FAILED,
|
||||
None,
|
||||
started.elapsed().as_millis() as i64,
|
||||
None,
|
||||
Some(&e.to_string()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!(user = %user_id, error = %log_err, "TIC: failed to record the failed run");
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn tick(
|
||||
&self,
|
||||
user_id: &str,
|
||||
pool: &SqlitePool,
|
||||
sessions: &Arc<ChatSessionManager>,
|
||||
hub: &Arc<ChatHub>,
|
||||
events: Vec<mcp_events::McpEvent>,
|
||||
) -> anyhow::Result<TicRun> {
|
||||
info!(user = %user_id, count = events.len(), "TIC: processing event batch");
|
||||
async fn tick(&self, ctx: &AgentRunCtx<'_>) -> Result<TicRun> {
|
||||
let events = mcp_events::pending_limited(ctx.pool, self.config.batch_size).await?;
|
||||
info!(user = %ctx.user_id, count = events.len(), "TIC: processing event batch");
|
||||
|
||||
// Mark as processed BEFORE running the agent — a crash mid-turn then costs
|
||||
// this batch rather than replaying it forever. The loss is visible: the run
|
||||
// row closes as `failed` with the error.
|
||||
let ids: Vec<i64> = events.iter().map(|e| e.id).collect();
|
||||
mcp_events::mark_processed(pool, &ids).await?;
|
||||
mcp_events::mark_processed(ctx.pool, &ids).await?;
|
||||
|
||||
let prompt = build_prompt(&events);
|
||||
let rc = self.run_context_for(user_id).await;
|
||||
let rc = configured_run_context(
|
||||
&self.config_store,
|
||||
&self.registry_pool,
|
||||
TIC_SECURITY_GROUP_KEY,
|
||||
ctx.user_id,
|
||||
)
|
||||
.await;
|
||||
|
||||
// A fresh ephemeral session per tick (agent_id = "tic", source = "tic").
|
||||
// ChatHub is bypassed: TIC is not a user-facing source and must not take
|
||||
// over the `sources` row of a conversation the user is having.
|
||||
let (session_id, _) = sessions
|
||||
.create_session(TIC_AGENT, TIC_SOURCE, false, true, rc.as_ref())
|
||||
.await?;
|
||||
let handler = sessions.get_or_create_handler(session_id).await?;
|
||||
handler.set_auto_deny_approvals();
|
||||
|
||||
// The session's event stream has no subscriber, but the translator awaits
|
||||
// its sends — a receiver that is merely dropped, or kept and never polled,
|
||||
// wedges the turn at the channel's capacity. Drain it explicitly.
|
||||
let (tx, mut rx) = mpsc::channel(32);
|
||||
tokio::spawn(async move { while rx.recv().await.is_some() {} });
|
||||
|
||||
let (notify, emitted) = counting_notify(Arc::clone(hub));
|
||||
|
||||
handler
|
||||
.handle_message(
|
||||
&prompt,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
vec![notify],
|
||||
std::collections::HashMap::new(),
|
||||
tx,
|
||||
true,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let (session_id, notified) = run_ephemeral_turn(
|
||||
TIC_AGENT,
|
||||
TIC_SOURCE,
|
||||
&build_prompt(&events),
|
||||
rc.as_ref(),
|
||||
"TIC",
|
||||
ctx,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(TicRun {
|
||||
session_id,
|
||||
events_processed: events.len(),
|
||||
notifications_emitted: emitted.load(Ordering::Relaxed),
|
||||
notifications_emitted: notified,
|
||||
})
|
||||
}
|
||||
|
||||
/// The security group for this user's tick.
|
||||
///
|
||||
/// The configured group is an instance-wide admin setting, so it cannot be
|
||||
/// applied verbatim to somebody else's session: that would hand a restricted
|
||||
/// member's TIC run a tool set their role never granted. It goes through the
|
||||
/// same seam a persisted group does — [`run_context::reconcile_group_for_user`],
|
||||
/// which degrades it to the user's role default when their role does not allow
|
||||
/// it. With nothing configured we still start from the role default rather than
|
||||
/// `None`, because `None` means the catch-all group, which is *wider*.
|
||||
async fn run_context_for(&self, user_id: &str) -> Option<RunContext> {
|
||||
let configured = self
|
||||
.config_store
|
||||
.get(TIC_SECURITY_GROUP_KEY)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|g| !g.is_empty());
|
||||
|
||||
match configured {
|
||||
Some(group) => {
|
||||
let wanted = RunContext::with_security_group(Some(group));
|
||||
run_context::reconcile_group_for_user(&self.registry_pool, user_id, Some(wanted)).await
|
||||
}
|
||||
None => run_context::role_default_run_context(&self.registry_pool, user_id).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the `notify` tool so the run log can report how many notifications the
|
||||
/// tick actually produced, without the tool itself knowing it is being counted.
|
||||
fn counting_notify(hub: Arc<ChatHub>) -> (InterfaceTool, Arc<AtomicUsize>) {
|
||||
let inner = crate::tools::notify::make_tool(hub, "TIC");
|
||||
let counter = Arc::new(AtomicUsize::new(0));
|
||||
#[async_trait]
|
||||
impl SystemAgent for TicManager {
|
||||
fn id(&self) -> &'static str { TIC_AGENT }
|
||||
|
||||
let handler = {
|
||||
let counter = Arc::clone(&counter);
|
||||
let call = Arc::clone(&inner.handler);
|
||||
Arc::new(move |args: serde_json::Value| {
|
||||
let counter = Arc::clone(&counter);
|
||||
let fut = call(args);
|
||||
Box::pin(async move {
|
||||
let out = fut.await;
|
||||
if out.is_ok() {
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
out
|
||||
}) as ToolFuture
|
||||
fn scope(&self) -> AgentScope { AgentScope::PerUser }
|
||||
|
||||
fn config_set(&self) -> ConfigSet { config_set() }
|
||||
|
||||
fn interval_key(&self) -> &'static str { TIC_INTERVAL_MINUTES_KEY }
|
||||
|
||||
async fn is_enabled(&self) -> bool {
|
||||
enabled_from_config(&self.config_store, TIC_ENABLED_KEY).await
|
||||
}
|
||||
|
||||
/// Seconds between passes: the Settings value (minutes) wins, else `config.yml`.
|
||||
async fn interval_secs(&self) -> u64 {
|
||||
interval_from_config(
|
||||
&self.config_store,
|
||||
TIC_INTERVAL_MINUTES_KEY,
|
||||
60,
|
||||
self.config.interval_secs,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// No pending events means no tick at all — and no row. The batch is re-read
|
||||
/// in [`TicManager::tick`]; it is one indexed query on a small table, and
|
||||
/// paying it twice is cheaper than a trait shaped around carrying the rows.
|
||||
async fn has_work(&self, ctx: &AgentRunCtx<'_>) -> Result<bool> {
|
||||
let events = mcp_events::pending_limited(ctx.pool, self.config.batch_size).await?;
|
||||
Ok(!events.is_empty())
|
||||
}
|
||||
|
||||
async fn run(&self, ctx: &AgentRunCtx<'_>) -> Result<AgentOutcome> {
|
||||
let run = self.tick(ctx).await?;
|
||||
Ok(AgentOutcome {
|
||||
session_id: Some(run.session_id),
|
||||
stats: serde_json::json!({
|
||||
"events_processed": run.events_processed,
|
||||
"notifications_emitted": run.notifications_emitted,
|
||||
}),
|
||||
})
|
||||
};
|
||||
|
||||
(InterfaceTool { definition: inner.definition, handler }, counter)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Prompt builder ─────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user