use serde::Serialize;
use super::*;
use crate::tools::telemetry::{RecallTelemetry, SearchTelemetry};
use crate::events::{ContextBudgetSnapshot, IndexReadinessSnapshot};
const READINESS_STATE_READY: &str = "ready";
const READINESS_STATE_WARMING: &str = "warming";
const READINESS_STATE_UNAVAILABLE: &str = "unavailable";
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ReadinessQuery {
Probed(IndexReadinessSnapshot),
NeverProbed,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ContextBudgetQuery {
Recorded(ContextBudgetSnapshot),
NeverRecorded,
}
impl SessionRegistry {
pub fn record_index_readiness(
&self,
id: &str,
readiness: Option<&trusty_common::search_readiness::IndexReadiness>,
summary: &str,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
let snapshot = match readiness {
Some(r) => IndexReadinessSnapshot {
state: if r.semantic_search_ready() {
READINESS_STATE_READY
} else {
READINESS_STATE_WARMING
}
.to_string(),
index_id: Some(r.index_id.clone()),
lifecycle_status: Some(r.lifecycle_status.clone()),
chunk_count: Some(r.chunk_count),
lexical_ready: r.lexical_ready,
semantic_ready: r.semantic_ready,
graph_ready: r.graph_ready,
summary: summary.to_string(),
},
None => IndexReadinessSnapshot {
state: READINESS_STATE_UNAVAILABLE.to_string(),
index_id: None,
lifecycle_status: None,
chunk_count: None,
lexical_ready: false,
semantic_ready: false,
graph_ready: false,
summary: summary.to_string(),
},
};
{
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.readiness = Some(snapshot.clone());
}
}
self.record(
id,
Event::IndexReadiness {
session_id: id.to_string(),
state: snapshot.state,
index_id: snapshot.index_id,
lifecycle_status: snapshot.lifecycle_status,
chunk_count: snapshot.chunk_count,
lexical_ready: snapshot.lexical_ready,
semantic_ready: snapshot.semantic_ready,
graph_ready: snapshot.graph_ready,
summary: snapshot.summary,
},
);
Ok(())
}
pub fn get_readiness(&self, id: &str) -> Result<ReadinessQuery, RpcError> {
self.ensure_exists(id)?;
Ok(self
.lock()
.get(id)
.and_then(|e| e.readiness.clone())
.map(ReadinessQuery::Probed)
.unwrap_or(ReadinessQuery::NeverProbed))
}
pub fn record_context_budget(
&self,
id: &str,
measurement: &crate::agent_loop::ContextBudgetSnapshot,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
let mut snapshot = ContextBudgetSnapshot {
context_window_tokens: measurement.context_window,
overhead_tokens: measurement.overhead_tokens,
overhead_cap_tokens: measurement.overhead_cap_tokens,
working_context_pct: measurement.working_context_pct,
overhead_pct: measurement.overhead_pct,
within_budget: measurement.within_budget,
compaction_fired: measurement.fired,
compaction_rounds: measurement.rounds,
lifetime_compaction_alarm_count: 0,
working_context_pct_low_water_mark: None,
working_context_pct_sample_count: 0,
lifetime_cadence_floor_breach_count: 0,
};
{
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.context_floor.record(measurement.working_context_pct);
snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
entry.context_budget = Some(snapshot);
}
}
self.record(
id,
Event::ContextBudget {
session_id: id.to_string(),
context_window_tokens: snapshot.context_window_tokens,
overhead_tokens: snapshot.overhead_tokens,
overhead_cap_tokens: snapshot.overhead_cap_tokens,
working_context_pct: snapshot.working_context_pct,
overhead_pct: snapshot.overhead_pct,
within_budget: snapshot.within_budget,
compaction_fired: snapshot.compaction_fired,
compaction_rounds: snapshot.compaction_rounds,
},
);
Ok(())
}
pub fn get_context_budget(&self, id: &str) -> Result<ContextBudgetQuery, RpcError> {
self.ensure_exists(id)?;
let cached = self.lock().get(id).and_then(|entry| {
entry.context_budget.map(|mut snapshot| {
snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
snapshot
})
});
Ok(cached
.map(|mut snapshot| {
let data_dir = crate::agent_loop::telemetry::default_data_dir();
snapshot.lifetime_compaction_alarm_count =
crate::agent_loop::telemetry::lifetime_compaction_alarm_count(&data_dir);
snapshot.lifetime_cadence_floor_breach_count =
crate::agent_loop::telemetry::lifetime_cadence_floor_breach_count(&data_dir);
ContextBudgetQuery::Recorded(snapshot)
})
.unwrap_or(ContextBudgetQuery::NeverRecorded))
}
pub fn record_tool_started(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
args: &str,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::ToolStarted {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
tool: tool.to_string(),
call_id: call_id.to_string(),
args_preview: crate::events::preview(args, 500),
},
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn record_tool_finished(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
success: bool,
result: &str,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::ToolFinished {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
tool: tool.to_string(),
call_id: call_id.to_string(),
success,
result_preview: crate::events::preview(result, 500),
},
);
Ok(())
}
pub fn record_tool_error(
&self,
id: &str,
agent: &str,
agent_id: &str,
tool: &str,
call_id: &str,
error: &str,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::ToolError {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
tool: tool.to_string(),
call_id: call_id.to_string(),
error: error.to_string(),
},
);
Ok(())
}
pub fn record_search_performed(
&self,
id: &str,
agent: &str,
agent_id: &str,
telemetry: &SearchTelemetry,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.push_search_audit(
id,
crate::events::SearchAuditRecord::Search {
agent: agent.to_string(),
agent_id: agent_id.to_string(),
lane: telemetry.lane.clone(),
query: telemetry.query.clone(),
hit_count: telemetry.hit_count,
latency_ms: telemetry.latency_ms,
at: Utc::now(),
},
);
self.record(
id,
Event::SearchPerformed {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
lane: telemetry.lane.clone(),
query: telemetry.query.clone(),
hit_count: telemetry.hit_count,
hits: telemetry.hits.clone(),
latency_ms: telemetry.latency_ms,
},
);
Ok(())
}
pub fn record_memory_recalled(
&self,
id: &str,
agent: &str,
agent_id: &str,
telemetry: &RecallTelemetry,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.push_search_audit(
id,
crate::events::SearchAuditRecord::Recall {
agent: agent.to_string(),
agent_id: agent_id.to_string(),
query: telemetry.query.clone(),
result_count: telemetry.results.len(),
injected_count: telemetry.results.iter().filter(|r| r.injected).count(),
at: Utc::now(),
},
);
self.record(
id,
Event::MemoryRecalled {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
query: telemetry.query.clone(),
results: telemetry.results.clone(),
},
);
Ok(())
}
pub fn record_log(&self, id: &str, level: &str, message: &str) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::Log {
session_id: id.to_string(),
level: level.to_string(),
message: message.to_string(),
},
);
Ok(())
}
pub fn record_progress(
&self,
id: &str,
message: &str,
percent: Option<f32>,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::Progress {
session_id: id.to_string(),
message: message.to_string(),
percent,
},
);
Ok(())
}
pub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::Message {
session_id: id.to_string(),
text: text.to_string(),
},
);
Ok(())
}
pub fn record_agent_message_delta(
&self,
id: &str,
agent: &str,
agent_id: &str,
turn_id: &str,
delta: &str,
done: bool,
) -> Result<(), RpcError> {
self.ensure_exists(id)?;
self.record(
id,
Event::AgentMessageDelta {
session_id: id.to_string(),
agent: agent.to_string(),
agent_id: agent_id.to_string(),
turn_id: turn_id.to_string(),
delta: delta.to_string(),
done,
},
);
Ok(())
}
fn ensure_exists(&self, id: &str) -> Result<(), RpcError> {
if self.lock().contains_key(id) {
Ok(())
} else {
Err(RpcError::session_not_found(id))
}
}
}