swink-agent-patterns 0.9.0

Multi-agent pipeline patterns for swink-agent
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
//! Loop pipeline execution.

use std::sync::Arc;
use std::time::Instant;

use swink_agent::{AgentMessage, AgentResult, ContentBlock, LlmMessage, Usage};
use tokio_util::sync::CancellationToken;

use super::events::PipelineEvent;
use super::executor::AgentFactory;
use super::output::{PipelineError, PipelineOutput, StepResult};
use super::types::{ExitCondition, PipelineId};

/// Execute a loop pipeline: run the body agent repeatedly until an exit condition
/// is met or `max_iterations` is reached.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_loop(
    factory: &Arc<dyn AgentFactory>,
    event_handler: &Option<Arc<dyn Fn(PipelineEvent) + Send + Sync>>,
    id: PipelineId,
    _name: String,
    body: String,
    exit_condition: ExitCondition,
    max_iterations: usize,
    input: String,
    cancellation_token: CancellationToken,
) -> Result<PipelineOutput, PipelineError> {
    let pipeline_start = Instant::now();
    let mut steps: Vec<StepResult> = Vec::new();
    let mut total_usage = Usage::default();
    let mut accumulated_responses: Vec<String> = Vec::new();

    for iteration in 0..max_iterations {
        // Check cancellation before each iteration.
        if cancellation_token.is_cancelled() {
            return Err(PipelineError::Cancelled);
        }

        // Emit step-started event.
        if let Some(handler) = event_handler {
            handler(PipelineEvent::StepStarted {
                pipeline_id: id.clone(),
                step_index: iteration,
                agent_name: body.clone(),
            });
        }

        let step_start = Instant::now();

        // Create a fresh agent for this iteration.
        let mut agent = factory.create(&body)?;

        // Build input messages: original input + accumulated context from prior iterations.
        let mut messages = Vec::new();
        if accumulated_responses.is_empty() {
            messages.push(make_user_message(&input));
        } else {
            let context = format!(
                "{}\n\nPrevious iterations:\n{}",
                input,
                accumulated_responses
                    .iter()
                    .enumerate()
                    .map(|(i, r)| format!("Iteration {}: {}", i + 1, r))
                    .collect::<Vec<_>>()
                    .join("\n")
            );
            messages.push(make_user_message(&context));
        }

        // Run the agent.
        let result = agent
            .prompt_async(messages)
            .await
            .map_err(|e| PipelineError::StepFailed {
                step_index: iteration,
                agent_name: body.clone(),
                source: Box::new(e),
            })?;

        let step_duration = step_start.elapsed();
        let response_text = extract_text(&result);

        // Accumulate usage.
        total_usage.merge(&result.usage);

        // Record step result.
        let step = StepResult {
            agent_name: body.clone(),
            response: response_text.clone(),
            duration: step_duration,
            usage: result.usage.clone(),
        };
        steps.push(step);

        // Emit step-completed event.
        if let Some(handler) = event_handler {
            handler(PipelineEvent::StepCompleted {
                pipeline_id: id.clone(),
                step_index: iteration,
                agent_name: body.clone(),
                duration: step_duration,
                usage: result.usage.clone(),
            });
        }

        accumulated_responses.push(response_text.clone());

        // Check exit condition.
        let should_exit = match &exit_condition {
            ExitCondition::ToolCalled { tool_name } => check_tool_called(&result, tool_name),
            ExitCondition::OutputContains { compiled, .. } => compiled.is_match(&response_text),
            ExitCondition::MaxIterations => false, // Never triggers early exit.
        };

        if should_exit {
            let total_duration = pipeline_start.elapsed();
            if let Some(handler) = event_handler {
                handler(PipelineEvent::Completed {
                    pipeline_id: id.clone(),
                    total_duration,
                    total_usage: total_usage.clone(),
                });
            }
            return Ok(PipelineOutput {
                pipeline_id: id,
                final_response: response_text,
                steps,
                total_duration,
                total_usage,
            });
        }
    }

    // All iterations exhausted.
    match exit_condition {
        ExitCondition::MaxIterations => {
            // MaxIterations exit condition: success after running all iterations.
            let total_duration = pipeline_start.elapsed();
            let final_response = accumulated_responses.last().cloned().unwrap_or_default();
            if let Some(handler) = event_handler {
                handler(PipelineEvent::Completed {
                    pipeline_id: id.clone(),
                    total_duration,
                    total_usage: total_usage.clone(),
                });
            }
            Ok(PipelineOutput {
                pipeline_id: id,
                final_response,
                steps,
                total_duration,
                total_usage,
            })
        }
        _ => Err(PipelineError::MaxIterationsReached {
            iterations: max_iterations,
        }),
    }
}

/// Extract the text response from the last assistant message in an `AgentResult`.
fn extract_text(result: &AgentResult) -> String {
    result
        .messages
        .iter()
        .rev()
        .find_map(|m| match m {
            AgentMessage::Llm(LlmMessage::Assistant(msg)) => Some(msg),
            _ => None,
        })
        .map(|msg| {
            msg.content
                .iter()
                .filter_map(|b| match b {
                    ContentBlock::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("")
        })
        .unwrap_or_default()
}

/// Check whether the agent result contains a tool call with the given name.
fn check_tool_called(result: &AgentResult, tool_name: &str) -> bool {
    result.messages.iter().any(|m| match m {
        AgentMessage::Llm(LlmMessage::Assistant(msg)) => msg
            .content
            .iter()
            .any(|b| matches!(b, ContentBlock::ToolCall { name, .. } if name == tool_name)),
        _ => false,
    })
}

/// Build a user message from plain text.
fn make_user_message(text: &str) -> AgentMessage {
    AgentMessage::Llm(LlmMessage::User(swink_agent::UserMessage {
        content: vec![ContentBlock::Text {
            text: text.to_string(),
        }],
        timestamp: 0,
        cache_hint: None,
    }))
}

#[cfg(all(test, feature = "testkit"))]
mod tests {
    use super::*;
    use std::sync::Arc;

    use swink_agent::AgentOptions;
    use swink_agent::testing::{
        MockStreamFn, default_convert, default_model, text_events, tool_call_events,
    };

    use crate::pipeline::executor::SimpleAgentFactory;

    /// Build a factory that creates agents returning the given event sequences.
    fn factory_with_responses(
        name: &str,
        responses: Vec<Vec<swink_agent::AssistantMessageEvent>>,
    ) -> Arc<SimpleAgentFactory> {
        let name = name.to_string();
        let responses = Arc::new(std::sync::Mutex::new(responses));
        let mut factory = SimpleAgentFactory::new();
        factory.register(name, move || {
            // Pop the first response set for each agent creation.
            let next = {
                let mut guard = responses.lock().unwrap();
                if guard.is_empty() {
                    vec![]
                } else {
                    vec![guard.remove(0)]
                }
            };
            let options = AgentOptions::new(
                "loop-body",
                default_model(),
                Arc::new(MockStreamFn::new(next)),
                default_convert,
            );
            Agent::new(options)
        });
        Arc::new(factory)
    }

    use swink_agent::Agent;

    // T038: ToolCalled exit — mock returns tool call on iteration 2
    #[tokio::test]
    async fn loop_exits_on_tool_called() {
        let factory = factory_with_responses(
            "body",
            vec![
                text_events("iteration 1 output"),
                tool_call_events("tc-1", "done", "{}"),
            ],
        );

        let result = run_loop(
            &(factory as Arc<dyn AgentFactory>),
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            ExitCondition::ToolCalled {
                tool_name: "done".to_string(),
            },
            10,
            "do something".to_string(),
            CancellationToken::new(),
        )
        .await;

        let output = result.expect("should succeed");
        assert_eq!(output.steps.len(), 2);
        // First step has text, second triggered the tool call exit.
        assert!(!output.steps[0].response.is_empty());
    }

    // T039: OutputContains exit — mock returns "DONE" on iteration 2, regex matches
    #[tokio::test]
    async fn loop_exits_on_output_contains() {
        let factory = factory_with_responses(
            "body",
            vec![
                text_events("still working..."),
                text_events("all finished DONE"),
            ],
        );

        let exit_cond = ExitCondition::output_contains(r"DONE").unwrap();

        let result = run_loop(
            &(factory as Arc<dyn AgentFactory>),
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            exit_cond,
            10,
            "process data".to_string(),
            CancellationToken::new(),
        )
        .await;

        let output = result.expect("should succeed");
        assert_eq!(output.steps.len(), 2);
        assert!(output.steps[1].response.contains("DONE"));
    }

    // T040: MaxIterationsReached — exit condition never met
    #[tokio::test]
    async fn loop_errors_when_max_iterations_reached() {
        let factory = factory_with_responses(
            "body",
            vec![
                text_events("iter 1"),
                text_events("iter 2"),
                text_events("iter 3"),
            ],
        );

        let exit_cond = ExitCondition::output_contains(r"NEVER_MATCHES").unwrap();

        let result = run_loop(
            &(factory as Arc<dyn AgentFactory>),
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            exit_cond,
            3,
            "input".to_string(),
            CancellationToken::new(),
        )
        .await;

        match result {
            Err(PipelineError::MaxIterationsReached { iterations }) => {
                assert_eq!(iterations, 3);
            }
            other => panic!("expected MaxIterationsReached, got: {other:?}"),
        }
    }

    // T041: Body agent error halts loop
    #[tokio::test]
    async fn loop_halts_on_agent_error() {
        // Body agent not registered → AgentNotFound on first iteration.
        let factory: Arc<dyn AgentFactory> = Arc::new(SimpleAgentFactory::new());

        let result = run_loop(
            &factory,
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            ExitCondition::MaxIterations,
            5,
            "input".to_string(),
            CancellationToken::new(),
        )
        .await;

        assert!(
            matches!(result, Err(PipelineError::AgentNotFound { .. })),
            "expected AgentNotFound, got: {result:?}"
        );
    }

    // T042: Context accumulates across iterations
    #[tokio::test]
    async fn loop_accumulates_context() {
        // Use a context-capturing approach: we verify that the factory is called
        // 3 times (one per iteration) and each step records the response.
        let factory = factory_with_responses(
            "body",
            vec![
                text_events("response A"),
                text_events("response B"),
                text_events("response C DONE"),
            ],
        );

        let exit_cond = ExitCondition::output_contains(r"DONE").unwrap();

        let result = run_loop(
            &(factory as Arc<dyn AgentFactory>),
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            exit_cond,
            10,
            "original input".to_string(),
            CancellationToken::new(),
        )
        .await;

        let output = result.expect("should succeed");
        assert_eq!(output.steps.len(), 3);
        assert_eq!(output.steps[0].response, "response A");
        assert_eq!(output.steps[1].response, "response B");
        assert!(output.steps[2].response.contains("DONE"));
    }

    // T043: MaxIterations exit condition runs to cap successfully
    #[tokio::test]
    async fn loop_max_iterations_exit_condition_succeeds() {
        let factory = factory_with_responses(
            "body",
            vec![
                text_events("iter 1"),
                text_events("iter 2"),
                text_events("iter 3"),
            ],
        );

        let result = run_loop(
            &(factory as Arc<dyn AgentFactory>),
            &None,
            PipelineId::new("test-loop"),
            "test".to_string(),
            "body".to_string(),
            ExitCondition::MaxIterations,
            3,
            "input".to_string(),
            CancellationToken::new(),
        )
        .await;

        let output = result.expect("MaxIterations should succeed after running all iterations");
        assert_eq!(output.steps.len(), 3);
        assert_eq!(output.final_response, "iter 3");
    }
}