vv-agent 0.6.2

VectorVein agent runtime, SDK, CLI, tools, and workspace backends
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
use super::*;

#[test]
fn runtime_seeds_skill_state_from_task_metadata() {
    let mut finish_args = BTreeMap::new();
    finish_args.insert("message".to_string(), json!("done"));
    let llm = ScriptedLlmClient::new(vec![LLMResponse::with_tool_calls(
        "finish",
        vec![ToolCall::new(
            "finish_skill_state",
            "task_finish",
            finish_args,
        )],
    )]);
    let runtime = AgentRuntime::new(llm);
    let mut task = AgentTask::new("skill_state", "demo", "system", "finish");
    task.metadata.insert(
        "available_skills".to_string(),
        json!([{"name": "demo", "description": "Demo skill"}]),
    );
    task.metadata
        .insert("active_skills".to_string(), json!(["already-active"]));

    let result = runtime.run(task).expect("run");

    assert_eq!(result.status, AgentStatus::Completed);
    assert_eq!(
        result.shared_state["available_skills"],
        json!([{"name": "demo", "description": "Demo skill"}])
    );
    assert_eq!(
        result.shared_state["active_skills"],
        json!(["already-active"])
    );
}

#[test]
fn runtime_keeps_initial_skill_state_over_task_metadata() {
    let mut finish_args = BTreeMap::new();
    finish_args.insert("message".to_string(), json!("done"));
    let llm = ScriptedLlmClient::new(vec![LLMResponse::with_tool_calls(
        "finish",
        vec![ToolCall::new(
            "finish_initial_skill_state",
            "task_finish",
            finish_args,
        )],
    )]);
    let runtime = AgentRuntime::new(llm);
    let mut task = AgentTask::new("initial_skill_state", "demo", "system", "finish");
    task.metadata.insert(
        "available_skills".to_string(),
        json!([{"name": "metadata-skill", "description": "Metadata skill"}]),
    );
    task.metadata
        .insert("active_skills".to_string(), json!(["metadata-active"]));
    task.initial_shared_state.insert(
        "available_skills".to_string(),
        json!([{"name": "state-skill", "description": "State skill"}]),
    );
    task.initial_shared_state
        .insert("active_skills".to_string(), json!(["state-active"]));

    let result = runtime.run(task).expect("run");

    assert_eq!(result.status, AgentStatus::Completed);
    assert_eq!(
        result.shared_state["available_skills"],
        json!([{"name": "state-skill", "description": "State skill"}])
    );
    assert_eq!(
        result.shared_state["active_skills"],
        json!(["state-active"])
    );
}

#[test]
fn runtime_can_poll_async_configured_sub_agent_status() {
    let mut sub_task_args = BTreeMap::new();
    sub_task_args.insert("agent_id".to_string(), json!("researcher"));
    sub_task_args.insert(
        "task_description".to_string(),
        json!("Collect async task facts"),
    );
    sub_task_args.insert("wait_for_completion".to_string(), json!(false));
    let llm = InspectingSubTaskStatusLlmClient::new(vec![LLMResponse::with_tool_calls(
        "",
        vec![ToolCall::new(
            "parent_async_sub_call",
            "create_sub_task",
            sub_task_args,
        )],
    )]);
    let inspector = llm.clone();
    let runtime = AgentRuntime::new(llm);
    let mut task = AgentTask::new("parent_async", "demo", "parent system", "delegate async");
    task.max_cycles = 50;
    task.sub_agents.insert(
        "researcher".to_string(),
        SubAgentConfig::new("demo", "research profile"),
    );

    let result = runtime.run(task).expect("run");

    assert_eq!(result.status, AgentStatus::Completed);
    assert_eq!(
        result.final_answer.as_deref(),
        Some("parent saw async child result")
    );
    assert!(inspector.status_payloads().iter().any(|payload| {
        payload["tasks"][0]["status"] == "completed"
            && payload["tasks"][0]["final_answer"] == "async child complete"
    }));
}

#[test]
fn runtime_can_continue_completed_async_sub_agent_session() {
    let mut sub_task_args = BTreeMap::new();
    sub_task_args.insert("agent_id".to_string(), json!("researcher"));
    sub_task_args.insert(
        "task_description".to_string(),
        json!("Collect async task facts"),
    );
    sub_task_args.insert("wait_for_completion".to_string(), json!(false));
    let llm = InspectingSubTaskContinuationLlmClient::new(vec![LLMResponse::with_tool_calls(
        "",
        vec![ToolCall::new(
            "parent_async_sub_call",
            "create_sub_task",
            sub_task_args,
        )],
    )]);
    let inspector = llm.clone();
    let runtime = AgentRuntime::new(llm);
    let mut task = AgentTask::new(
        "parent_async_continue",
        "demo",
        "parent system",
        "delegate async",
    );
    task.max_cycles = 50;
    task.sub_agents.insert(
        "researcher".to_string(),
        SubAgentConfig::new("demo", "research profile"),
    );

    let result = runtime.run(task).expect("run");

    assert_eq!(result.status, AgentStatus::Completed);
    assert_eq!(
        result.final_answer.as_deref(),
        Some("parent saw followed-up child result")
    );
    assert!(inspector.status_payloads().iter().any(|payload| {
        payload["interaction"]["action"] == "continued"
            && payload["tasks"][0]["final_answer"] == "follow-up child complete"
    }));
}
#[derive(Clone)]
struct InspectingSubTaskStatusLlmClient {
    responses: Arc<Mutex<VecDeque<LLMResponse>>>,
    status_payloads: Arc<Mutex<Vec<serde_json::Value>>>,
}

impl InspectingSubTaskStatusLlmClient {
    fn new(responses: Vec<LLMResponse>) -> Self {
        Self {
            responses: Arc::new(Mutex::new(VecDeque::from(responses))),
            status_payloads: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn status_payloads(&self) -> Vec<serde_json::Value> {
        self.status_payloads
            .lock()
            .expect("status payloads poisoned")
            .clone()
    }
}

impl LlmClient for InspectingSubTaskStatusLlmClient {
    fn complete(&self, request: LlmRequest) -> Result<LLMResponse, LlmError> {
        let is_child_request = request
            .messages
            .first()
            .is_some_and(|message| message.content.contains("research profile"));
        if is_child_request {
            return Ok(LLMResponse::with_tool_calls(
                "",
                vec![ToolCall::new(
                    "child_async_finish",
                    "task_finish",
                    BTreeMap::from([("message".to_string(), json!("async child complete"))]),
                )],
            ));
        }
        if !is_child_request {
            let latest_async_task_id = request
                .messages
                .iter()
                .rev()
                .filter_map(|message| {
                    if message.role != vv_agent::MessageRole::Tool
                        || message.tool_call_id.as_deref() != Some("parent_async_sub_call")
                    {
                        return None;
                    }
                    let payload: serde_json::Value = serde_json::from_str(&message.content).ok()?;
                    payload
                        .get("task_id")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                })
                .next();
            if let Some(task_id) = latest_async_task_id {
                if !request.messages.iter().any(|message| {
                    message.role == vv_agent::MessageRole::Tool
                        && message.tool_call_id.as_deref() == Some("parent_async_status")
                }) {
                    return Ok(LLMResponse::with_tool_calls(
                        "",
                        vec![ToolCall::new(
                            "parent_async_status",
                            "sub_task_status",
                            BTreeMap::from([
                                ("task_ids".to_string(), json!([task_id])),
                                ("detail_level".to_string(), json!("snapshot")),
                            ]),
                        )],
                    ));
                }
            }
        }

        let mut latest_status_payload = None;
        for message in &request.messages {
            if message.role == vv_agent::MessageRole::Tool
                && message.tool_call_id.as_deref() == Some("parent_async_status")
            {
                if let Ok(payload) = serde_json::from_str::<serde_json::Value>(&message.content) {
                    self.status_payloads
                        .lock()
                        .expect("status payloads poisoned")
                        .push(payload.clone());
                    latest_status_payload = Some(payload);
                }
            }
        }
        if let Some(payload) = latest_status_payload {
            let completed = payload["tasks"]
                .as_array()
                .and_then(|tasks| tasks.first())
                .is_some_and(|task| task["status"] == "completed");
            if completed {
                return Ok(LLMResponse::with_tool_calls(
                    "",
                    vec![ToolCall::new(
                        "parent_finish",
                        "task_finish",
                        BTreeMap::from([(
                            "message".to_string(),
                            json!("parent saw async child result"),
                        )]),
                    )],
                ));
            }
            if let Some(task_id) = payload["tasks"]
                .as_array()
                .and_then(|tasks| tasks.first())
                .and_then(|task| task["task_id"].as_str())
            {
                std::thread::sleep(std::time::Duration::from_millis(10));
                return Ok(LLMResponse::with_tool_calls(
                    "",
                    vec![ToolCall::new(
                        "parent_async_status",
                        "sub_task_status",
                        BTreeMap::from([
                            ("task_ids".to_string(), json!([task_id])),
                            ("detail_level".to_string(), json!("snapshot")),
                        ]),
                    )],
                ));
            }
        }

        self.responses
            .lock()
            .map_err(|_| LlmError::Request("inspector poisoned".to_string()))?
            .pop_front()
            .ok_or(LlmError::ScriptExhausted)
    }
}

#[derive(Clone)]
struct InspectingSubTaskContinuationLlmClient {
    responses: Arc<Mutex<VecDeque<LLMResponse>>>,
    status_payloads: Arc<Mutex<Vec<serde_json::Value>>>,
}

impl InspectingSubTaskContinuationLlmClient {
    fn new(responses: Vec<LLMResponse>) -> Self {
        Self {
            responses: Arc::new(Mutex::new(VecDeque::from(responses))),
            status_payloads: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn status_payloads(&self) -> Vec<serde_json::Value> {
        self.status_payloads
            .lock()
            .expect("status payloads poisoned")
            .clone()
    }
}

impl LlmClient for InspectingSubTaskContinuationLlmClient {
    fn complete(&self, request: LlmRequest) -> Result<LLMResponse, LlmError> {
        let is_child_request = request
            .messages
            .first()
            .is_some_and(|message| message.content.contains("research profile"));
        if is_child_request {
            let is_follow_up = request.messages.iter().any(|message| {
                message.role == vv_agent::MessageRole::User
                    && message.content.contains("Add appendix")
            });
            let message = if is_follow_up {
                "follow-up child complete"
            } else {
                "initial child complete"
            };
            return Ok(LLMResponse::with_tool_calls(
                "",
                vec![ToolCall::new(
                    if is_follow_up {
                        "child_follow_up_finish"
                    } else {
                        "child_initial_finish"
                    },
                    "task_finish",
                    BTreeMap::from([("message".to_string(), json!(message))]),
                )],
            ));
        }

        let latest_create_task_id = request
            .messages
            .iter()
            .rev()
            .filter_map(|message| {
                if message.role != vv_agent::MessageRole::Tool
                    || message.tool_call_id.as_deref() != Some("parent_async_sub_call")
                {
                    return None;
                }
                let payload: serde_json::Value = serde_json::from_str(&message.content).ok()?;
                payload
                    .get("task_id")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string)
            })
            .next();

        if let Some(task_id) = latest_create_task_id {
            let mut latest_status_payload = None;
            let mut saw_continue_result = false;
            for message in &request.messages {
                if message.role != vv_agent::MessageRole::Tool {
                    continue;
                }
                if message.tool_call_id.as_deref() == Some("parent_async_status")
                    || message.tool_call_id.as_deref() == Some("parent_async_continue")
                {
                    if let Ok(payload) = serde_json::from_str::<serde_json::Value>(&message.content)
                    {
                        self.status_payloads
                            .lock()
                            .expect("status payloads poisoned")
                            .push(payload.clone());
                        if message.tool_call_id.as_deref() == Some("parent_async_continue") {
                            saw_continue_result = true;
                        }
                        latest_status_payload = Some(payload);
                    }
                }
            }

            if saw_continue_result {
                let follow_up_complete = latest_status_payload.as_ref().is_some_and(|payload| {
                    payload["tasks"][0]["status"] == "completed"
                        && payload["tasks"][0]["final_answer"] == "follow-up child complete"
                });
                return Ok(LLMResponse::with_tool_calls(
                    "",
                    vec![ToolCall::new(
                        "parent_finish",
                        "task_finish",
                        BTreeMap::from([(
                            "message".to_string(),
                            json!(if follow_up_complete {
                                "parent saw followed-up child result"
                            } else {
                                "parent saw follow-up failure"
                            }),
                        )]),
                    )],
                ));
            }

            if let Some(payload) = latest_status_payload {
                let completed = payload["tasks"]
                    .as_array()
                    .and_then(|tasks| tasks.first())
                    .is_some_and(|task| task["status"] == "completed");
                if completed {
                    return Ok(LLMResponse::with_tool_calls(
                        "",
                        vec![ToolCall::new(
                            "parent_async_continue",
                            "sub_task_status",
                            BTreeMap::from([
                                ("task_ids".to_string(), json!([task_id])),
                                ("detail_level".to_string(), json!("snapshot")),
                                ("message".to_string(), json!("Add appendix")),
                                ("wait_for_response".to_string(), json!(true)),
                            ]),
                        )],
                    ));
                }
            }

            std::thread::sleep(std::time::Duration::from_millis(10));
            return Ok(LLMResponse::with_tool_calls(
                "",
                vec![ToolCall::new(
                    "parent_async_status",
                    "sub_task_status",
                    BTreeMap::from([
                        ("task_ids".to_string(), json!([task_id])),
                        ("detail_level".to_string(), json!("snapshot")),
                    ]),
                )],
            ));
        }

        self.responses
            .lock()
            .map_err(|_| LlmError::Request("inspector poisoned".to_string()))?
            .pop_front()
            .ok_or(LlmError::ScriptExhausted)
    }
}