use super::goal::{GoalAction, GoalError, GoalView, TurnOrigin};
use super::ledger::SessionLedger;
use super::task::{RunningStatus, RunningTask, TaskInfo, TaskType, TodoItem};
use crate::interface::exec::ExecProviders;
use crate::permission::PermissionMode;
use crate::tool::Tool;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
#[derive(Debug, Clone, Copy)]
pub struct ReadRecord<'a> {
pub path: &'a Path,
pub offset: Option<usize>,
pub limit: Option<usize>,
pub tool_use_id: &'a str,
pub cut_short: bool,
}
impl<'a> ReadRecord<'a> {
pub fn whole(path: &'a Path, tool_use_id: &'a str) -> Self {
Self {
path,
offset: None,
limit: None,
tool_use_id,
cut_short: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeldRead {
Whole,
CutShort,
}
#[derive(Debug, Clone, Default)]
pub struct SessionEnv {
pub cwd: PathBuf,
pub refusal_rule_roots: Vec<PathBuf>,
pub additional_writable_dirs: Vec<PathBuf>,
pub read_directories: Vec<PathBuf>,
pub read_anywhere: bool,
pub cache_directories: Vec<PathBuf>,
pub unattended: bool,
pub base_mode: PermissionMode,
pub skill_dirs: LiveDirs,
pub protected_dirs: LiveDirs,
}
#[derive(Debug, Clone, Default)]
pub struct LiveDirs(Arc<std::sync::RwLock<Vec<PathBuf>>>);
impl LiveDirs {
pub fn get(&self) -> Vec<PathBuf> {
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub fn set(&self, dirs: Vec<PathBuf>) {
*self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = dirs;
}
pub fn extend(&self, dirs: impl IntoIterator<Item = PathBuf>) {
let mut held = self
.0
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for dir in dirs {
if !held.contains(&dir) {
held.push(dir);
}
}
}
pub fn holding(&self, path: &Path) -> Option<PathBuf> {
self.0
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.find(|dir| path.starts_with(dir))
.cloned()
}
}
impl SessionEnv {
pub fn new(cwd: PathBuf) -> Self {
Self {
cwd,
..Self::default()
}
}
}
pub const SESSION_STATE_NS: &str = "agix.session_state";
pub const SESSION_STATE_EVENT: &str = "change";
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DurableState {
#[serde(default)]
pub plan: Option<PlanState>,
#[serde(default)]
pub todos: Vec<TodoItem>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub activated_tools: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PlanState {
pub exit_to: Option<PermissionMode>,
}
pub trait Session: Send + Sync + std::fmt::Debug {
fn env(&self) -> Arc<SessionEnv>;
fn exec(&self) -> Option<ExecProviders>;
fn tool(&self, name: &str) -> Option<Arc<dyn Tool>>;
fn permission_mode(&self) -> PermissionMode;
fn set_permission_mode(&self, mode: PermissionMode);
fn enter_plan_mode(&self);
fn exit_plan_mode(&self) -> PermissionMode;
fn host_permission_mode(&self) -> Option<PermissionMode>;
fn model_choice(&self) -> Option<String>;
fn register_task(
&self,
task_id: String,
task_type: TaskType,
cancel: CancellationToken,
detail: serde_json::Value,
) -> Arc<RunningTask>;
fn finish_task(&self, task_id: &str, status: RunningStatus);
fn find_running_task(&self, task_id: &str) -> Option<Arc<RunningTask>>;
fn cancel_running_task(&self, task_id: &str) -> bool;
fn running_background_task_ids(&self) -> Vec<String>;
fn task_infos(&self) -> Vec<TaskInfo>;
fn post_notice(&self, key: Option<String>, text: String);
fn retract_notice(&self, key: &str) -> bool;
fn take_notices(&self) -> Vec<String>;
fn record_read(&self, read: ReadRecord<'_>);
fn record_write(&self, path: &Path);
fn check_read_staleness(&self, path: &Path) -> Option<&'static str>;
fn check_read_dedup_with_range(
&self,
path: &Path,
offset: Option<usize>,
limit: Option<usize>,
) -> Option<HeldRead>;
fn is_consecutive_read(&self, path: &Path) -> bool;
fn todos(&self) -> Vec<TodoItem>;
fn set_todos(&self, items: Vec<TodoItem>);
fn activated_tools(&self) -> HashSet<String>;
fn activate_tools(&self, names: Vec<String>);
fn ledger(&self) -> std::sync::MutexGuard<'_, SessionLedger>;
fn goal_view(&self) -> Option<GoalView>;
fn goal_create(
&self,
objective: String,
limits: super::goal::GoalLimits,
origin: TurnOrigin,
) -> Result<GoalView, GoalError>;
fn goal_update(
&self,
goal_id: &str,
revision: u64,
action: GoalAction,
origin: TurnOrigin,
max_rounds_limit: u32,
) -> Result<GoalView, GoalError>;
}
pub fn stop_with_notice(
session: &dyn Session,
task: &RunningTask,
notice: impl FnOnce(&RunningTask) -> String,
) {
task.cancel.cancel();
if !task.claim_end() {
return;
}
if !task.has_ended() {
session.post_notice(Some(task.task_id.clone()), notice(task));
}
session.cancel_running_task(&task.task_id);
}
pub struct TaskScope {
session: Arc<dyn Session>,
task: Arc<RunningTask>,
}
impl TaskScope {
pub fn new(
session: Arc<dyn Session>,
task_id: impl Into<String>,
task_type: TaskType,
cancel: tokio_util::sync::CancellationToken,
detail: serde_json::Value,
) -> Self {
let task = session.register_task(task_id.into(), task_type, cancel, detail);
Self { session, task }
}
pub fn task(&self) -> &Arc<RunningTask> {
&self.task
}
}
impl Drop for TaskScope {
fn drop(&mut self) {
let status = if self.task.cancel.is_cancelled() {
RunningStatus::Cancelled
} else {
RunningStatus::Completed
};
self.session.finish_task(&self.task.task_id, status);
}
}
pub struct TaskLease {
session: Arc<dyn Session>,
task: Arc<RunningTask>,
stopped_notice: Option<StoppedNotice>,
concluded: bool,
}
type StoppedNotice = Box<dyn Fn(&RunningTask) -> String + Send + Sync>;
impl TaskLease {
pub fn new(
session: Arc<dyn Session>,
task_id: impl Into<String>,
task_type: TaskType,
cancel: tokio_util::sync::CancellationToken,
detail: serde_json::Value,
) -> Self {
let task = session.register_task(task_id.into(), task_type, cancel, detail);
Self {
session,
task,
stopped_notice: None,
concluded: false,
}
}
pub fn notifying(
mut self,
notice: impl Fn(&RunningTask) -> String + Send + Sync + 'static,
) -> Self {
self.stopped_notice = Some(Box::new(notice));
self
}
pub fn task(&self) -> &Arc<RunningTask> {
&self.task
}
pub fn conclude(mut self, status: RunningStatus, notice: Option<String>) {
self.concluded = true;
if !self.task.claim_end() {
return;
}
if let Some(notice) = notice.filter(|_| !self.task.has_ended()) {
self.session
.post_notice(Some(self.task.task_id.clone()), notice);
}
self.session.finish_task(&self.task.task_id, status);
}
}
impl Drop for TaskLease {
fn drop(&mut self) {
if self.concluded || !self.task.claim_end() {
return;
}
if let Some(notice) = self.stopped_notice.as_ref() {
if !self.task.has_ended() {
self.session
.post_notice(Some(self.task.task_id.clone()), notice(&self.task));
}
}
self.session
.finish_task(&self.task.task_id, RunningStatus::Cancelled);
}
}