Skip to main content

lean_ctx/tools/
ctx_task.rs

1use crate::core::a2a::task::{TaskPart, TaskState, TaskStore};
2
3pub fn handle(
4    action: &str,
5    current_agent_id: Option<&str>,
6    task_id: Option<&str>,
7    to_agent: Option<&str>,
8    description: Option<&str>,
9    state: Option<&str>,
10    message: Option<&str>,
11) -> String {
12    let agent = match current_agent_id {
13        Some(id) => id,
14        None if action == "list" || action == "info" => "unknown",
15        None => {
16            return "Error: agent must be registered first (use ctx_agent action=register)"
17                .to_string();
18        }
19    };
20
21    let path = match TaskStore::default_path() {
22        Ok(path) => path,
23        Err(error) => return format!("Error: task storage unavailable: {error}"),
24    };
25    TaskStore::mutate_locked(&path, |store| {
26        store.cleanup_old(72);
27        Ok(match action {
28            "create" => handle_create(store, agent, to_agent, description),
29            "update" => handle_update(store, agent, task_id, state, message),
30            "list" => handle_list(store, agent),
31            "get" => handle_get(store, task_id),
32            "cancel" => handle_cancel(store, agent, task_id, message),
33            "message" => handle_message(store, agent, task_id, message),
34            "info" => handle_info(store),
35            _ => format!(
36                "Unknown action '{action}'. Available: create, update, list, get, cancel, message, info"
37            ),
38        })
39    })
40    .unwrap_or_else(|error: std::io::Error| format!("Error: task storage unavailable: {error}"))
41}
42
43fn handle_create(
44    store: &mut TaskStore,
45    from: &str,
46    to: Option<&str>,
47    desc: Option<&str>,
48) -> String {
49    let Some(to_agent) = to else {
50        return "Error: to_agent is required for task creation".to_string();
51    };
52    let description = desc.unwrap_or("(no description)");
53    let id = store.create_task(from, to_agent, description);
54    format!("Task created: {id}\n  From: {from}\n  To: {to_agent}\n  Description: {description}")
55}
56
57fn handle_update(
58    store: &mut TaskStore,
59    agent: &str,
60    task_id: Option<&str>,
61    state: Option<&str>,
62    message: Option<&str>,
63) -> String {
64    let Some(tid) = task_id else {
65        return "Error: task_id is required".to_string();
66    };
67    let new_state = match state {
68        Some(s) => match TaskState::parse_str(s) {
69            Some(st) => st,
70            None => {
71                return format!(
72                    "Error: invalid state '{s}'. Use: working, input-required, completed, failed, canceled"
73                );
74            }
75        },
76        None => return "Error: state is required for update".to_string(),
77    };
78
79    let Some(task) = store.get_task_mut(tid) else {
80        return format!("Error: task '{tid}' not found");
81    };
82
83    if task.to_agent != agent && task.from_agent != agent {
84        return format!("Error: agent '{agent}' is not involved in task '{tid}'");
85    }
86
87    match task.transition(new_state.clone(), message) {
88        Ok(()) => {
89            if let Some(msg) = message {
90                task.add_message(
91                    agent,
92                    vec![TaskPart::Text {
93                        text: msg.to_string(),
94                    }],
95                );
96            }
97            format!(
98                "Task {tid} updated → {new_state}\n  History: {} transitions",
99                task.history.len()
100            )
101        }
102        Err(e) => format!("Error: {e}"),
103    }
104}
105
106fn handle_list(store: &TaskStore, agent: &str) -> String {
107    let tasks = store.tasks_for_agent(agent);
108    if tasks.is_empty() {
109        return "No tasks found for this agent.".to_string();
110    }
111
112    let mut lines = vec![format!("Tasks ({}):", tasks.len())];
113    for task in &tasks {
114        let direction = if task.from_agent == agent {
115            format!("→ {}", task.to_agent)
116        } else {
117            format!("← {}", task.from_agent)
118        };
119        lines.push(format!(
120            "  {} [{}] {} — {}",
121            task.id, task.state, direction, task.description
122        ));
123    }
124
125    let pending = store.pending_tasks_for(agent);
126    if !pending.is_empty() {
127        lines.push(format!(
128            "\n{} pending task(s) assigned to you.",
129            pending.len()
130        ));
131    }
132
133    lines.join("\n")
134}
135
136fn handle_get(store: &TaskStore, task_id: Option<&str>) -> String {
137    let Some(tid) = task_id else {
138        return "Error: task_id is required".to_string();
139    };
140    let Some(task) = store.get_task(tid) else {
141        return format!("Error: task '{tid}' not found");
142    };
143
144    let mut lines = vec![
145        format!("Task: {}", task.id),
146        format!("  State: {}", task.state),
147        format!("  From: {}", task.from_agent),
148        format!("  To: {}", task.to_agent),
149        format!("  Description: {}", task.description),
150        format!("  Created: {}", task.created_at),
151        format!("  Updated: {}", task.updated_at),
152        format!("  Messages: {}", task.messages.len()),
153        format!("  Artifacts: {}", task.artifacts.len()),
154    ];
155
156    if !task.history.is_empty() {
157        lines.push("  History:".to_string());
158        for t in &task.history {
159            lines.push(format!(
160                "    {} → {} ({})",
161                t.from,
162                t.to,
163                t.reason.as_deref().unwrap_or("-")
164            ));
165        }
166    }
167
168    lines.join("\n")
169}
170
171fn handle_cancel(
172    store: &mut TaskStore,
173    agent: &str,
174    task_id: Option<&str>,
175    reason: Option<&str>,
176) -> String {
177    let Some(tid) = task_id else {
178        return "Error: task_id is required".to_string();
179    };
180    let Some(task) = store.get_task_mut(tid) else {
181        return format!("Error: task '{tid}' not found");
182    };
183
184    if task.from_agent != agent {
185        return format!(
186            "Error: only the task creator can cancel (creator: {})",
187            task.from_agent
188        );
189    }
190
191    match task.transition(TaskState::Canceled, reason) {
192        Ok(()) => format!("Task {tid} canceled."),
193        Err(e) => format!("Error: {e}"),
194    }
195}
196
197fn handle_message(
198    store: &mut TaskStore,
199    agent: &str,
200    task_id: Option<&str>,
201    message: Option<&str>,
202) -> String {
203    let Some(tid) = task_id else {
204        return "Error: task_id is required".to_string();
205    };
206    let Some(msg) = message else {
207        return "Error: message is required".to_string();
208    };
209    let Some(task) = store.get_task_mut(tid) else {
210        return format!("Error: task '{tid}' not found");
211    };
212
213    task.add_message(
214        agent,
215        vec![TaskPart::Text {
216            text: msg.to_string(),
217        }],
218    );
219    format!(
220        "Message added to task {tid} ({} messages total)",
221        task.messages.len()
222    )
223}
224
225fn handle_info(store: &TaskStore) -> String {
226    let total = store.tasks.len();
227    let active = store
228        .tasks
229        .iter()
230        .filter(|t| !t.state.is_terminal())
231        .count();
232    let completed = store
233        .tasks
234        .iter()
235        .filter(|t| t.state == TaskState::Completed)
236        .count();
237    let failed = store
238        .tasks
239        .iter()
240        .filter(|t| t.state == TaskState::Failed)
241        .count();
242
243    format!("Task Store: {total} total, {active} active, {completed} completed, {failed} failed")
244}