use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use kjarni::agent::{
Access, Agent, AgentConfig, AgentEvents, AgentModel, Approval, Memory, Session, SessionInfo,
ToolCall, ToolOutcome, tools,
};
use serde::Serialize;
use serde_json::{Value as Json, json};
use tokio::sync::{broadcast, oneshot};
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct Event {
pub seq: u64,
#[serde(flatten)]
pub kind: EventKind,
}
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventKind {
User {
text: String,
},
Text {
delta: String,
},
ToolCall {
call: u32,
name: String,
summary: String,
access: &'static str,
arguments: Json,
},
Approval {
approval: u64,
call: u32,
summary: String,
access: &'static str,
},
Approved {
approval: u64,
decision: &'static str,
},
ToolResult {
call: u32,
ok: bool,
denied: bool,
output: String,
},
Notice {
message: String,
},
Done {
text: String,
steps: usize,
tool_calls: usize,
stopped_early: bool,
},
Error {
message: String,
},
Stopped,
}
impl EventKind {
pub fn ends_turn(&self) -> bool {
matches!(
self,
EventKind::Done { .. } | EventKind::Error { .. } | EventKind::Stopped
)
}
}
fn decision_name(a: Approval) -> &'static str {
match a {
Approval::Once => "once",
Approval::Always => "always",
Approval::Deny => "deny",
}
}
struct Turn {
busy: bool,
events: Vec<Event>,
pending: Option<(u64, oneshot::Sender<Approval>)>,
task: Option<tokio::task::AbortHandle>,
transcript: Json,
}
pub struct Snapshot {
pub transcript: Json,
pub busy: bool,
pub events: Vec<Event>,
pub pending_approval: Option<u64>,
}
fn transcript_of(agent: &Agent) -> Json {
let specs = agent.tools();
let messages: Vec<Json> = agent
.messages()
.iter()
.map(|m| super::display::message(m, specs))
.collect();
json!({ "summary": agent.summary(), "messages": messages })
}
pub struct Live {
pub id: String,
agent: tokio::sync::Mutex<Agent>,
turn: Mutex<Turn>,
tx: broadcast::Sender<Event>,
hub: Arc<Hub>,
}
#[derive(Default)]
struct Hub {
seq: Mutex<u64>,
held: RwLock<bool>,
}
impl Hub {
fn next(&self) -> u64 {
let mut seq = self.seq.lock().expect("event counter lock");
*seq += 1;
*seq
}
}
#[derive(Clone)]
pub enum Answers {
User,
Allowed(Arc<HashSet<String>>),
}
#[derive(Debug, PartialEq)]
pub enum SendError {
Busy,
Empty,
Held,
}
pub struct Hold(Arc<Hub>);
impl Drop for Hold {
fn drop(&mut self) {
*self.0.held.write().expect("hold lock") = false;
}
}
impl Live {
fn emit(&self, kind: EventKind) -> Event {
self.emit_with(kind, None)
}
fn emit_with(&self, kind: EventKind, transcript: Option<Json>) -> Event {
let event = Event {
seq: self.hub.next(),
kind,
};
let mut turn = self.turn.lock().expect("turn lock");
if let Some(t) = transcript {
turn.transcript = t;
}
if event.kind.ends_turn() {
turn.busy = false;
turn.task = None;
turn.pending = None;
}
turn.events.push(event.clone());
let _ = self.tx.send(event.clone());
event
}
pub fn follow(&self, after: u64) -> (Vec<Event>, broadcast::Receiver<Event>) {
let turn = self.turn.lock().expect("turn lock");
let rx = self.tx.subscribe();
let past = turn
.events
.iter()
.filter(|e| e.seq > after)
.cloned()
.collect();
(past, rx)
}
pub fn busy(&self) -> bool {
self.turn.lock().expect("turn lock").busy
}
pub fn snapshot(&self) -> Snapshot {
let turn = self.turn.lock().expect("turn lock");
Snapshot {
transcript: turn.transcript.clone(),
busy: turn.busy,
events: if turn.busy {
turn.events.clone()
} else {
Vec::new()
},
pending_approval: turn.pending.as_ref().map(|(id, _)| *id),
}
}
pub fn send(self: &Arc<Self>, text: &str) -> Result<(), SendError> {
self.send_with(text, Answers::User)
}
pub fn send_with(self: &Arc<Self>, text: &str, answers: Answers) -> Result<(), SendError> {
let text = text.trim().to_string();
if text.is_empty() {
return Err(SendError::Empty);
}
{
let held = self.hub.held.read().expect("hold lock");
if *held {
return Err(SendError::Held);
}
let mut turn = self.turn.lock().expect("turn lock");
if turn.busy {
return Err(SendError::Busy);
}
turn.busy = true;
turn.events.clear();
}
self.emit(EventKind::User { text: text.clone() });
let live = self.clone();
let task = tokio::spawn(async move {
let mut agent = live.agent.lock().await;
let mut events = Relay {
live: live.clone(),
call: 0,
answers,
};
let kind = match agent.send(&text, &mut events).await {
Ok(reply) => EventKind::Done {
text: super::display::split_reasoning(&reply.text).1.to_string(),
steps: reply.steps,
tool_calls: reply.tool_calls,
stopped_early: reply.stopped_early,
},
Err(e) => EventKind::Error {
message: format!("{e:#}"),
},
};
let transcript = transcript_of(&agent);
live.emit_with(kind, Some(transcript));
});
let mut turn = self.turn.lock().expect("turn lock");
if turn.busy {
turn.task = Some(task.abort_handle());
}
Ok(())
}
pub fn answer(&self, id: u64, decision: Approval) -> bool {
let sender = {
let mut turn = self.turn.lock().expect("turn lock");
match turn.pending.take() {
Some((pending, sender)) if pending == id => sender,
other => {
turn.pending = other;
return false;
}
}
};
self.emit(EventKind::Approved {
approval: id,
decision: decision_name(decision),
});
sender.send(decision).is_ok()
}
pub fn stop(self: &Arc<Self>) -> bool {
let task = {
let mut turn = self.turn.lock().expect("turn lock");
if !turn.busy {
return false;
}
turn.pending = None;
turn.task.take()
};
if let Some(task) = task {
task.abort();
}
self.emit(EventKind::Stopped);
let live = self.clone();
tokio::spawn(async move {
let agent = live.agent.lock().await;
let transcript = transcript_of(&agent);
drop(agent);
live.turn.lock().expect("turn lock").transcript = transcript;
});
true
}
}
struct Relay {
live: Arc<Live>,
call: u32,
answers: Answers,
}
#[async_trait]
impl AgentEvents for Relay {
async fn text(&mut self, delta: &str) {
self.live.emit(EventKind::Text {
delta: delta.to_string(),
});
}
async fn tool_call(&mut self, call: &ToolCall, summary: &str, access: Access) {
self.call += 1;
self.live.emit(EventKind::ToolCall {
call: self.call,
name: call.name.clone(),
summary: summary.to_string(),
access: access.as_str(),
arguments: Json::Object(call.arguments.clone()),
});
}
async fn approve(&mut self, call: &ToolCall, summary: &str, access: Access) -> Approval {
let id = self.live.hub.next();
let asked = EventKind::Approval {
approval: id,
call: self.call,
summary: summary.to_string(),
access: access.as_str(),
};
if let Answers::Allowed(allowed) = &self.answers {
self.live.emit(asked);
let decision = if allowed.contains(&call.name) {
Approval::Once
} else {
self.live.emit(EventKind::Notice {
message: format!(
"{} is not allowed in this schedule, so the call was declined.",
call.name
),
});
Approval::Deny
};
self.live.emit(EventKind::Approved {
approval: id,
decision: decision_name(decision),
});
return decision;
}
let (tx, rx) = oneshot::channel();
self.live.turn.lock().expect("turn lock").pending = Some((id, tx));
self.live.emit(asked);
rx.await.unwrap_or(Approval::Deny)
}
async fn tool_result(&mut self, _call: &ToolCall, outcome: &ToolOutcome) {
self.live.emit(EventKind::ToolResult {
call: self.call,
ok: outcome.ok,
denied: outcome.denied,
output: outcome.output.clone(),
});
}
async fn notice(&mut self, message: &str) {
self.live.emit(EventKind::Notice {
message: message.to_string(),
});
}
}
pub struct AgentSetup {
pub model: Arc<dyn AgentModel>,
pub memory: Option<Arc<Memory>>,
pub workdir: PathBuf,
pub max_steps: usize,
pub approve_all: bool,
}
pub struct Conversations {
setup: AgentSetup,
sessions_dir: PathBuf,
live: Mutex<HashMap<String, Arc<Live>>>,
hub: Arc<Hub>,
}
pub fn valid_id(id: &str) -> bool {
!id.is_empty()
&& id.len() <= 64
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
impl Conversations {
pub fn new(setup: AgentSetup, sessions_dir: PathBuf) -> Self {
Self {
setup,
sessions_dir,
live: Mutex::new(HashMap::new()),
hub: Arc::new(Hub::default()),
}
}
pub fn setup(&self) -> &AgentSetup {
&self.setup
}
pub fn list(&self) -> Result<Vec<SessionInfo>> {
Session::list(&self.sessions_dir)
}
pub fn busy(&self, id: &str) -> bool {
self.live
.lock()
.expect("conversations lock")
.get(id)
.is_some_and(|l| l.busy())
}
pub fn any_busy(&self) -> bool {
self.live
.lock()
.expect("conversations lock")
.values()
.any(|l| l.busy())
}
pub fn held(&self) -> bool {
*self.hub.held.read().expect("hold lock")
}
pub fn hold(&self) -> Option<Hold> {
let mut held = self.hub.held.write().expect("hold lock");
if *held || self.any_busy() {
return None;
}
*held = true;
Some(Hold(self.hub.clone()))
}
pub fn create(&self) -> Result<Arc<Live>> {
let session = Session::create(&self.sessions_dir)?;
let id = session.id().to_string();
let live = self.wrap(id.clone(), self.agent().with_session(session));
self.live
.lock()
.expect("conversations lock")
.insert(id, live.clone());
Ok(live)
}
pub fn get(&self, id: &str) -> Result<Option<Arc<Live>>> {
if !valid_id(id) {
return Ok(None);
}
if let Some(live) = self.live.lock().expect("conversations lock").get(id) {
return Ok(Some(live.clone()));
}
if !self.sessions_dir.join(format!("{id}.jsonl")).exists() {
return Ok(None);
}
let session = Session::open(&self.sessions_dir, id)?;
let restored = session.load()?;
let agent = self.agent().with_session(session).with_history(restored);
let mut live = self.live.lock().expect("conversations lock");
let entry = live
.entry(id.to_string())
.or_insert_with(|| self.wrap(id.to_string(), agent));
Ok(Some(entry.clone()))
}
pub fn delete(&self, id: &str) -> Result<bool> {
if !valid_id(id) {
return Ok(false);
}
let mut live = self.live.lock().expect("conversations lock");
if live.get(id).is_some_and(|l| l.busy()) {
return Err(anyhow!("the conversation is answering; stop it first"));
}
let path = self.sessions_dir.join(format!("{id}.jsonl"));
if !path.exists() {
return Ok(false);
}
std::fs::remove_file(&path)?;
live.remove(id);
Ok(true)
}
fn agent(&self) -> Agent {
let workdir = &self.setup.workdir;
let notes = kjarni::agent::project_notes(workdir);
let config = AgentConfig {
max_steps: self.setup.max_steps,
workdir: Some(workdir.display().to_string()),
project_notes: notes.map(|n| n.text),
..Default::default()
};
let workspace = Arc::new(tools::Workspace::new(workdir));
let mut agent = Agent::new(
self.setup.model.clone(),
tools::builtin(workspace, self.setup.memory.clone()),
config,
);
if let Some(memory) = &self.setup.memory {
agent = agent.with_memory(memory.clone());
}
if self.setup.approve_all {
for access in [Access::Write, Access::Execute, Access::Network] {
agent.approve_access(access);
}
}
agent
}
fn wrap(&self, id: String, agent: Agent) -> Arc<Live> {
let (tx, _) = broadcast::channel(1024);
let transcript = transcript_of(&agent);
Arc::new(Live {
id,
agent: tokio::sync::Mutex::new(agent),
turn: Mutex::new(Turn {
busy: false,
events: Vec::new(),
pending: None,
task: None,
transcript,
}),
tx,
hub: self.hub.clone(),
})
}
}