anda_engine 0.16.5

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
use super::*;
use crate::engine::EngineBuilder;

fn input(id: &str, content: Option<&str>, status: Option<&str>) -> TodoItemInput {
    TodoItemInput {
        id: id.to_string(),
        content: content.map(ToString::to_string),
        status: status.map(ToString::to_string),
    }
}

fn mock_ctx() -> BaseCtx {
    EngineBuilder::new().mock_ctx().base
}

#[test]
fn set_dedupes_normalizes_and_preserves_order() {
    let mut store = TodoStore::default();

    let items = store
        .set(vec![
            input("1", Some("draft plan"), Some(TODO_STATUS_PENDING)),
            input("1", Some("final plan"), Some(TODO_STATUS_COMPLETED)),
        ])
        .unwrap();

    assert_eq!(
        items,
        vec![TodoItem {
            id: "1".to_string(),
            content: "final plan".to_string(),
            status: TODO_STATUS_COMPLETED.to_string(),
        }]
    );
}

#[test]
fn update_patches_existing_items_and_preserves_order() {
    let mut store = TodoStore::default();
    store
        .set(vec![
            input("1", Some("draft"), Some(TODO_STATUS_PENDING)),
            input("2", Some("implement"), Some(TODO_STATUS_PENDING)),
        ])
        .unwrap();

    let items = store
        .update(vec![
            input(
                "2",
                Some("implement todo tool"),
                Some(TODO_STATUS_IN_PROGRESS),
            ),
            input("3", Some("write tests"), Some(TODO_STATUS_PENDING)),
            input(
                "3",
                Some("write tests thoroughly"),
                Some(TODO_STATUS_COMPLETED),
            ),
        ])
        .unwrap();

    assert_eq!(
        items,
        vec![
            TodoItem {
                id: "1".to_string(),
                content: "draft".to_string(),
                status: TODO_STATUS_PENDING.to_string(),
            },
            TodoItem {
                id: "2".to_string(),
                content: "implement todo tool".to_string(),
                status: TODO_STATUS_IN_PROGRESS.to_string(),
            },
            TodoItem {
                id: "3".to_string(),
                content: "write tests thoroughly".to_string(),
                status: TODO_STATUS_COMPLETED.to_string(),
            },
        ]
    );
}

#[test]
fn injection_format_only_includes_active_items() {
    let mut store = TodoStore::default();
    store
        .set(vec![
            input("1", Some("plan"), Some(TODO_STATUS_PENDING)),
            input("2", Some("build"), Some(TODO_STATUS_IN_PROGRESS)),
            input("3", Some("done"), Some(TODO_STATUS_COMPLETED)),
            input("4", Some("skip"), Some(TODO_STATUS_CANCELLED)),
        ])
        .unwrap();

    let injected = store.format_for_injection().unwrap();
    assert!(injected.contains(TODO_ACTIVE_LIST_PREFIX));
    assert!(injected.contains("- [ ] 1. plan (pending)"));
    assert!(injected.contains("- [>] 2. build (in_progress)"));
    assert!(!injected.contains("done"));
    assert!(!injected.contains("skip"));
}

#[tokio::test]
async fn tool_call_persists_session_state() {
    let ctx = mock_ctx();
    let tool = TodoTool::new();

    let first = tool
        .call(
            ctx.clone(),
            TodoArgs {
                op: Some(TODO_OP_SET.to_string()),
                items: Some(vec![input("1", Some("plan"), Some(TODO_STATUS_PENDING))]),
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();
    assert_eq!(first.output.summary.total, 1);
    assert!(first.output.items.is_empty());
    assert!(todo_session(&ctx).has_items());

    let second = tool
        .call(ctx.clone(), TodoArgs::default(), Vec::new())
        .await
        .unwrap();
    assert_eq!(
        second.output.items,
        vec![TodoItem {
            id: "1".to_string(),
            content: "plan".to_string(),
            status: TODO_STATUS_PENDING.to_string(),
        }]
    );

    let third = tool
        .call(
            ctx.clone(),
            TodoArgs {
                op: Some(TODO_OP_UPDATE.to_string()),
                items: Some(vec![TodoItemInput {
                    id: "1".to_string(),
                    content: Some("plan carefully".to_string()),
                    status: None,
                }]),
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();

    assert_eq!(third.output.summary.pending, 1);
    assert!(third.output.items.is_empty());

    let fourth = tool
        .call(
            ctx.clone(),
            TodoArgs {
                op: Some(TODO_OP_READ.to_string()),
                items: None,
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();
    assert_eq!(fourth.output.items[0].content, "plan carefully");
}

#[tokio::test]
async fn session_state_persists_across_per_call_child_contexts() {
    // Mirror how the completion runner drives tools: a long-lived parent
    // context seeds the session, and each tool invocation runs on a fresh
    // `child_base` context that snapshot-copies parent state. Without the
    // seeded session each child would create its own empty store and writes
    // would be lost between calls.
    let parent = EngineBuilder::new().mock_ctx();
    parent.base.set_state(TodoSession::new());
    let tool = TodoTool::new();

    let write_ctx = parent.child_base("todo").unwrap();
    let first = tool
        .call(
            write_ctx,
            TodoArgs {
                op: Some(TODO_OP_SET.to_string()),
                items: Some(vec![input("1", Some("plan"), Some(TODO_STATUS_PENDING))]),
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();
    assert_eq!(first.output.summary.total, 1);

    // A distinct child context (as produced by a later tool call) must
    // observe the write performed by the previous one.
    let read_ctx = parent.child_base("todo").unwrap();
    let second = tool
        .call(
            read_ctx,
            TodoArgs {
                op: Some(TODO_OP_READ.to_string()),
                items: None,
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();
    assert_eq!(
        second.output.items,
        vec![TodoItem {
            id: "1".to_string(),
            content: "plan".to_string(),
            status: TODO_STATUS_PENDING.to_string(),
        }]
    );
}

#[test]
fn invalid_batches_leave_the_entire_list_unchanged() {
    let mut store = TodoStore::default();
    store
        .set(vec![input("old", Some("keep"), Some("completed"))])
        .unwrap();
    let before = store.snapshot();
    for bad in [
        input("", Some("bad"), None),
        input("bad", Some(""), None),
        input("bad", Some("new"), Some("done")),
        input("new", None, None),
    ] {
        assert!(
            store
                .update(vec![input("old", Some("changed"), None), bad.clone()])
                .is_err()
        );
        assert_eq!(store.snapshot(), before);
        assert!(store.set(vec![bad]).is_err());
        assert_eq!(store.snapshot(), before);
    }
    assert!(
        store
            .set(vec![
                input("old", None, None),
                input("old", Some("replacement"), None)
            ])
            .is_err()
    );
    assert_eq!(store.snapshot(), before);
    // Even a shadowed duplicate must validate.
    assert!(
        store
            .update(vec![
                input("old", None, Some("done")),
                input("old", None, Some("pending"))
            ])
            .is_err()
    );
    assert_eq!(store.snapshot(), before);
    store
        .update(vec![input(
            " old ",
            Some(" changed "),
            Some(" IN_PROGRESS "),
        )])
        .unwrap();
    assert_eq!(
        store.snapshot(),
        vec![TodoItem {
            id: "old".into(),
            content: "changed".into(),
            status: "in_progress".into()
        }]
    );
}

#[tokio::test]
async fn tool_rejects_missing_items_unknown_ops_and_invalid_statuses() {
    let ctx = mock_ctx();
    let session = todo_session(&ctx);
    let initial = session
        .set(vec![input("a", Some("keep"), Some("completed"))])
        .unwrap();
    let tool = TodoTool::new();
    for args in [
        serde_json::json!({"op":"set"}),
        serde_json::json!({"op":"set", "items":null}),
        serde_json::json!({"op":"update"}),
        serde_json::json!({"op":"typo"}),
        serde_json::json!({"op":"read", "items":[]}),
        serde_json::json!({"op":"update", "items":[{"id":"a","status":"done"}]}),
    ] {
        let result = tool.call_raw(ctx.clone(), args, vec![]).await.unwrap();
        assert_eq!(result.is_error, Some(true));
        assert!(result.output.get("error").is_some());
        assert_eq!(session.snapshot(), initial);
    }
    assert!(
        tool.call_raw(ctx.clone(), serde_json::json!({"operation":"set"}), vec![])
            .await
            .is_err()
    );
    assert!(
        tool.call_raw(
            ctx.clone(),
            serde_json::json!({"op":"set","items":[{"id":"a","content":"x","statuz":"pending"}]}),
            vec![]
        )
        .await
        .is_err()
    );
    let result = tool
        .call_raw(
            ctx.clone(),
            serde_json::json!({"op":"set","items":[]}),
            vec![],
        )
        .await
        .unwrap();
    assert_ne!(result.is_error, Some(true));
    assert!(session.snapshot().is_empty());
}

#[test]
fn task_limits_and_injection_are_bounded_for_unicode() {
    let mut store = TodoStore::default();
    store
        .set(
            (0..40)
                .map(|i| input(&i.to_string(), Some(&"中🙂".repeat(40)), None))
                .collect(),
        )
        .unwrap();
    let before = store.snapshot();
    let rendered = store.format_for_injection().unwrap();
    assert!(rendered.len() <= INJECTION_BYTES);
    assert!(rendered.contains("more active tasks omitted"));
    assert!(
        store
            .set(
                (0..257)
                    .map(|i| input(&i.to_string(), Some("x"), None))
                    .collect()
            )
            .is_err()
    );
    assert!(
        store
            .update(vec![input("0", Some(&"x".repeat(4097)), None)])
            .is_err()
    );
    assert_eq!(store.snapshot(), before);
    store
        .set(vec![input("a", Some("all done"), Some("completed"))])
        .unwrap();
    assert_eq!(store.format_for_injection(), None);
}

#[tokio::test]
async fn existing_hook_observes_explanation_and_committed_session() {
    use crate::hook::ToolHook;
    use async_trait::async_trait;
    type Observations = Arc<parking_lot::Mutex<Vec<(TodoOutput, Vec<TodoItem>)>>>;
    struct Observer(Observations);
    #[async_trait]
    impl ToolHook<TodoArgs, TodoOutput> for Observer {
        async fn after_tool_call(
            &self,
            ctx: &BaseCtx,
            output: ToolOutput<TodoOutput>,
        ) -> Result<ToolOutput<TodoOutput>, BoxError> {
            self.0
                .lock()
                .push((output.output.clone(), todo_session(ctx).snapshot()));
            Ok(output)
        }
    }
    let ctx = mock_ctx();
    let observed = Arc::new(parking_lot::Mutex::new(Vec::new()));
    ctx.set_state(TodoToolHook::new(Arc::new(Observer(observed.clone()))));
    let output = TodoTool::new()
        .call(
            ctx,
            TodoArgs {
                op: Some("set".into()),
                items: Some(vec![input("a", Some("implement"), None)]),
                explanation: Some("Split implementation from validation".into()),
            },
            vec![],
        )
        .await
        .unwrap();
    assert!(output.output.items.is_empty());
    let observed = observed.lock();
    assert_eq!(observed.len(), 1);
    assert_eq!(
        observed[0].0.explanation.as_deref(),
        Some("Split implementation from validation")
    );
    assert_eq!(observed[0].1[0].content, "implement");
}