use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use chrono::Utc;
use serde_json::json;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use uuid::Uuid;
use crate::agent_loop::Transcript;
use crate::events::{Event, SessionEventEnvelope};
use crate::jsonrpc::{NotifySender, RpcError};
use crate::mode::HarnessMode;
use crate::perf::TokenUsage;
use crate::run_task::TurnRecord;
use super::model::{Session, SessionStatus};
use super::transcript::TranscriptRecord;
pub const DEFAULT_RING_CAPACITY: usize = 1000;
struct SessionEntry {
session: Session,
seq: u64,
ring: VecDeque<SessionEventEnvelope>,
attachments: HashMap<Uuid, oneshot::Sender<()>>,
execution: Option<Execution>,
transcript: Vec<TurnRecord>,
usage: TokenUsage,
cost_usd: Option<f64>,
pm_transcript: Option<Transcript>,
memory_sink: Option<Arc<super::memory_sink::TurnMemorySink>>,
}
struct Execution {
cancel: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}
pub struct SessionRegistry {
sessions: Mutex<HashMap<String, SessionEntry>>,
ring_capacity: usize,
}
impl Default for SessionRegistry {
fn default() -> Self {
Self::new()
}
}
impl SessionRegistry {
pub fn new() -> Self {
Self::with_capacity(DEFAULT_RING_CAPACITY)
}
pub fn with_capacity(ring_capacity: usize) -> Self {
Self {
sessions: Mutex::new(HashMap::new()),
ring_capacity,
}
}
pub fn create(&self, task: String, agent: Option<String>, project: Option<String>) -> Session {
let id = Uuid::new_v4().to_string();
let session = Session {
id: id.clone(),
task,
agent,
project: project.clone(),
status: SessionStatus::Created,
created_at: Utc::now(),
mode: None,
};
{
let mut sessions = self.lock();
sessions.insert(
id.clone(),
SessionEntry {
session: session.clone(),
seq: 0,
ring: VecDeque::new(),
attachments: HashMap::new(),
execution: None,
transcript: Vec::new(),
usage: TokenUsage::default(),
cost_usd: None,
pm_transcript: None,
memory_sink: None,
},
);
}
self.record(
&id,
Event::SessionStarted {
session_id: id.clone(),
project: project.unwrap_or_default(),
},
);
self.transition(&id, SessionStatus::Running);
self.status(&id).unwrap_or(session)
}
pub fn list(&self) -> Vec<Session> {
self.lock().values().map(|e| e.session.clone()).collect()
}
pub fn status(&self, id: &str) -> Result<Session, RpcError> {
self.lock()
.get(id)
.map(|e| e.session.clone())
.ok_or_else(|| RpcError::session_not_found(id))
}
pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError> {
if !self.lock().contains_key(id) {
return Err(RpcError::session_not_found(id));
}
self.record(
id,
Event::SessionInput {
session_id: id.to_string(),
input: input.to_string(),
},
);
Ok(())
}
pub fn cancel(&self, id: &str) -> Result<Session, RpcError> {
let already_terminal = {
let sessions = self.lock();
let entry = sessions
.get(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
entry.session.status.is_terminal()
};
if already_terminal {
return self.status(id);
}
self.transition(id, SessionStatus::Cancelled);
self.record(
id,
Event::SessionCancelled {
session_id: id.to_string(),
},
);
self.record(
id,
Event::SessionDone {
session_id: id.to_string(),
status: SessionStatus::Cancelled.as_str().to_string(),
},
);
self.status(id)
}
pub fn finish(&self, id: &str, status: SessionStatus) -> Result<Session, RpcError> {
let already_terminal = {
let sessions = self.lock();
let entry = sessions
.get(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
entry.session.status.is_terminal()
};
if !already_terminal {
self.transition(id, status);
self.record(
id,
Event::SessionDone {
session_id: id.to_string(),
status: status.as_str().to_string(),
},
);
}
self.status(id)
}
pub fn attach(
&self,
id: &str,
connection_id: Uuid,
notify: NotifySender,
) -> Result<Vec<SessionEventEnvelope>, RpcError> {
let replay = {
let mut sessions = self.lock();
let entry = sessions
.get_mut(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
let (cancel_tx, cancel_rx) = oneshot::channel();
entry.attachments.insert(connection_id, cancel_tx);
spawn_forwarder(id.to_string(), notify, cancel_rx);
entry.ring.iter().cloned().collect::<Vec<_>>()
};
Ok(replay)
}
pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError> {
let mut sessions = self.lock();
let entry = sessions
.get_mut(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
if let Some(cancel_tx) = entry.attachments.remove(&connection_id) {
let _ = cancel_tx.send(());
}
Ok(())
}
pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError> {
self.lock()
.get(id)
.map(|e| e.ring.iter().cloned().collect())
.ok_or_else(|| RpcError::session_not_found(id))
}
pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError> {
let (cancel, resumed) = {
let mut sessions = self.lock();
let entry = sessions
.get_mut(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
if matches!(
entry.session.status,
SessionStatus::Cancelled | SessionStatus::Failed | SessionStatus::DeadlineExceeded
) {
return Err(RpcError::invalid_argument(format!(
"session {id} is already terminal"
)));
}
if entry.execution.is_some() {
return Err(RpcError::invalid_argument(format!(
"session {id} already has a task running"
)));
}
let resumed = entry.session.status == SessionStatus::Finished;
if resumed {
entry.session.status = SessionStatus::Running;
}
let cancel = Arc::new(AtomicBool::new(false));
entry.execution = Some(Execution {
cancel: Arc::clone(&cancel),
handle: None,
});
(cancel, resumed)
};
if resumed {
self.record(
id,
Event::SessionStatusChanged {
session_id: id.to_string(),
status: SessionStatus::Running.as_str().to_string(),
},
);
}
Ok(cancel)
}
pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>) {
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id)
&& let Some(execution) = entry.execution.as_mut()
{
execution.handle = Some(handle);
}
}
pub fn finish_execution(&self, id: &str) {
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.execution = None;
}
}
pub fn is_executing(&self, id: &str) -> bool {
self.lock().get(id).is_some_and(|e| e.execution.is_some())
}
pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError> {
let sessions = self.lock();
let entry = sessions
.get(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
match &entry.execution {
Some(execution) => {
execution.cancel.store(true, Ordering::Relaxed);
Ok(true)
}
None => Ok(false),
}
}
pub fn set_run_outcome(
&self,
id: &str,
transcript: Vec<TurnRecord>,
usage: TokenUsage,
cost_usd: Option<f64>,
) {
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.transcript.extend(transcript);
entry.usage.add(&usage);
entry.cost_usd = match (entry.cost_usd, cost_usd) {
(Some(a), Some(b)) => Some(a + b),
(Some(a), None) | (None, Some(a)) => Some(a),
(None, None) => None,
};
}
}
pub fn begin_pm_transcript(
&self,
id: &str,
system: &str,
task: &str,
) -> Result<Transcript, RpcError> {
let mut sessions = self.lock();
let entry = sessions
.get_mut(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
Ok(match entry.pm_transcript.take() {
Some(mut existing) => {
existing.push_user(task);
existing
}
None => Transcript::seed(system, task),
})
}
pub fn store_pm_transcript(&self, id: &str, transcript: Transcript) {
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.pm_transcript = Some(transcript);
}
}
pub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError> {
let sessions = self.lock();
let entry = sessions
.get(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
Ok(TranscriptRecord {
session_id: id.to_string(),
turns: entry.transcript.clone(),
usage: entry.usage,
cost_usd: entry.cost_usd,
mode: entry.session.mode,
compaction_events: entry
.pm_transcript
.as_ref()
.map(Transcript::compaction_events)
.unwrap_or(0),
goals: goal_ops::goal_records(entry),
})
}
pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError> {
let mut sessions = self.lock();
let entry = sessions
.get_mut(id)
.ok_or_else(|| RpcError::session_not_found(id))?;
entry.session.mode = Some(mode);
Ok(())
}
pub async fn shutdown_executions(&self, grace: Duration) {
let handles: Vec<JoinHandle<()>> = {
let mut sessions = self.lock();
sessions
.values_mut()
.filter_map(|entry| {
let execution = entry.execution.as_mut()?;
execution.cancel.store(true, Ordering::Relaxed);
execution.handle.take()
})
.collect()
};
if handles.is_empty() {
return;
}
let _ = tokio::time::timeout(grace, futures_util::future::join_all(handles)).await;
}
fn record(&self, id: &str, event: Event) {
let envelope = {
let mut sessions = self.lock();
let Some(entry) = sessions.get_mut(id) else {
return;
};
entry.seq += 1;
let envelope = SessionEventEnvelope::new(id.to_string(), entry.seq, Utc::now(), event);
if entry.ring.len() >= self.ring_capacity {
entry.ring.pop_front();
}
entry.ring.push_back(envelope.clone());
envelope
};
crate::events::publish(envelope);
}
fn transition(&self, id: &str, status: SessionStatus) {
{
let mut sessions = self.lock();
if let Some(entry) = sessions.get_mut(id) {
entry.session.status = status;
}
}
self.record(
id,
Event::SessionStatusChanged {
session_id: id.to_string(),
status: status.as_str().to_string(),
},
);
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionEntry>> {
self.sessions
.lock()
.unwrap_or_else(|poison| poison.into_inner())
}
}
fn spawn_forwarder(session_id: String, notify: NotifySender, cancel_rx: oneshot::Receiver<()>) {
use tokio::sync::broadcast::error::RecvError;
let mut events = crate::events::subscribe();
tokio::spawn(async move {
tokio::pin!(cancel_rx);
loop {
tokio::select! {
biased;
_ = &mut cancel_rx => break,
received = events.recv() => match received {
Ok(envelope) if envelope.session_id == session_id => {
let notification = json!({
"jsonrpc": "2.0",
"method": "session.event",
"params": envelope,
});
if notify.send(notification).is_err() {
break;
}
}
Ok(_) => continue,
Err(RecvError::Lagged(_)) => continue,
Err(RecvError::Closed) => break,
},
}
}
});
}
#[path = "registry_events.rs"]
mod events;
#[path = "registry_memory_sink.rs"]
mod memory_sink_ext;
#[path = "registry_goals.rs"]
mod goal_ops;
#[cfg(test)]
#[path = "registry_tests.rs"]
mod registry_tests;