lingshu-tools 0.10.0

Tool registry, ToolHandler trait, and 50+ tool implementations
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
//! # todo — Task checklist management
//!
//! WHY todo: Lets the agent track multi-step plans visibly. Mirrors
//! hermes-agent's `manage_todo_list` tool.
//!
//! ## Stateful design (TodoStore)
//!
//! A `TodoStore` instance is created once per conversation and shared
//! (via `Arc`) into every tool execution via `ToolContext.todo_store`.
//! This means the list survives context compression — after compression,
//! `format_for_injection()` re-injects active items into the conversation
//! so the model never loses its task plan.
//!
//! WHY server-side state over relying on the LLM: After compression the
//! LLM's view of the todo list disappears. Hoisting the list out of the
//! conversation context makes it reliably available on every turn.

use std::sync::Mutex;

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;

use lingshu_types::{ToolError, ToolSchema};

use crate::registry::{ToolContext, ToolHandler};

pub struct TodoTool;

// ─── Domain types ─────────────────────────────────────────────────────

#[derive(Debug, Clone, Deserialize)]
pub struct TodoItem {
    pub id: u32,
    pub title: String,
    pub status: String, // "not-started" | "in-progress" | "completed" | "blocked" | "cancelled"
}

#[derive(Deserialize)]
struct Args {
    /// Full todo list to write. Omit to read the current list.
    #[serde(default)]
    items: Option<Vec<TodoItem>>,
    /// Hermes-compatible todo payload shape.
    #[serde(default)]
    todos: Option<Vec<HermesTodoItem>>,
    /// true → update existing items by id, append new ones.
    /// false (default) → replace the entire list.
    #[serde(default)]
    merge: Option<bool>,
}

#[derive(Deserialize)]
struct HermesTodoItem {
    id: String,
    content: String,
    status: String,
}

fn status_from_hermes(status: &str) -> &str {
    match status {
        "pending" => "not-started",
        "in_progress" => "in-progress",
        "completed" => "completed",
        "cancelled" => "cancelled",
        _ => "not-started",
    }
}

fn stable_todo_id(raw: &str) -> u32 {
    if let Ok(parsed) = raw.parse::<u32>() {
        return parsed;
    }

    let mut hash: u32 = 2166136261;
    for byte in raw.as_bytes() {
        hash ^= u32::from(*byte);
        hash = hash.wrapping_mul(16777619);
    }
    hash.max(1)
}

fn normalize_items(args: &Args) -> Option<Vec<TodoItem>> {
    args.items.clone().or_else(|| {
        args.todos.as_ref().map(|todos| {
            todos
                .iter()
                .map(|item| TodoItem {
                    id: stable_todo_id(&item.id),
                    title: item.content.clone(),
                    status: status_from_hermes(&item.status).to_string(),
                })
                .collect()
        })
    })
}

// ─── TodoStore ────────────────────────────────────────────────────────

/// Per-session in-memory task list, safe for concurrent access.
///
/// WHY Arc<TodoStore> not Arc<Mutex<Vec>>: The Mutex lives inside the
/// store, so callers can share `Arc<TodoStore>` without a separate
/// wrapping `Mutex`. Each method handles its own locking.
pub struct TodoStore {
    items: Mutex<Vec<TodoItem>>,
}

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

impl TodoStore {
    pub fn new() -> Self {
        Self {
            items: Mutex::new(Vec::new()),
        }
    }

    /// Replace the entire list with `new_items`.
    pub fn write(&self, new_items: Vec<TodoItem>) {
        *self.items.lock().expect("todo store mutex poisoned") = new_items;
    }

    /// Update existing items by id, append items with unknown ids.
    ///
    /// WHY merge mode: Allows the agent to update a single status without
    /// re-passing the full list, reducing token usage.
    pub fn merge_items(&self, updates: Vec<TodoItem>) {
        let mut guard = self.items.lock().expect("todo store mutex poisoned");
        for update in updates {
            if let Some(existing) = guard.iter_mut().find(|i| i.id == update.id) {
                *existing = update;
            } else {
                guard.push(update);
            }
        }
    }

    /// Return a snapshot of the current list.
    pub fn read(&self) -> Vec<TodoItem> {
        self.items
            .lock()
            .expect("todo store mutex poisoned")
            .clone()
    }

    /// True if the store contains any items.
    pub fn has_items(&self) -> bool {
        !self
            .items
            .lock()
            .expect("todo store mutex poisoned")
            .is_empty()
    }

    /// Produce active items for re-injection after context compression.
    ///
    /// WHY only active items: Re-injecting completed/cancelled items
    /// causes the model to re-do finished work. Narrowing to "not-started"
    /// and "in-progress" gives the model exactly what it needs to continue.
    /// Blocked items are also injected so the model sees the unresolved dependency.
    ///
    /// Returns None when there are no active items (nothing to inject).
    pub fn format_for_injection(&self) -> Option<String> {
        let guard = self.items.lock().expect("todo store mutex poisoned");
        let active: Vec<&TodoItem> = guard
            .iter()
            .filter(|i| {
                i.status == "not-started" || i.status == "in-progress" || i.status == "blocked"
            })
            .collect();
        if active.is_empty() {
            return None;
        }
        let mut lines =
            vec!["[Your active task list was preserved across context compression]".to_string()];
        for item in active {
            let marker = if item.status == "in-progress" {
                "[>]"
            } else if item.status == "blocked" {
                "[!]"
            } else {
                "[ ]"
            };
            lines.push(format!(
                "- {} {}. {} ({})",
                marker, item.id, item.title, item.status
            ));
        }
        Some(lines.join("\n"))
    }
}

#[async_trait]
impl ToolHandler for TodoTool {
    fn name(&self) -> &'static str {
        "manage_todo_list"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &["todo"]
    }

    fn toolset(&self) -> &'static str {
        "meta"
    }

    fn emoji(&self) -> &'static str {
        "📝"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "manage_todo_list".into(),
            description: "Manage your task list for the current session. Use for complex tasks \
                          with 3+ steps or when the user provides multiple tasks. \
                          Call with no parameters (omit 'items') to read the current list.\n\n\
                          Writing:\n\
                          - Provide 'items' array to create/update items\n\
                          - merge=false (default): replace the entire list with a fresh plan\n\
                          - merge=true: update existing items by id, add any new ones\n\n\
                          Each item: {id: integer, title: string, \
                          status: not-started|in-progress|completed|blocked|cancelled}\n\
                          Use `blocked` when a dependency, approval, or user input is still required.\n\
                          Hermes-compatible calls using `todo` with `todos`, `content`, and \
                          pending|in_progress statuses are also accepted.\n\
                          Only ONE item in-progress at a time. \
                          Mark items completed immediately when done.\n\n\
                          Always returns the full current list."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "items": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "id": { "type": "integer" },
                                "title": { "type": "string" },
                                "status": {
                                    "type": "string",
                                    "enum": ["not-started", "in-progress", "completed", "blocked", "cancelled"]
                                }
                            },
                            "required": ["id", "title", "status"]
                        },
                        "description": "Complete array of todo items to write. Omit to read the current list."
                    },
                    "merge": {
                        "type": "boolean",
                        "description": "true: update existing items by id, add new ones. false (default): replace entire list.",
                        "default": false
                    }
                },
                "required": []
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: Args = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "manage_todo_list".into(),
            message: e.to_string(),
        })?;
        let normalized_items = normalize_items(&args);

        if let Some(store) = &ctx.todo_store {
            // ── Stateful path: use per-session TodoStore ──────────────────
            if let Some(mut raw_items) = normalized_items {
                // Normalize statuses before writing.
                for item in &mut raw_items {
                    normalize_status(item);
                }
                if args.merge.unwrap_or(false) {
                    store.merge_items(raw_items);
                } else {
                    store.write(raw_items);
                }
            }
            // Read back full list (whether we just wrote or not)
            let items = store.read();
            format_response(items)
        } else {
            // ── Stateless fallback (tests, minimal contexts without a store) ──
            let raw_items = normalized_items.unwrap_or_default();
            let items: Vec<TodoItem> = raw_items
                .into_iter()
                .map(|mut i| {
                    normalize_status(&mut i);
                    i
                })
                .collect();
            format_response(items)
        }
    }

    fn parallel_safe(&self) -> bool {
        false // state mutation
    }
}

/// Build the JSON response for a todo list snapshot — single source of truth
/// used by both the stateful and stateless paths.
///
/// WHY extracted: DRY — both the store path and the stateless fallback
/// need identical output formatting.
fn format_response(items: Vec<TodoItem>) -> Result<String, ToolError> {
    let total = items.len();
    let not_started = items.iter().filter(|i| i.status == "not-started").count();
    let in_progress = items.iter().filter(|i| i.status == "in-progress").count();
    let completed = items.iter().filter(|i| i.status == "completed").count();
    let blocked = items.iter().filter(|i| i.status == "blocked").count();
    let cancelled = items.iter().filter(|i| i.status == "cancelled").count();

    let todos: Vec<serde_json::Value> = items
        .iter()
        .map(|i| json!({"id": i.id, "title": i.title, "status": i.status}))
        .collect();

    let result = json!({
        "todos": todos,
        "summary": {
            "total": total,
            "not_started": not_started,
            "in_progress": in_progress,
            "completed": completed,
            "blocked": blocked,
            "cancelled": cancelled
        }
    });

    Ok(serde_json::to_string(&result).expect("json serialization is infallible"))
}

fn normalize_status(item: &mut TodoItem) {
    // Accept "pending" as a hermes-agent compatibility alias for "not-started".
    if item.status == "pending"
        || !matches!(
            item.status.as_str(),
            "not-started" | "in-progress" | "completed" | "blocked" | "cancelled"
        )
    {
        item.status = "not-started".to_string();
    }
}

inventory::submit!(&TodoTool as &dyn ToolHandler);

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

    fn make_item(id: u32, title: &str, status: &str) -> TodoItem {
        TodoItem {
            id,
            title: title.to_string(),
            status: status.to_string(),
        }
    }

    // ── TodoStore unit tests ───────────────────────────────────────────

    #[test]
    fn store_write_and_read() {
        let store = TodoStore::new();
        store.write(vec![
            make_item(1, "Task A", "not-started"),
            make_item(2, "Task B", "in-progress"),
        ]);
        let items = store.read();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].title, "Task A");
        assert_eq!(items[1].status, "in-progress");
    }

    #[test]
    fn store_write_replaces_all() {
        let store = TodoStore::new();
        store.write(vec![make_item(1, "Old", "not-started")]);
        store.write(vec![make_item(2, "New", "completed")]);
        let items = store.read();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].title, "New");
    }

    #[test]
    fn store_merge_updates_existing_appends_new() {
        let store = TodoStore::new();
        store.write(vec![
            make_item(1, "Task A", "not-started"),
            make_item(2, "Task B", "not-started"),
        ]);
        store.merge_items(vec![
            make_item(1, "Task A", "completed"),   // update existing
            make_item(3, "Task C", "in-progress"), // append new
        ]);
        let items = store.read();
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].status, "completed", "Task A should be updated");
        assert_eq!(items[1].status, "not-started", "Task B unchanged");
        assert_eq!(items[2].title, "Task C", "Task C appended");
    }

    #[test]
    fn normalize_items_accepts_hermes_shape() {
        let args = Args {
            items: None,
            todos: Some(vec![HermesTodoItem {
                id: "plan-step-1".into(),
                content: "Inspect the bug".into(),
                status: "in_progress".into(),
            }]),
            merge: Some(true),
        };
        let items = normalize_items(&args).expect("compat items");
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].title, "Inspect the bug");
        assert_eq!(items[0].status, "in-progress");
        assert_ne!(items[0].id, 0);
    }

    #[test]
    fn store_format_for_injection_active_only() {
        let store = TodoStore::new();
        store.write(vec![
            make_item(1, "Done task", "completed"),
            make_item(2, "Active task", "in-progress"),
            make_item(3, "Pending task", "not-started"),
            make_item(4, "Cancelled", "cancelled"),
        ]);
        let injection = store
            .format_for_injection()
            .expect("should have active items");
        assert!(injection.contains("[>] 2. Active task"));
        assert!(injection.contains("[ ] 3. Pending task"));
        assert!(
            !injection.contains("Done task"),
            "completed items must not be injected"
        );
        assert!(
            !injection.contains("Cancelled"),
            "cancelled items must not be injected"
        );
    }

    #[test]
    fn store_format_for_injection_none_when_all_done() {
        let store = TodoStore::new();
        store.write(vec![
            make_item(1, "Done", "completed"),
            make_item(2, "Also done", "cancelled"),
        ]);
        assert!(store.format_for_injection().is_none());
    }

    #[test]
    fn store_format_for_injection_none_when_empty() {
        let store = TodoStore::new();
        assert!(store.format_for_injection().is_none());
    }

    #[test]
    fn store_has_items() {
        let store = TodoStore::new();
        assert!(!store.has_items());
        store.write(vec![make_item(1, "T", "not-started")]);
        assert!(store.has_items());
    }

    // ── Tool integration tests ─────────────────────────────────────────

    #[tokio::test]
    async fn todo_renders_list() {
        let ctx = ToolContext::test_context();
        let result = TodoTool
            .execute(
                json!({
                    "items": [
                        {"id": 1, "title": "First task", "status": "completed"},
                        {"id": 2, "title": "Second task", "status": "in-progress"},
                        {"id": 3, "title": "Third task", "status": "not-started"}
                    ]
                }),
                &ctx,
            )
            .await
            .expect("ok");

        let v: serde_json::Value = serde_json::from_str(&result).expect("valid json");
        assert_eq!(v["summary"]["total"], 3);
        assert_eq!(v["summary"]["completed"], 1);
        assert_eq!(v["summary"]["in_progress"], 1);
        assert_eq!(v["summary"]["not_started"], 1);
        assert_eq!(v["summary"]["cancelled"], 0);
        let todos = v["todos"].as_array().expect("array");
        assert_eq!(todos[0]["status"], "completed");
        assert_eq!(todos[1]["status"], "in-progress");
        assert_eq!(todos[2]["status"], "not-started");
    }

    #[tokio::test]
    async fn todo_cancelled_status() {
        let ctx = ToolContext::test_context();
        let result = TodoTool
            .execute(
                json!({
                    "items": [
                        {"id": 1, "title": "Done", "status": "completed"},
                        {"id": 2, "title": "Skipped", "status": "cancelled"}
                    ]
                }),
                &ctx,
            )
            .await
            .expect("ok");

        let v: serde_json::Value = serde_json::from_str(&result).expect("valid json");
        assert_eq!(v["summary"]["cancelled"], 1);
        assert_eq!(v["summary"]["completed"], 1);
        assert_eq!(v["summary"]["total"], 2);
    }

    #[tokio::test]
    async fn todo_unknown_status_normalized() {
        let ctx = ToolContext::test_context();
        let result = TodoTool
            .execute(
                json!({
                    "items": [
                        {"id": 1, "title": "Task A", "status": "weird-status"}
                    ]
                }),
                &ctx,
            )
            .await
            .expect("ok");

        let v: serde_json::Value = serde_json::from_str(&result).expect("valid json");
        let todos = v["todos"].as_array().expect("array");
        assert_eq!(
            todos[0]["status"], "not-started",
            "Unknown status should be coerced to not-started"
        );
        assert_eq!(v["summary"]["not_started"], 1);
    }

    #[tokio::test]
    async fn todo_read_only_with_store() {
        let mut ctx = ToolContext::test_context();
        let store = Arc::new(TodoStore::new());
        store.write(vec![make_item(1, "Prepopulated", "in-progress")]);
        ctx.todo_store = Some(store);

        // No "items" key — read-only call
        let result = TodoTool.execute(json!({}), &ctx).await.expect("ok");

        let v: serde_json::Value = serde_json::from_str(&result).expect("valid json");
        assert_eq!(v["summary"]["total"], 1);
        assert_eq!(v["todos"][0]["title"], "Prepopulated");
    }

    #[tokio::test]
    async fn todo_merge_mode_with_store() {
        let mut ctx = ToolContext::test_context();
        let store = Arc::new(TodoStore::new());
        store.write(vec![
            make_item(1, "Task A", "not-started"),
            make_item(2, "Task B", "not-started"),
        ]);
        ctx.todo_store = Some(store);

        // Merge: only update id=1, leave id=2 untouched
        let result = TodoTool
            .execute(
                json!({
                    "items": [{"id": 1, "title": "Task A", "status": "completed"}],
                    "merge": true
                }),
                &ctx,
            )
            .await
            .expect("ok");

        let v: serde_json::Value = serde_json::from_str(&result).expect("valid json");
        assert_eq!(v["summary"]["total"], 2, "merge should not remove Task B");
        assert_eq!(v["todos"][0]["status"], "completed");
        assert_eq!(v["todos"][1]["status"], "not-started");
    }
}