git_iris/agents/tools/
workspace.rs

1//! Iris workspace tool for Rig
2//!
3//! This tool provides Iris with her own personal workspace for taking notes,
4//! creating task lists, and managing her workflow during complex operations.
5
6use anyhow::Result;
7use rig::completion::ToolDefinition;
8use rig::tool::Tool;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use std::sync::{Arc, Mutex};
12
13use super::common::parameters_schema;
14
15// Use standard tool error macro for consistency
16crate::define_tool_error!(WorkspaceError);
17
18/// Workspace tool for Iris's note-taking and task management
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Workspace {
21    #[serde(skip)]
22    data: Arc<Mutex<WorkspaceData>>,
23}
24
25#[derive(Debug, Default)]
26struct WorkspaceData {
27    notes: Vec<String>,
28    tasks: Vec<WorkspaceTask>,
29}
30
31#[derive(Debug, Clone)]
32struct WorkspaceTask {
33    description: String,
34    status: TaskStatus,
35    priority: TaskPriority,
36}
37
38/// Workspace action type
39#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, Default)]
40#[serde(rename_all = "snake_case")]
41pub enum WorkspaceAction {
42    /// Add a note to the workspace
43    AddNote,
44    /// Add a task to track
45    AddTask,
46    /// Update an existing task's status
47    UpdateTask,
48    /// Get summary of notes and tasks
49    #[default]
50    GetSummary,
51}
52
53/// Task priority level
54#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, Default)]
55#[serde(rename_all = "lowercase")]
56pub enum TaskPriority {
57    Low,
58    #[default]
59    Medium,
60    High,
61    Critical,
62}
63
64/// Task status
65#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, Default)]
66#[serde(rename_all = "snake_case")]
67pub enum TaskStatus {
68    #[default]
69    Pending,
70    InProgress,
71    Completed,
72    Blocked,
73}
74
75impl std::fmt::Display for TaskStatus {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            TaskStatus::Pending => write!(f, "pending"),
79            TaskStatus::InProgress => write!(f, "in_progress"),
80            TaskStatus::Completed => write!(f, "completed"),
81            TaskStatus::Blocked => write!(f, "blocked"),
82        }
83    }
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
87pub struct WorkspaceArgs {
88    /// Action to perform
89    pub action: WorkspaceAction,
90    /// Content for note or task description
91    #[serde(default)]
92    pub content: Option<String>,
93    /// Priority level for tasks
94    #[serde(default)]
95    pub priority: Option<TaskPriority>,
96    /// Index of task to update (0-based)
97    #[serde(default)]
98    pub task_index: Option<usize>,
99    /// New status for task updates
100    #[serde(default)]
101    pub status: Option<TaskStatus>,
102}
103
104impl Default for Workspace {
105    fn default() -> Self {
106        Self::new()
107    }
108}
109
110impl Workspace {
111    pub fn new() -> Self {
112        Self {
113            data: Arc::new(Mutex::new(WorkspaceData::default())),
114        }
115    }
116}
117
118impl Tool for Workspace {
119    const NAME: &'static str = "workspace";
120    type Error = WorkspaceError;
121    type Args = WorkspaceArgs;
122    type Output = String;
123
124    async fn definition(&self, _: String) -> ToolDefinition {
125        ToolDefinition {
126            name: "workspace".to_string(),
127            description: "Iris's personal workspace for notes and task management. Use this to track progress, take notes on findings, and manage complex workflows.".to_string(),
128            parameters: parameters_schema::<WorkspaceArgs>(),
129        }
130    }
131
132    async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error> {
133        let mut data = self
134            .data
135            .lock()
136            .map_err(|e| WorkspaceError(e.to_string()))?;
137
138        let result = match args.action {
139            WorkspaceAction::AddNote => {
140                let content = args
141                    .content
142                    .ok_or_else(|| WorkspaceError("Content required for add_note".to_string()))?;
143                data.notes.push(content);
144                json!({
145                    "success": true,
146                    "message": "Note added successfully",
147                    "note_count": data.notes.len()
148                })
149            }
150            WorkspaceAction::AddTask => {
151                let content = args
152                    .content
153                    .ok_or_else(|| WorkspaceError("Content required for add_task".to_string()))?;
154                let priority = args.priority.unwrap_or_default();
155
156                data.tasks.push(WorkspaceTask {
157                    description: content,
158                    status: TaskStatus::Pending,
159                    priority,
160                });
161
162                json!({
163                    "success": true,
164                    "message": "Task added successfully",
165                    "task_count": data.tasks.len()
166                })
167            }
168            WorkspaceAction::UpdateTask => {
169                let task_index = args.task_index.ok_or_else(|| {
170                    WorkspaceError("task_index required for update_task".to_string())
171                })?;
172                let status = args
173                    .status
174                    .ok_or_else(|| WorkspaceError("status required for update_task".to_string()))?;
175
176                if task_index >= data.tasks.len() {
177                    return Err(WorkspaceError(format!(
178                        "Task index {task_index} out of range"
179                    )));
180                }
181
182                data.tasks[task_index].status = status.clone();
183
184                json!({
185                    "success": true,
186                    "message": format!("Task {} updated to {}", task_index, status),
187                })
188            }
189            WorkspaceAction::GetSummary => {
190                let pending = data
191                    .tasks
192                    .iter()
193                    .filter(|t| matches!(t.status, TaskStatus::Pending))
194                    .count();
195                let in_progress = data
196                    .tasks
197                    .iter()
198                    .filter(|t| matches!(t.status, TaskStatus::InProgress))
199                    .count();
200                let completed = data
201                    .tasks
202                    .iter()
203                    .filter(|t| matches!(t.status, TaskStatus::Completed))
204                    .count();
205
206                json!({
207                    "notes_count": data.notes.len(),
208                    "tasks": {
209                        "total": data.tasks.len(),
210                        "pending": pending,
211                        "in_progress": in_progress,
212                        "completed": completed
213                    },
214                    "recent_notes": data.notes.iter().rev().take(3).collect::<Vec<_>>(),
215                    "active_tasks": data.tasks.iter()
216                        .filter(|t| !matches!(t.status, TaskStatus::Completed))
217                        .map(|t| json!({
218                            "description": t.description,
219                            "status": t.status.to_string(),
220                            "priority": format!("{:?}", t.priority).to_lowercase()
221                        }))
222                        .collect::<Vec<_>>()
223                })
224            }
225        };
226
227        serde_json::to_string_pretty(&result).map_err(|e| WorkspaceError(e.to_string()))
228    }
229}