ai-agent 0.88.0

Idiomatic agent sdk inspired by the claude code source leak
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
// Source: ~/claudecode/openclaudecode/src/tools/TaskCreateTool/TaskCreateTool.ts
// Source: ~/claudecode/openclaudecode/src/tools/TaskGetTool/TaskGetTool.ts
// Source: ~/claudecode/openclaudecode/src/tools/TaskUpdateTool/TaskUpdateTool.ts
// Source: ~/claudecode/openclaudecode/src/tools/TaskListTool/TaskListTool.ts
//! Task management tools (V2).
//!
//! Provides tools for creating, listing, updating, and getting tasks.

use crate::error::AgentError;
use crate::types::*;
use std::collections::HashMap;
use std::sync::{
    Mutex, OnceLock,
    atomic::{AtomicU64, Ordering},
};

pub const TASK_CREATE_TOOL_NAME: &str = "TaskCreate";
pub const TASK_GET_TOOL_NAME: &str = "TaskGet";
pub const TASK_LIST_TOOL_NAME: &str = "TaskList";
pub const TASK_UPDATE_TOOL_NAME: &str = "TaskUpdate";

/// Global task store
static TASKS: OnceLock<Mutex<HashMap<String, Task>>> = OnceLock::new();
static TASK_COUNTER: AtomicU64 = AtomicU64::new(1);

fn get_tasks_map() -> &'static Mutex<HashMap<String, Task>> {
    TASKS.get_or_init(|| Mutex::new(HashMap::new()))
}

pub fn reset_task_store() {
    let mut guard = get_tasks_map().lock().unwrap();
    guard.clear();
    drop(guard);
    TASK_COUNTER.store(1, Ordering::SeqCst);
}

/// Test-only lock that serializes concurrent tests using the task store.
/// Prevents race conditions when multiple tests run in parallel.
#[cfg(test)]
pub fn get_test_lock() -> &'static Mutex<()> {
    use std::sync::Mutex as StdMutex;
    static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| StdMutex::new(()))
}

/// Get all non-completed, non-deleted tasks.
pub fn get_unfinished_tasks() -> Vec<Task> {
    let guard = get_tasks_map().lock().unwrap();
    guard
        .values()
        .filter(|t| t.status != "completed" && t.status != "deleted")
        .cloned()
        .collect()
}

/// Get all tasks (including deleted and internal).
pub fn get_all_tasks() -> Vec<Task> {
    let guard = get_tasks_map().lock().unwrap();
    guard.values().cloned().collect()
}

fn next_task_id() -> String {
    let id = TASK_COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("task-{}", id)
}

/// A task in the V2 task system
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Task {
    pub id: String,
    pub subject: String,
    pub description: String,
    pub status: String, // pending, in_progress, completed, deleted
    #[serde(rename = "activeForm")]
    pub active_form: Option<String>,
    pub owner: Option<String>,
    pub blocks: Vec<String>,     // task IDs this task blocks
    pub blocked_by: Vec<String>, // task IDs that block this task
    #[serde(rename = "_internal")]
    pub internal: Option<bool>,
}

impl Task {
    fn new(id: String, subject: String, description: String, active_form: Option<String>) -> Self {
        Self {
            id,
            subject,
            description,
            status: "pending".to_string(),
            active_form,
            owner: None,
            blocks: vec![],
            blocked_by: vec![],
            internal: None,
        }
    }
}

/// TaskCreate tool - create a new task
pub struct TaskCreateTool;

impl TaskCreateTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TASK_CREATE_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Create a new task in the task list. Tasks can be tracked with status and can block other tasks."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TaskCreate".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["subject"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        content["content"].as_str().map(|s| s.to_string())
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "subject": {
                    "type": "string",
                    "description": "A brief title for the task"
                },
                "description": {
                    "type": "string",
                    "description": "What needs to be done"
                },
                "activeForm": {
                    "type": "string",
                    "description": "Present continuous form shown in spinner when in_progress"
                }
            }),
            required: Some(vec!["subject".to_string(), "description".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let subject = input["subject"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("subject is required".to_string()))?
            .to_string();

        let description = input["description"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("description is required".to_string()))?
            .to_string();

        let active_form = input["activeForm"].as_str().map(|s| s.to_string());

        let id = next_task_id();
        let task = Task::new(
            id.clone(),
            subject.clone(),
            description.clone(),
            active_form.clone(),
        );

        let mut guard = get_tasks_map().lock().unwrap();
        guard.insert(id.clone(), task);
        drop(guard);

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!(
                "Task created: {}\nSubject: {}\nID: {}",
                id,
                subject.clone(),
                id
            ),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TaskCreateTool {
    fn default() -> Self {
        Self::new()
    }
}

/// TaskList tool - list all tasks
pub struct TaskListTool;

impl TaskListTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TASK_LIST_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "List all tasks in the task list. Shows task ID, subject, status, and blocking information."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TaskList".to_string()
    }

    pub fn get_tool_use_summary(&self, _input: Option<&serde_json::Value>) -> Option<String> {
        None
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        let text = content["content"].as_str()?;
        let lines = text.lines().count();
        Some(format!("{} lines", lines))
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({}),
            required: None,
        }
    }

    pub async fn execute(
        &self,
        _input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let guard = get_tasks_map().lock().unwrap();

        // Filter out internal tasks (matching TS)
        let tasks: Vec<&Task> = guard
            .values()
            .filter(|t| t.internal != Some(true) && t.status != "deleted")
            .collect();

        if tasks.is_empty() {
            return Ok(ToolResult {
                result_type: "text".to_string(),
                tool_use_id: "".to_string(),
                content: "No tasks.".to_string(),
                is_error: None,
                was_persisted: None,
            });
        }

        let lines: Vec<String> = tasks
            .iter()
            .map(|t| {
                let blocking_note = if !t.blocks.is_empty() {
                    format!(" (blocks: {})", t.blocks.join(", "))
                } else {
                    String::new()
                };
                let owner_note = if let Some(owner) = &t.owner {
                    format!(" [{}]", owner)
                } else {
                    String::new()
                };
                format!(
                    "{}. {} [{}] - {}{}{}",
                    t.id,
                    t.subject,
                    t.status,
                    t.active_form.as_deref().unwrap_or(""),
                    owner_note,
                    blocking_note
                )
            })
            .collect();

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!("Tasks:\n{}", lines.join("\n")),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TaskListTool {
    fn default() -> Self {
        Self::new()
    }
}

/// TaskUpdate tool - update a task
pub struct TaskUpdateTool;

impl TaskUpdateTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TASK_UPDATE_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Update an existing task's status, subject, description, or other fields."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TaskUpdate".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["taskId"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        content["content"].as_str().map(|s| s.to_string())
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "taskId": {
                    "type": "string",
                    "description": "The ID of the task to update"
                },
                "subject": {
                    "type": "string",
                    "description": "New subject for the task"
                },
                "description": {
                    "type": "string",
                    "description": "New description for the task"
                },
                "status": {
                    "type": "string",
                    "enum": ["pending", "in_progress", "completed", "deleted"],
                    "description": "New status for the task"
                },
                "activeForm": {
                    "type": "string",
                    "description": "New active form"
                },
                "owner": {
                    "type": "string",
                    "description": "New owner for the task"
                },
                "blocks": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Task IDs that this task blocks"
                },
                "blockedBy": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Task IDs that block this task"
                }
            }),
            required: Some(vec!["taskId".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let task_id = input["taskId"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("taskId is required".to_string()))?;

        let mut guard = get_tasks_map().lock().unwrap();
        let task = guard
            .get_mut(task_id)
            .ok_or_else(|| AgentError::Tool(format!("Task '{}' not found", task_id)))?;

        let mut changes: Vec<String> = Vec::new();

        let old_status = task.status.clone();

        if let Some(subject) = input["subject"].as_str() {
            task.subject = subject.to_string();
            changes.push("subject".to_string());
        }
        if let Some(description) = input["description"].as_str() {
            task.description = description.to_string();
            changes.push("description".to_string());
        }
        if let Some(status) = input["status"].as_str() {
            task.status = status.to_string();
            changes.push(format!("status: {} -> {}", old_status, status));
        }
        if let Some(active_form) = input["activeForm"].as_str() {
            task.active_form = Some(active_form.to_string());
            changes.push("activeForm".to_string());
        }
        if let Some(owner) = input["owner"].as_str() {
            task.owner = Some(owner.to_string());
            changes.push(format!("owner -> {}", owner));
        }
        if let Some(blocks) = input["blocks"].as_array() {
            task.blocks = blocks
                .iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect();
            changes.push("blocks".to_string());
        }
        if let Some(blocked_by) = input["blockedBy"].as_array() {
            task.blocked_by = blocked_by
                .iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect();
            changes.push("blockedBy".to_string());
        }

        drop(guard);

        let changes_str = if changes.is_empty() {
            "no changes".to_string()
        } else {
            changes.join(", ")
        };

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content: format!("Task {} updated: {}", task_id, changes_str),
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TaskUpdateTool {
    fn default() -> Self {
        Self::new()
    }
}

/// TaskGet tool - get a specific task
pub struct TaskGetTool;

impl TaskGetTool {
    pub fn new() -> Self {
        Self
    }

    pub fn name(&self) -> &str {
        TASK_GET_TOOL_NAME
    }

    pub fn description(&self) -> &str {
        "Get details of a specific task by ID."
    }

    pub fn user_facing_name(&self, _input: Option<&serde_json::Value>) -> String {
        "TaskGet".to_string()
    }

    pub fn get_tool_use_summary(&self, input: Option<&serde_json::Value>) -> Option<String> {
        input.and_then(|inp| inp["taskId"].as_str().map(String::from))
    }

    pub fn render_tool_result_message(
        &self,
        content: &serde_json::Value,
    ) -> Option<String> {
        let text = content["content"].as_str()?;
        let lines = text.lines().count();
        Some(format!("{} lines", lines))
    }

    pub fn input_schema(&self) -> ToolInputSchema {
        ToolInputSchema {
            schema_type: "object".to_string(),
            properties: serde_json::json!({
                "taskId": {
                    "type": "string",
                    "description": "The ID of the task to retrieve"
                }
            }),
            required: Some(vec!["taskId".to_string()]),
        }
    }

    pub async fn execute(
        &self,
        input: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<ToolResult, AgentError> {
        let task_id = input["taskId"]
            .as_str()
            .ok_or_else(|| AgentError::Tool("taskId is required".to_string()))?;

        let guard = get_tasks_map().lock().unwrap();
        let task = guard
            .get(task_id)
            .ok_or_else(|| AgentError::Tool(format!("Task '{}' not found", task_id)))?;

        let content = serde_json::to_string_pretty(&serde_json::json!({
            "id": task.id,
            "subject": task.subject,
            "description": task.description,
            "status": task.status,
            "activeForm": task.active_form,
            "owner": task.owner,
            "blocks": task.blocks,
            "blockedBy": task.blocked_by
        }))
        .unwrap_or_default();

        Ok(ToolResult {
            result_type: "text".to_string(),
            tool_use_id: "".to_string(),
            content,
            is_error: Some(false),
            was_persisted: None,
        })
    }
}

impl Default for TaskGetTool {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_setup() -> std::sync::MutexGuard<'static, ()> {
        let _lock = get_test_lock().lock().unwrap();
        reset_task_store();
        _lock
    }

    #[tokio::test]
    async fn test_task_create_and_get() {
        let _lock = test_setup();

        let create = TaskCreateTool::new();
        let result = create
            .execute(
                serde_json::json!({
                    "subject": "Test Task",
                    "description": "A test task",
                    "activeForm": "Testing"
                }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());

        // Extract the task ID from the create result (format: "ID: task-N")
        let content = result.unwrap().content;
        let task_id = content
            .lines()
            .find(|l| l.starts_with("ID: "))
            .unwrap()
            .strip_prefix("ID: ")
            .unwrap()
            .trim()
            .to_string();

        let get = TaskGetTool::new();
        let get_result = get
            .execute(
                serde_json::json!({ "taskId": task_id }),
                &ToolContext::default(),
            )
            .await;
        assert!(get_result.is_ok());
        let content = get_result.unwrap().content;
        assert!(content.contains("Test Task"));
    }

    #[tokio::test]
    async fn test_task_list() {
        let _lock = test_setup();

        let create = TaskCreateTool::new();
        create
            .execute(
                serde_json::json!({ "subject": "Task A", "description": "Desc A" }),
                &ToolContext::default(),
            )
            .await
            .unwrap();

        let list = TaskListTool::new();
        let result = list
            .execute(serde_json::json!({}), &ToolContext::default())
            .await;
        assert!(result.is_ok());
        assert!(result.unwrap().content.contains("Task A"));
    }

    #[tokio::test]
    async fn test_task_update_status() {
        let _lock = test_setup();

        let update = TaskUpdateTool::new();
        let result = update
            .execute(
                serde_json::json!({
                    "taskId": "task-1",
                    "status": "in_progress"
                }),
                &ToolContext::default(),
            )
            .await;
        // task-1 doesn't exist yet after reset, so create it first
        let create = TaskCreateTool::new();
        let create_result = create
            .execute(
                serde_json::json!({
                    "subject": "Update Me",
                    "description": "To be updated"
                }),
                &ToolContext::default(),
            )
            .await
            .unwrap();
        let task_id = create_result
            .content
            .lines()
            .find(|l| l.starts_with("ID: "))
            .unwrap()
            .strip_prefix("ID: ")
            .unwrap()
            .trim()
            .to_string();

        let result = update
            .execute(
                serde_json::json!({
                    "taskId": task_id,
                    "status": "in_progress"
                }),
                &ToolContext::default(),
            )
            .await;
        assert!(result.is_ok());

        let get = TaskGetTool::new();
        let get_result = get
            .execute(
                serde_json::json!({ "taskId": task_id }),
                &ToolContext::default(),
            )
            .await;
        assert!(get_result.unwrap().content.contains("in_progress"));
    }
}